"""Shared tool-call dispatch for both agent loops. ``scheduler/worker.py`` (sync, OpenAI-compatible loop) and ``backends/copilot.py`` (async Copilot SDK loop) each hand-duplicated the same ~14-way if/elif dispatch from a tool-call name + arguments to the underlying sync tool implementation. ``dispatch_tool_call`` is the single shared body; each loop wraps its raw text result however its own contract needs (worker.py returns it as-is, copilot.py wraps it in a ``ToolResult`` and tracks files_changed/verification_failure around the call). ``task_complete``/``task_blocked`` are deliberately NOT handled here: what happens next differs structurally per loop (worker.py returns from its turn loop immediately; copilot.py records intent in a nonlocal dict and lets the SDK session keep running) -- each loop's own outer control flow still owns those two. HITL-mode gating of mutating tools is also caller-specific and stays in each loop. """ from __future__ import annotations from afk_developer.config import Config from afk_developer.scheduler.tools.codebase import discover_project, grep_codebase, list_directory from afk_developer.scheduler.tools.file_ops import ( edit_file, glob_files, normalize_line_endings, read_evidence_file, read_evidence_metadata, read_evidence_section, read_file, search_evidence_text, write_file, ) from afk_developer.scheduler.tools.shell import run_command from afk_developer.scheduler.verification import run_verification_request # Tools whose dispatch is shared here. task_complete/task_blocked are handled # by each loop's own outer control flow instead (see module docstring). DISPATCHED_TOOL_NAMES = frozenset( { "read_file", "read_evidence_file", "read_evidence_metadata", "read_evidence_section", "search_evidence_text", "write_file", "edit_file", "normalize_line_endings", "glob_files", "run_command", "run_verification", "discover_project", "list_directory", "grep_codebase", } ) def dispatch_tool_call( name: str, args: dict, *, project_dir: str, evidence_roots: list[str], config: Config, disallow_unscoped_pytest: bool = False, allowed_output_paths: list[str] | None = None, project_name: str = "", ) -> str: """Execute one shared tool call and return its raw text result. Callers are responsible for JSON-decoding ``args`` beforehand and for catching exceptions around this call (both loops already wrap their own call site in a broad ``except Exception`` that reports a "Tool error" string back to the model, and that behavior is preserved unchanged by being left in each caller rather than duplicated here). """ if name == "read_file": return read_file( args.get("path", ""), project_dir, args.get("offset", 0), args.get("limit", 500) ) if name == "read_evidence_file": return read_evidence_file( args.get("path", ""), evidence_roots, args.get("offset", 0), args.get("limit", 500) ) if name == "read_evidence_metadata": return read_evidence_metadata(args.get("path", ""), evidence_roots) if name == "read_evidence_section": return read_evidence_section( args.get("path", ""), args.get("start_text", ""), evidence_roots, args.get("end_text", ""), args.get("occurrence", 0), args.get("max_chars", 60000), ) if name == "search_evidence_text": return search_evidence_text( args.get("text", ""), evidence_roots, args.get("suffix", ".xml"), args.get("max_results", 100), ) if name in {"write_file", "edit_file", "normalize_line_endings"}: scope_error = _mutation_scope_error(args.get("path", ""), allowed_output_paths) if scope_error: return scope_error if name == "write_file": return write_file(args["path"], args["content"], project_dir) if name == "edit_file": return edit_file(args["path"], args["old_string"], args["new_string"], project_dir) if name == "normalize_line_endings": return normalize_line_endings(args["path"], args["style"], project_dir) if name == "glob_files": return glob_files(args["pattern"], project_dir) if name == "run_command": timeout = min(int(args.get("timeout", 60)), config.max_shell_timeout) if not disallow_unscoped_pytest: return run_command(args["command"], project_dir, timeout) return run_command( args["command"], project_dir, timeout, disallow_unscoped_pytest=disallow_unscoped_pytest, ) if name == "run_verification": return run_verification_request( args, project_dir, max_timeout_seconds=config.max_shell_timeout, projects_dir=config.projects_dir, python_executable=config.target_python, default_project_name=project_name, ).to_tool_text() if name == "discover_project": return discover_project(project_dir) if name == "list_directory": return list_directory(args.get("path", ""), project_dir) if name == "grep_codebase": return grep_codebase(args["pattern"], project_dir, args.get("include", "")) return f"Unknown tool: {name}" def _mutation_scope_error(path: str, allowed_output_paths: list[str] | None) -> str: """Return a deterministic rejection for a checkpoint-scoped mutation.""" if allowed_output_paths is None: return "" if path in set(allowed_output_paths): return "" return ( "TASK_MUTATION_SCOPE_REJECTED: Discovery checkpoint permits mutations only to " f"{sorted(allowed_output_paths)}; received {path!r}." )