"""Tool registration, argument validation, approvals, and uniform results.""" from __future__ import annotations import json import shlex from collections.abc import Callable from dataclasses import dataclass from typing import Any from nano_python_agents.events import NullEventLogger from nano_python_agents.tools import PathViolation, ToolFailure, ToolOutcome, WorkspaceTools from nano_python_agents.todo import TodoError, TodoStore from nano_python_agents.types import ToolCall, ToolResult, ToolSchema @dataclass class ApprovalRequest: tool_name: str summary: str detail: str ApprovalCallback = Callable[[ApprovalRequest], bool] class Gateway: def __init__( self, workspace_tools: WorkspaceTools, approval_callback: ApprovalCallback, event_logger=None, skill_registry=None, todo_store: TodoStore | None = None, ) -> None: self.tools = workspace_tools self.approve = approval_callback self.events = event_logger or NullEventLogger() self._skill_registry = skill_registry self._todo_store = todo_store self._active_skill_name: str | None = None self._schemas = self._build_schemas() def schemas(self) -> list[ToolSchema]: return list(self._schemas.values()) def execute(self, call: ToolCall) -> ToolResult: self._log("tool_start", call_id=call.id, tool=call.name) if call.name not in self._schemas: result = ToolResult(call.id, f"Unknown tool: {call.name}", True) elif not isinstance(call.arguments, dict): result = ToolResult( call.id, "Tool arguments must be a valid JSON object.", True, ) else: try: outcome = self._dispatch(call.name, call.arguments) result = ToolResult( call_id=call.id, content=outcome.content, is_error=outcome.is_error, metadata=outcome.metadata, ) except (PathViolation, ToolFailure, KeyError) as error: result = ToolResult(call.id, f"Error: {error}", True) except TodoError as error: result = ToolResult( call.id, f"TODO_ERROR[{error.code}]: {error}", True, metadata={"todo_error_code": error.code}, ) except Exception as error: result = ToolResult( call.id, f"Unexpected tool error: {type(error).__name__}: {error}", True, ) self._log( "tool_end", call_id=call.id, tool=call.name, is_error=result.is_error, content_chars=len(result.content), **result.metadata, ) return result def _dispatch(self, name: str, arguments: dict[str, Any]) -> ToolOutcome: if name == "list_files": return self.tools.execute_registered(name, arguments) if name == "read_file": return self.tools.execute_registered(name, arguments) if name == "search_text": return self.tools.execute_registered(name, arguments) if name == "replace_text": prepared = self.tools.prepare_replace(arguments) approved = self.approve( ApprovalRequest( tool_name=name, summary=f"Apply this change to {prepared.relative_path}?", detail=prepared.diff, ) ) self._log("approval", tool=name, target=prepared.relative_path, approved=approved) if not approved: return ToolOutcome( "User rejected the proposed change. The file was not modified.", is_error=True, metadata={"approved": False, "modified": False}, ) outcome = self.tools.apply_replace(prepared) outcome.metadata["approved"] = True return outcome if name == "run_tests": if arguments: raise ToolFailure("run_tests does not accept arguments") if not self.tools.test_command: raise ToolFailure("run_tests is not configured") approved = self.approve( ApprovalRequest( tool_name=name, summary="Run the configured test command?", detail=shlex.join(self.tools.test_command), ) ) self._log("approval", tool=name, approved=approved) if not approved: return ToolOutcome( "User declined to run tests.", is_error=True, metadata={"approved": False}, ) outcome = self.tools.run_tests() outcome.metadata["approved"] = True return outcome if name == "load_skill": if self._skill_registry is None: raise ToolFailure("no skills are configured") if set(arguments) != {"name"}: raise ToolFailure("load_skill accepts exactly one 'name' argument") skill_name = arguments.get("name") if not isinstance(skill_name, str) or not skill_name: raise ToolFailure("load_skill requires a non-empty 'name' argument") from nano_python_agents.skill_registry import SkillError try: meta, body = self._skill_registry.load(skill_name) except SkillError as exc: raise ToolFailure(str(exc)) if not set(meta.allowed_tools).issubset({"list_files", "search_text", "read_file"}): raise ToolFailure(f"skill {meta.name!r} is not read-only") if self._active_skill_name not in {None, meta.name}: raise ToolFailure( f"skill {self._active_skill_name!r} is already active; v0.2 allows one active skill" ) self._active_skill_name = meta.name self._log( "skill_loaded", skill=meta.name, version=meta.version, content_hash=meta.content_hash, ) bounded_body, truncated = self.tools.bound_output(body) return ToolOutcome( bounded_body, is_error=False, metadata={ "skill": meta.name, "version": meta.version, "hash": meta.content_hash, "allowed_tools": list(meta.allowed_tools), "truncated": truncated, }, ) if name == "todowrite": if self._todo_store is None: raise ToolFailure("todowrite is not enabled") if set(arguments) != {"todos"}: raise TodoError("todowrite accepts exactly the 'todos' field", "invalid_arguments") result = self._todo_store.update(arguments["todos"]) return ToolOutcome( json.dumps(result, ensure_ascii=False, sort_keys=True), metadata={ "todo_revision": result["revision"], "changed_positions": result["changed_positions"], "status_counts": result["status_counts"], }, ) raise ToolFailure(f"Unknown tool: {name}") def _build_schemas(self) -> dict[str, ToolSchema]: schemas = { "list_files": ToolSchema( name="list_files", description=( "List workspace files recursively with depth and count limits. " "The optional path must be workspace-relative." ), parameters={ "type": "object", "properties": { "path": { "type": "string", "description": "Workspace-relative directory; defaults to the root.", } }, "additionalProperties": False, }, ), "read_file": ToolSchema( name="read_file", description="Read a bounded line range from a workspace UTF-8 text file.", parameters={ "type": "object", "properties": { "path": {"type": "string"}, "offset": {"type": "integer", "minimum": 1}, "limit": {"type": "integer", "minimum": 1}, }, "required": ["path"], "additionalProperties": False, }, ), "search_text": ToolSchema( name="search_text", description="Search for a literal string in bounded workspace text files.", parameters={ "type": "object", "properties": { "query": {"type": "string"}, "path": { "type": "string", "description": "Workspace-relative directory; defaults to the root.", }, }, "required": ["query"], "additionalProperties": False, }, ), "replace_text": ToolSchema( name="replace_text", description=( "Replace one unique text occurrence in a workspace file. " "Shows a unified diff and requires user approval before an atomic write." ), parameters={ "type": "object", "properties": { "path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}, }, "required": ["path", "old_text", "new_text"], "additionalProperties": False, }, ), } if self.tools.test_command: schemas["run_tests"] = ToolSchema( name="run_tests", description=( "Run the fixed test argv from local configuration. " "Takes no arguments and requires user approval." ), parameters={ "type": "object", "properties": {}, "additionalProperties": False, }, ) if self._skill_registry is not None and self._skill_registry.names(): schemas["load_skill"] = ToolSchema( name="load_skill", description="Load the full instructions for a named skill by its identifier.", parameters={ "type": "object", "properties": { "name": {"type": "string", "description": "Skill identifier from the skill index."}, }, "required": ["name"], "additionalProperties": False, }, ) if self._todo_store is not None: schemas["todowrite"] = ToolSchema( name="todowrite", description=( "Replace the complete sequential TODO list. The host owns revision and " "validates the canonical item order and state transitions." ), parameters={ "type": "object", "properties": { "todos": { "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "content": {"type": "string"}, "status": { "type": "string", "enum": ["pending", "in_progress", "completed", "cancelled"], }, "priority": { "type": "string", "enum": ["high", "medium", "low"], }, }, "required": ["content", "status", "priority"], "additionalProperties": False, }, } }, "required": ["todos"], "additionalProperties": False, }, ) return schemas def _log(self, event_type: str, **fields: Any) -> None: try: self.events.log(event_type, **fields) except Exception: pass