"""Shared LLM tool-schema definitions for both agent loops. ``scheduler/worker.py`` (the sync, OpenAI-compatible loop) and ``backends/copilot.py`` (the async Copilot SDK loop) each define their own JSON-schema-style tool descriptions for the same ~15 tools, in two different wire formats. This module is the single source of truth: canonical entries as ``(name, description, properties, required)`` tuples (the shape ``copilot.py`` already used internally), a shared ``build_tool_schemas`` filter, and one adapter per wire format each loop actually needs. Filtering note: ``copilot.py`` already excluded mutating tools for a read-only task, ``run_verification`` for a mutating task, and the evidence-reading tools when no evidence roots are configured for the task. ``worker.py`` previously exposed all tools unconditionally regardless of context -- adopting this shared, already-correct filter is a deliberate, in-scope fix (not scope creep): a read-only task's OpenAI-compatible coder could previously have its ``write_file``/``edit_file``/``run_command`` tool calls actually dispatched and executed, since nothing upstream of dispatch stopped it. """ from __future__ import annotations from copy import deepcopy from afk_developer.scheduler.verification import VERIFICATION_TOOL_SCHEMA ToolSchema = tuple[str, str, dict, list[str]] """(name, description, properties, required) -- one tool's canonical schema.""" _READ_ONLY_EXCLUDED_TOOLS = frozenset( {"write_file", "edit_file", "normalize_line_endings", "run_command"} ) _EVIDENCE_TOOLS = frozenset( { "read_evidence_file", "read_evidence_metadata", "read_evidence_section", "search_evidence_text", } ) TOOL_SCHEMAS: list[ToolSchema] = [ ( "read_file", "Read a file from the project. Returns line-numbered content.", { "path": {"type": "string", "description": "Path relative to project root"}, "offset": { "type": "integer", "description": "Line number to start reading from (0-indexed)", "default": 0, }, "limit": {"type": "integer", "description": "Max lines to return", "default": 500}, }, ["path"], ), ( "read_evidence_file", "Read an approved external evidence file using a path relative to an approved root.", { "path": {"type": "string", "description": "Relative evidence file path"}, "offset": {"type": "integer", "default": 0}, "limit": {"type": "integer", "default": 500}, }, ["path"], ), ( "read_evidence_metadata", "Read bounded byte-level metadata from an approved external evidence file.", {"path": {"type": "string", "description": "Relative evidence file path"}}, ["path"], ), ( "read_evidence_section", "Read a bounded literal-marker-delimited section from approved external evidence.", { "path": {"type": "string"}, "start_text": {"type": "string"}, "end_text": {"type": "string"}, "occurrence": {"type": "integer", "default": 0}, "max_chars": {"type": "integer", "default": 60000}, }, ["path", "start_text"], ), ( "search_evidence_text", "Search approved external evidence for literal text and return per-file counts.", { "text": {"type": "string"}, "suffix": {"type": "string", "default": ".xml"}, "max_results": {"type": "integer", "default": 100}, }, ["text"], ), ( "write_file", "Create a new file or overwrite an existing file.", { "path": {"type": "string", "description": "Path relative to project root"}, "content": {"type": "string", "description": "Complete file contents"}, }, ["path", "content"], ), ( "edit_file", "Replace a string in an existing file. old_string must match exactly once.", { "path": {"type": "string", "description": "Path relative to project root"}, "old_string": { "type": "string", "description": "Exact text to replace (must be unique in file)", }, "new_string": {"type": "string", "description": "Replacement text"}, }, ["path", "old_string", "new_string"], ), ( "normalize_line_endings", "Normalize an existing UTF-8 project file to exact LF or CRLF line endings without " "changing its text.", {"path": {"type": "string"}, "style": {"type": "string", "enum": ["lf", "crlf"]}}, ["path", "style"], ), ( "glob_files", "Find files matching a glob pattern.", { "pattern": { "type": "string", "description": "Glob pattern (e.g. '**/*.py', 'src/**/*.ts')", }, }, ["pattern"], ), ( "run_command", "Execute a shell command in the project directory.", { "command": {"type": "string", "description": "Shell command to run"}, "timeout": { "type": "integer", "description": "Timeout in seconds (default 60)", "default": 60, }, }, ["command"], ), ( "run_verification", "Run one typed, allowlisted read-only validation request.", VERIFICATION_TOOL_SCHEMA.get("properties", {}), VERIFICATION_TOOL_SCHEMA.get("required", []), ), ( "discover_project", "Get the project directory tree and key config files.", {}, [], ), ( "list_directory", "List contents of a directory.", {"path": {"type": "string", "description": "Directory path relative to project root"}}, ["path"], ), ( "grep_codebase", "Search codebase for a regex pattern. Requires ripgrep (rg).", { "pattern": {"type": "string", "description": "Regex pattern to search for"}, "include": {"type": "string", "description": "File pattern to include (e.g. '*.py')"}, }, ["pattern"], ), ( "task_complete", "Signal that the task is complete. Call this when all changes are made AND verified.", { "summary": {"type": "string", "description": "What was accomplished"}, "files_changed": { "type": "array", "items": {"type": "string"}, "description": "List of file paths that were created or modified", }, }, ["summary", "files_changed"], ), ( "task_blocked", "Signal that required research evidence is unavailable. Do not implement unsupported " "assumptions.", { "reason": {"type": "string"}, "missing_evidence": {"type": "string"}, }, ["reason", "missing_evidence"], ), ] def build_tool_schemas( *, read_only: bool, has_evidence_roots: bool, allow_baseline_compare: bool = True, ) -> list[ToolSchema]: """Return the tool schemas applicable to one task. Mutating tools are excluded for a read-only task; ``run_verification`` is excluded for a mutating task (that path verifies via ``run_command`` instead); the evidence-reading tools are excluded entirely when no evidence roots are configured for the task. Same filter for every caller. """ schemas = TOOL_SCHEMAS if read_only: schemas = [s for s in schemas if s[0] not in _READ_ONLY_EXCLUDED_TOOLS] else: schemas = [s for s in schemas if s[0] != "run_verification"] if not has_evidence_roots: schemas = [s for s in schemas if s[0] not in _EVIDENCE_TOOLS] if not allow_baseline_compare: filtered: list[ToolSchema] = [] for name, description, properties, required in schemas: if name == "run_verification": properties = deepcopy(properties) properties["kind"]["enum"] = [ kind for kind in properties["kind"]["enum"] if kind != "baseline_compare" ] properties["kind"]["description"] = ( "The fixed read-only verification operation to run. " "file_sha256 hashes project files." ) filtered.append((name, description, properties, required)) schemas = filtered return schemas def tool_parameters(name: str, properties: dict, required: list[str]) -> dict: """The JSON-schema ``parameters`` object for one tool. ``run_verification`` uses ``VERIFICATION_TOOL_SCHEMA`` directly so its ``additionalProperties: False`` is preserved; every other tool gets the standard ``{type: object, properties, required}`` shape. """ if name == "run_verification": if properties: return { "type": "object", "additionalProperties": False, "properties": properties, "required": required, } return VERIFICATION_TOOL_SCHEMA return {"type": "object", "properties": properties, "required": required} def to_openai_tool_definitions(schemas: list[ToolSchema]) -> list[dict]: """Adapt canonical schemas to the OpenAI-compatible ``tools=[...]`` shape.""" return [ { "type": "function", "function": { "name": name, "description": description, "parameters": tool_parameters(name, properties, required), }, } for name, description, properties, required in schemas ]