File size: 13,375 Bytes
fd11263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""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