saicode 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,305 @@
1
+ """Built-in tools. Each tool checks the policy before acting.
2
+
3
+ Tools never draw on the screen. When a change needs the user's approval,
4
+ they hand an ApprovalRequest to the approver the front end provides.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import difflib
10
+ from collections.abc import Callable
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from saicode.ai.base import ToolSpec
16
+ from saicode.core.policy import LIST, READ, RUN, WRITE, Decision, Policy
17
+ from saicode.sandbox import Runner
18
+
19
+ MAX_READ_CHARS = 100_000
20
+ MAX_OUTPUT_CHARS = 20_000
21
+ SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv"}
22
+
23
+
24
+ @dataclass
25
+ class ApprovalRequest:
26
+ kind: str # "write" or "run": the bucket for "always allow"
27
+ title: str # e.g. "Edit src/app.py"
28
+ detail: str # a diff, new file content, or a command
29
+ detail_format: str # "diff", "file:<path>" or "shell"
30
+ can_always: bool = True
31
+
32
+
33
+ Approver = Callable[[ApprovalRequest], str] # returns "yes", "no" or "always"
34
+
35
+
36
+ @dataclass
37
+ class ToolOutcome:
38
+ output: str # what the model sees
39
+ summary: str # one line for the screen and the audit log
40
+ status: str = "ok" # "ok" | "denied" | "error"
41
+ content: str | None = None # full content (logged only if include_content)
42
+
43
+
44
+ @dataclass
45
+ class ToolContext:
46
+ workdir: Path
47
+ policy: Policy
48
+ runner: Runner
49
+ approver: Approver
50
+ on_running: Callable[[str], None] = lambda command: None
51
+
52
+
53
+ def _ask(ctx: ToolContext, req: ApprovalRequest) -> bool:
54
+ req.can_always = ctx.policy.allow_always
55
+ answer = ctx.approver(req)
56
+ if answer == "always":
57
+ ctx.policy.remember_always(req.kind)
58
+ return True
59
+ return answer == "yes"
60
+
61
+
62
+ def _denied(reason: str) -> ToolOutcome:
63
+ return ToolOutcome(output=f"Not allowed: {reason}", summary=reason, status="denied")
64
+
65
+
66
+ # ---- tools ------------------------------------------------------------------
67
+
68
+
69
+ def list_files(ctx: ToolContext, path: str = ".") -> ToolOutcome:
70
+ verdict = ctx.policy.check_path(LIST, path)
71
+ if verdict.decision is Decision.DENY:
72
+ return _denied(verdict.reason)
73
+ target = ctx.policy.resolve(path)
74
+ if target is None or not target.is_dir():
75
+ return ToolOutcome(f"Error: {path} is not a directory.", "not a directory", "error")
76
+ items = [
77
+ p.name + ("/" if p.is_dir() else "")
78
+ for p in sorted(target.iterdir())
79
+ if p.name not in SKIP_DIRS
80
+ ]
81
+ return ToolOutcome("\n".join(items) or "(empty folder)", f"{len(items)} items")
82
+
83
+
84
+ def read_file(ctx: ToolContext, path: str) -> ToolOutcome:
85
+ verdict = ctx.policy.check_path(READ, path)
86
+ if verdict.decision is Decision.DENY:
87
+ return _denied(verdict.reason)
88
+ target = ctx.policy.resolve(path)
89
+ try:
90
+ text = target.read_text(encoding="utf-8") # type: ignore[union-attr]
91
+ except Exception as e:
92
+ return ToolOutcome(f"Error reading {path}: {e}", f"failed: {e}", "error")
93
+ lines = text.count("\n") + 1
94
+ shown = (
95
+ text if len(text) <= MAX_READ_CHARS else text[:MAX_READ_CHARS] + "\n... (file truncated)"
96
+ )
97
+ return ToolOutcome(shown, f"{lines} lines", content=text)
98
+
99
+
100
+ def write_file(ctx: ToolContext, path: str, content: str) -> ToolOutcome:
101
+ verdict = ctx.policy.check_path(WRITE, path)
102
+ if verdict.decision is Decision.DENY:
103
+ return _denied(verdict.reason)
104
+ target = ctx.policy.resolve(path)
105
+ assert target is not None
106
+ if target.is_dir():
107
+ return ToolOutcome(f"Error: {path} is a directory, not a file.", "is a directory", "error")
108
+ exists = target.exists()
109
+ if verdict.decision is Decision.ASK:
110
+ if exists:
111
+ old = target.read_text(encoding="utf-8", errors="replace")
112
+ detail = "".join(
113
+ difflib.unified_diff(
114
+ old.splitlines(True),
115
+ content.splitlines(True),
116
+ fromfile=f"a/{path}",
117
+ tofile=f"b/{path}",
118
+ )
119
+ )
120
+ req = ApprovalRequest(WRITE, f"Overwrite {path}", detail or "(no changes)", "diff")
121
+ else:
122
+ req = ApprovalRequest(WRITE, f"Create {path}", content, f"file:{path}")
123
+ if not _ask(ctx, req):
124
+ return ToolOutcome("The user denied this write.", "denied by user", "denied")
125
+ target.parent.mkdir(parents=True, exist_ok=True)
126
+ target.write_text(content, encoding="utf-8")
127
+ return ToolOutcome(
128
+ f"Wrote {path}", f"saved ({len(content.splitlines())} lines)", content=content
129
+ )
130
+
131
+
132
+ def edit_file(ctx: ToolContext, path: str, old_text: str, new_text: str) -> ToolOutcome:
133
+ verdict = ctx.policy.check_path(WRITE, path)
134
+ if verdict.decision is Decision.DENY:
135
+ return _denied(verdict.reason)
136
+ target = ctx.policy.resolve(path)
137
+ assert target is not None
138
+ try:
139
+ text = target.read_text(encoding="utf-8")
140
+ except Exception as e:
141
+ return ToolOutcome(f"Error reading {path}: {e}", f"failed: {e}", "error")
142
+ count = text.count(old_text)
143
+ if count != 1:
144
+ return ToolOutcome(
145
+ f"Error: old_text found {count} times; it must appear exactly once.",
146
+ f"text matched {count} times, expected 1",
147
+ "error",
148
+ )
149
+ new_full = text.replace(old_text, new_text)
150
+ diff = "".join(
151
+ difflib.unified_diff(
152
+ text.splitlines(True),
153
+ new_full.splitlines(True),
154
+ fromfile=f"a/{path}",
155
+ tofile=f"b/{path}",
156
+ )
157
+ )
158
+ if verdict.decision is Decision.ASK and not _ask(
159
+ ctx, ApprovalRequest(WRITE, f"Edit {path}", diff, "diff")
160
+ ):
161
+ return ToolOutcome("The user denied this edit.", "denied by user", "denied")
162
+ target.write_text(new_full, encoding="utf-8")
163
+ return ToolOutcome(f"Edited {path}", "saved", content=diff)
164
+
165
+
166
+ def run_command(ctx: ToolContext, command: str) -> ToolOutcome:
167
+ verdict = ctx.policy.check_command(command)
168
+ if verdict.decision is Decision.DENY:
169
+ return _denied(verdict.reason)
170
+ if verdict.decision is Decision.ASK and not _ask(
171
+ ctx, ApprovalRequest(RUN, "Run command", command, "shell")
172
+ ):
173
+ return ToolOutcome("The user denied this command.", "denied by user", "denied")
174
+ ctx.on_running(command)
175
+ result = ctx.runner.run(command, ctx.workdir)
176
+ lines = result.output.splitlines()
177
+ status = "ok" if result.exit_code == 0 else "error"
178
+ summary = f"exit {result.exit_code} · {len(lines)} lines of output"
179
+ return ToolOutcome(
180
+ f"exit code {result.exit_code}\n{result.output[-MAX_OUTPUT_CHARS:]}",
181
+ summary,
182
+ status,
183
+ content=result.output,
184
+ )
185
+
186
+
187
+ # ---- registry -----------------------------------------------------------------
188
+
189
+ _STR = {"type": "string"}
190
+
191
+ Describer = Callable[[dict[str, Any]], tuple[str, str]] # args -> (action, target)
192
+
193
+ TOOLS: dict[str, tuple[ToolSpec, Callable[..., ToolOutcome], Describer]] = {
194
+ "list_files": (
195
+ ToolSpec(
196
+ "list_files",
197
+ "List files and folders inside a directory of the project.",
198
+ {
199
+ "type": "object",
200
+ "properties": {
201
+ "path": {
202
+ **_STR,
203
+ "description": (
204
+ "Directory relative to the project folder. "
205
+ 'Use "." for the project root.'
206
+ ),
207
+ }
208
+ },
209
+ },
210
+ ),
211
+ list_files,
212
+ lambda a: ("List", a.get("path", ".")),
213
+ ),
214
+ "read_file": (
215
+ ToolSpec(
216
+ "read_file",
217
+ "Read a text file from the project.",
218
+ {
219
+ "type": "object",
220
+ "properties": {
221
+ "path": {**_STR, "description": "File path relative to the project folder."}
222
+ },
223
+ "required": ["path"],
224
+ },
225
+ ),
226
+ read_file,
227
+ lambda a: ("Read", a.get("path", "")),
228
+ ),
229
+ "write_file": (
230
+ ToolSpec(
231
+ "write_file",
232
+ "Create a new file or overwrite an existing file with the full content.",
233
+ {
234
+ "type": "object",
235
+ "properties": {
236
+ "path": {**_STR, "description": "File path relative to the project folder."},
237
+ "content": {**_STR, "description": "The complete new content of the file."},
238
+ },
239
+ "required": ["path", "content"],
240
+ },
241
+ ),
242
+ write_file,
243
+ lambda a: ("Write", a.get("path", "")),
244
+ ),
245
+ "edit_file": (
246
+ ToolSpec(
247
+ "edit_file",
248
+ "Replace one exact piece of text in a file. old_text must appear exactly once.",
249
+ {
250
+ "type": "object",
251
+ "properties": {
252
+ "path": {**_STR, "description": "File path relative to the project folder."},
253
+ "old_text": {
254
+ **_STR,
255
+ "description": "The exact text to find, copied from the file.",
256
+ },
257
+ "new_text": {**_STR, "description": "The text to put in its place."},
258
+ },
259
+ "required": ["path", "old_text", "new_text"],
260
+ },
261
+ ),
262
+ edit_file,
263
+ lambda a: ("Edit", a.get("path", "")),
264
+ ),
265
+ "run_command": (
266
+ ToolSpec(
267
+ "run_command",
268
+ "Run a shell command in the project folder (tests, git status, installs).",
269
+ {
270
+ "type": "object",
271
+ "properties": {"command": {**_STR, "description": "The shell command to run."}},
272
+ "required": ["command"],
273
+ },
274
+ ),
275
+ run_command,
276
+ lambda a: ("Run", a.get("command", "")),
277
+ ),
278
+ }
279
+
280
+
281
+ def specs() -> list[ToolSpec]:
282
+ return [spec for spec, _, _ in TOOLS.values()]
283
+
284
+
285
+ def execute(ctx: ToolContext, name: str, args: dict[str, Any]) -> ToolOutcome:
286
+ entry = TOOLS.get(name)
287
+ if entry is None:
288
+ return ToolOutcome(f"Unknown tool {name}", f"unknown tool {name}", "error")
289
+ _, handler, _ = entry
290
+ try:
291
+ return handler(ctx, **args)
292
+ except TypeError as e:
293
+ return ToolOutcome(f"Bad arguments for {name}: {e}", "bad arguments", "error")
294
+ except (OSError, UnicodeError) as e:
295
+ # A failed file operation (folder instead of file, no permission, disk full, ...)
296
+ # is reported to the model instead of ending the session.
297
+ reason = e.strerror if isinstance(e, OSError) and e.strerror else str(e)
298
+ return ToolOutcome(f"Error: {name} failed: {reason}", f"failed: {reason}", "error")
299
+
300
+
301
+ def describe(name: str, args: dict[str, Any]) -> tuple[str, str]:
302
+ entry = TOOLS.get(name)
303
+ if entry is None:
304
+ return (name, "")
305
+ return entry[2](args)
@@ -0,0 +1 @@
1
+ """Terminal user interface. The only package that draws on the screen."""