spiritcode 0.1.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.
spiritcode/tools.py ADDED
@@ -0,0 +1,366 @@
1
+ import asyncio
2
+ import difflib
3
+ import os
4
+ import signal
5
+ import subprocess
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from pathspec import GitIgnoreSpec
10
+ from pydantic import BaseModel, ConfigDict, Field
11
+
12
+ from spiritcode.config import (
13
+ COMMAND_TIMEOUT,
14
+ EXCLUDED,
15
+ MAX_FILE_BYTES,
16
+ MAX_FILES,
17
+ MAX_RESULT_CHARS,
18
+ )
19
+ from spiritcode.permissions import Permissions, is_secret
20
+ from spiritcode.ui import KEY, UI, clean
21
+
22
+
23
+ class Args(BaseModel):
24
+ model_config = ConfigDict(extra="forbid", strict=True)
25
+
26
+
27
+ class ListFiles(Args):
28
+ path: str = "."
29
+
30
+
31
+ class Search(Args):
32
+ query: str = Field(min_length=1, max_length=1_000)
33
+ path: str = "."
34
+
35
+
36
+ class ReadFile(Args):
37
+ path: str
38
+ start: int = Field(default=1, ge=1)
39
+ end: int = Field(default=250, ge=1)
40
+
41
+
42
+ class CreateFile(Args):
43
+ path: str
44
+ content: str = Field(max_length=MAX_FILE_BYTES)
45
+
46
+
47
+ class EditFile(Args):
48
+ path: str
49
+ old_text: str = Field(min_length=1, max_length=MAX_FILE_BYTES)
50
+ new_text: str = Field(max_length=MAX_FILE_BYTES)
51
+
52
+
53
+ class RunCommand(Args):
54
+ command: str = Field(min_length=1, max_length=10_000)
55
+ cwd: str
56
+ timeout: int = Field(default=COMMAND_TIMEOUT, ge=1, le=3_600)
57
+
58
+
59
+ ARGUMENTS: dict[str, type[Args]] = {
60
+ "list_files": ListFiles,
61
+ "search": Search,
62
+ "read_file": ReadFile,
63
+ "create_file": CreateFile,
64
+ "edit_file": EditFile,
65
+ "run_command": RunCommand,
66
+ }
67
+ DESCRIPTIONS = {
68
+ "list_files": "List project files, respecting ignore rules. Never follows directory symlinks.",
69
+ "search": "Search literal text across project files, respecting ignore rules.",
70
+ "read_file": "Read UTF-8 file lines (inclusive, 1-based), and scoped AGENTS.md instructions.",
71
+ "create_file": "Create a new UTF-8 file. Fails if a file already exists.",
72
+ "edit_file": "Replace exactly one occurrence of old_text. Read the file first.",
73
+ "run_command": "Run shell command in explicit cwd after user approval. Not a sandbox.",
74
+ }
75
+
76
+
77
+ def definitions() -> list[dict[str, Any]]:
78
+ return [
79
+ {
80
+ "type": "function",
81
+ "function": {
82
+ "name": name,
83
+ "description": DESCRIPTIONS[name],
84
+ "parameters": model.model_json_schema(),
85
+ },
86
+ }
87
+ for name, model in ARGUMENTS.items()
88
+ ]
89
+
90
+
91
+ def text_file(path: Path) -> str:
92
+ with path.open("rb") as stream:
93
+ raw = stream.read(MAX_FILE_BYTES + 1)
94
+ if len(raw) > MAX_FILE_BYTES:
95
+ raise ValueError(f"Файл превышает лимит {MAX_FILE_BYTES} байт.")
96
+ if b"\0" in raw:
97
+ raise ValueError("Бинарный файл пропущен.")
98
+ return raw.decode("utf-8")
99
+
100
+
101
+ def project_files(root: Path) -> list[Path]:
102
+ """Per-directory GitIgnoreSpec preserves nested rules without requiring Git or rg."""
103
+ result: list[Path] = []
104
+
105
+ def walk(directory: Path, rules: list[tuple[Path, GitIgnoreSpec]]) -> None:
106
+ ignore = directory / ".gitignore"
107
+ if ignore.is_file() and not ignore.is_symlink():
108
+ try:
109
+ rules = [
110
+ *rules,
111
+ (directory, GitIgnoreSpec.from_lines(text_file(ignore).splitlines())),
112
+ ]
113
+ except (OSError, UnicodeError, ValueError):
114
+ pass
115
+ for child in sorted(directory.iterdir()):
116
+ if len(result) >= MAX_FILES:
117
+ return
118
+ if child.name in EXCLUDED or is_secret(child) or child.is_symlink():
119
+ continue
120
+ ignored = False
121
+ for base, spec in rules:
122
+ relative = child.relative_to(base).as_posix() + ("/" if child.is_dir() else "")
123
+ match = spec.check_file(relative)
124
+ if match.include is not None:
125
+ ignored = match.include
126
+ if ignored:
127
+ continue
128
+ if child.is_dir():
129
+ try:
130
+ walk(child, rules)
131
+ except OSError:
132
+ continue
133
+ elif child.is_file():
134
+ result.append(child)
135
+
136
+ walk(root, [])
137
+ return result
138
+
139
+
140
+ def unified(path: str, before: str | None, after: str | None) -> str:
141
+ return "".join(
142
+ difflib.unified_diff(
143
+ (before or "").splitlines(keepends=True),
144
+ (after or "").splitlines(keepends=True),
145
+ fromfile=f"a/{path}",
146
+ tofile=f"b/{path}",
147
+ )
148
+ )
149
+
150
+
151
+ class Tools:
152
+ def __init__(self, root: Path, ui: UI, snapshots: list[list[dict[str, Any]]]) -> None:
153
+ self.root, self.ui, self.snapshots = root.resolve(), ui, snapshots
154
+ self.permissions = Permissions(root, ui)
155
+ self.group: list[dict[str, Any]] = []
156
+ self.reads: dict[Path, str] = {}
157
+
158
+ def start_turn(self) -> None:
159
+ self.group = []
160
+ self.snapshots.append(self.group)
161
+
162
+ def instructions(self, path: Path) -> str:
163
+ if not path.is_relative_to(self.root):
164
+ return ""
165
+ sections: list[tuple[Path, str]] = []
166
+ for directory in [self.root, *reversed(path.parent.parents), path.parent]:
167
+ if not directory.is_relative_to(self.root):
168
+ continue
169
+ agent = directory / "AGENTS.md"
170
+ if agent.is_file() and not agent.is_symlink() and agent not in [s[0] for s in sections]:
171
+ sections.append((agent, text_file(agent)))
172
+ return "\n".join(f"Instructions for {p.parent}:\n{body}" for p, body in sections)
173
+
174
+ async def execute(self, name: str, arguments: str) -> str:
175
+ try:
176
+ if name not in ARGUMENTS:
177
+ raise ValueError("Неизвестный инструмент.")
178
+ args = ARGUMENTS[name].model_validate_json(arguments)
179
+ titles = {
180
+ "list_files": "Файлы проекта",
181
+ "search": "Поиск",
182
+ "read_file": "Чтение",
183
+ "create_file": "Создание",
184
+ "edit_file": "Изменение",
185
+ "run_command": "Команда",
186
+ }
187
+ if isinstance(args, RunCommand):
188
+ detail = args.command
189
+ else:
190
+ assert isinstance(args, (ListFiles, Search, ReadFile, CreateFile, EditFile))
191
+ detail = args.path
192
+ if isinstance(args, Search):
193
+ detail += " · " + args.query
194
+ self.ui.tool(titles[name], detail)
195
+ result = await self.dispatch(args)
196
+ if len(result) > MAX_RESULT_CHARS:
197
+ result = result[:MAX_RESULT_CHARS] + "\n[Результат усечён по лимиту]"
198
+ return clean(result)
199
+ except (ValueError, OSError, PermissionError) as exc:
200
+ self.ui.tool("Ошибка инструмента", str(exc), error=True)
201
+ return clean(f"Ошибка инструмента: {exc}")
202
+
203
+ async def dispatch(self, args: Args) -> str:
204
+ if isinstance(args, RunCommand):
205
+ return await self.run(args)
206
+ assert isinstance(args, (ListFiles, Search, ReadFile, CreateFile, EditFile))
207
+ path = await self.permissions.path(args.path, type(args).__name__)
208
+ if isinstance(args, (ListFiles, Search)):
209
+ # Walk from root so nested .gitignore never loses parent rules.
210
+ base = self.root if path.is_relative_to(self.root) else path
211
+ files = [p for p in project_files(base) if p.is_relative_to(path)]
212
+ if isinstance(args, ListFiles):
213
+ return "\n".join(str(p.relative_to(base)) for p in files) + (
214
+ f"\n[Не более {MAX_FILES} файлов]"
215
+ )
216
+ matches = []
217
+ for file in files:
218
+ try:
219
+ for number, line in enumerate(text_file(file).splitlines(), 1):
220
+ if args.query in line:
221
+ matches.append(f"{file.relative_to(base)}:{number}:{line}")
222
+ if sum(map(len, matches)) >= MAX_RESULT_CHARS:
223
+ return "\n".join(matches) + "\n[Поиск усечён]"
224
+ except (OSError, UnicodeError, ValueError):
225
+ continue
226
+ return "\n".join(matches) or "Совпадений нет."
227
+ if isinstance(args, ReadFile):
228
+ if args.end < args.start:
229
+ raise ValueError("Конец диапазона должен быть не меньше начала.")
230
+ body = text_file(path)
231
+ self.reads[path] = body
232
+ lines = body.splitlines()
233
+ return (
234
+ self.instructions(path)
235
+ + "\n"
236
+ + "\n".join(
237
+ f"{i}: {line}" for i, line in enumerate(lines, 1) if args.start <= i <= args.end
238
+ )
239
+ + ("\n[Есть следующие строки]" if len(lines) > args.end else "")
240
+ )
241
+ before = text_file(path) if path.exists() else None
242
+ if isinstance(args, CreateFile):
243
+ if before is not None:
244
+ raise ValueError("Файл уже существует; используйте edit_file.")
245
+ after = args.content
246
+ else:
247
+ assert isinstance(args, EditFile)
248
+ if before is None or self.reads.get(path) != before:
249
+ raise ValueError("Сначала прочитайте актуальный файл через read_file.")
250
+ if before.count(args.old_text) != 1:
251
+ raise ValueError("Исходный текст должен совпадать ровно один раз.")
252
+ after = before.replace(args.old_text, args.new_text, 1)
253
+ # Do not persist secret file contents in undo snapshots.
254
+ if is_secret(path):
255
+ raise PermissionError("Правки секретов не поддерживаются: снимки содержали бы секреты.")
256
+ if KEY.search(before or "") or KEY.search(after):
257
+ raise PermissionError("Файл с API-ключом SpiritLM нельзя сохранять в снимках правок.")
258
+ if len(after.encode("utf-8")) > MAX_FILE_BYTES:
259
+ raise ValueError("Новый файл превышает лимит размера.")
260
+ path.parent.mkdir(parents=True, exist_ok=True)
261
+ if before is None:
262
+ with path.open("x", encoding="utf-8", newline="") as stream:
263
+ stream.write(after)
264
+ else:
265
+ with path.open("w", encoding="utf-8", newline="") as stream:
266
+ stream.write(after)
267
+ self.reads[path] = after
268
+ self.group.append({"path": str(path), "before": before, "after": after})
269
+ diff = unified(str(path), before, after)
270
+ self.ui.diff(diff)
271
+ return "Файл изменён.\n" + diff
272
+
273
+ async def run(self, args: RunCommand) -> str:
274
+ cwd = await self.permissions.path(args.cwd, "Рабочая директория команды")
275
+ description = f"Команда: {args.command}\nКаталог: {cwd}\nТаймаут: {args.timeout} с"
276
+ if args.timeout > COMMAND_TIMEOUT:
277
+ description += "\nУвеличенный лимит времени."
278
+ if not await self.ui.approve(description):
279
+ return "Пользователь отклонил запуск команды."
280
+ env = {k: v for k, v in os.environ.items() if k.upper() != "SPIRITLM_API_KEY"}
281
+ options: dict[str, Any] = {}
282
+ if os.name == "nt":
283
+ options["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0x200)
284
+ else:
285
+ options["start_new_session"] = True
286
+ process = await asyncio.create_subprocess_shell(
287
+ args.command,
288
+ cwd=cwd,
289
+ env=env,
290
+ stdin=asyncio.subprocess.DEVNULL,
291
+ stdout=asyncio.subprocess.PIPE,
292
+ stderr=asyncio.subprocess.STDOUT,
293
+ **options,
294
+ )
295
+ output = bytearray()
296
+ truncated = False
297
+
298
+ async def collect() -> None:
299
+ nonlocal truncated
300
+ assert process.stdout
301
+ while chunk := await process.stdout.read(4096):
302
+ remaining = MAX_RESULT_CHARS - len(output)
303
+ output.extend(chunk[: max(0, remaining)])
304
+ truncated |= len(chunk) > remaining
305
+ await process.wait()
306
+
307
+ try:
308
+ async with asyncio.timeout(args.timeout):
309
+ await collect()
310
+ except TimeoutError:
311
+ await self.stop(process)
312
+ return "Команда остановлена: истёк лимит времени."
313
+ except asyncio.CancelledError:
314
+ await self.stop(process)
315
+ raise
316
+ return (
317
+ f"Код выхода: {process.returncode}\n"
318
+ + output.decode("utf-8", errors="replace")
319
+ + ("\n[Вывод усечён]" if truncated else "")
320
+ )
321
+
322
+ @staticmethod
323
+ async def stop(process: asyncio.subprocess.Process) -> None:
324
+ if os.name == "nt":
325
+ killer = await asyncio.create_subprocess_exec(
326
+ "taskkill",
327
+ "/PID",
328
+ str(process.pid),
329
+ "/T",
330
+ "/F",
331
+ stdout=asyncio.subprocess.DEVNULL,
332
+ stderr=asyncio.subprocess.DEVNULL,
333
+ )
334
+ await killer.wait()
335
+ else:
336
+ try:
337
+ os.killpg(process.pid, signal.SIGKILL)
338
+ except ProcessLookupError:
339
+ pass
340
+ await process.wait()
341
+
342
+ async def undo(self) -> str:
343
+ group = next((group for group in reversed(self.snapshots) if group), None)
344
+ if not group:
345
+ return "Нет правок для отмены. Команды не откатываются."
346
+ expected: dict[Path, str | None] = {}
347
+ for change in group:
348
+ expected[Path(change["path"])] = change["after"]
349
+ for path, content in expected.items():
350
+ checked = await self.permissions.path(str(path), "Отмена правки")
351
+ if checked != path or not path.exists() or text_file(path) != content:
352
+ raise ValueError("Файл изменён после правки; отмена остановлена.")
353
+
354
+ def restore() -> None:
355
+ for change in reversed(group):
356
+ path = Path(change["path"])
357
+ if change["before"] is None:
358
+ path.unlink()
359
+ else:
360
+ with path.open("w", encoding="utf-8", newline="") as stream:
361
+ stream.write(change["before"])
362
+
363
+ restore()
364
+ self.snapshots.remove(group)
365
+ self.reads.clear()
366
+ return "Последняя группа правок отменена. Команды не откатывались."