anixcode 0.8.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.
- anixcode/__init__.py +3 -0
- anixcode/__main__.py +4 -0
- anixcode/agent.py +358 -0
- anixcode/airpc.py +59 -0
- anixcode/checkpoints.py +87 -0
- anixcode/cli.py +185 -0
- anixcode/commands.py +218 -0
- anixcode/compaction.py +91 -0
- anixcode/danger.py +85 -0
- anixcode/i18n.py +67 -0
- anixcode/i18n_en.py +293 -0
- anixcode/llm.py +258 -0
- anixcode/mentions.py +116 -0
- anixcode/projects.py +142 -0
- anixcode/prompts.py +64 -0
- anixcode/providers.py +67 -0
- anixcode/settings.py +105 -0
- anixcode/storage.py +129 -0
- anixcode/tools/__init__.py +15 -0
- anixcode/tools/base.py +203 -0
- anixcode/tools/files.py +248 -0
- anixcode/tools/search.py +107 -0
- anixcode/tools/shell.py +86 -0
- anixcode/tui/__init__.py +0 -0
- anixcode/tui/anim.py +242 -0
- anixcode/tui/app.py +812 -0
- anixcode/tui/app.tcss +281 -0
- anixcode/tui/screens.py +556 -0
- anixcode/tui/widgets.py +374 -0
- anixcode-0.8.0.dist-info/METADATA +241 -0
- anixcode-0.8.0.dist-info/RECORD +35 -0
- anixcode-0.8.0.dist-info/WHEEL +5 -0
- anixcode-0.8.0.dist-info/entry_points.txt +2 -0
- anixcode-0.8.0.dist-info/licenses/LICENSE +21 -0
- anixcode-0.8.0.dist-info/top_level.txt +1 -0
anixcode/tools/base.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Tool interface and the context tools run in."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import difflib
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, ClassVar, Literal
|
|
14
|
+
|
|
15
|
+
Kind = Literal["read", "edit", "exec"]
|
|
16
|
+
|
|
17
|
+
IGNORE_DIRS = frozenset({
|
|
18
|
+
".git", "node_modules", "__pycache__", ".venv", "venv", ".mypy_cache", ".pytest_cache", ".ruff_cache",
|
|
19
|
+
"dist", "build", ".next", ".idea", ".vscode", "target", ".tox", ".cache", ".gradle",
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# Never walked into: Windows profile junk and junction loops ("Application Data" points back into AppData).
|
|
24
|
+
WALK_SKIP = frozenset(n.lower() for n in (
|
|
25
|
+
"AppData", "Application Data", "Local Settings", "Cookies", "NetHood", "PrintHood", "Recent", "SendTo",
|
|
26
|
+
"Start Menu", "Templates", "My Documents", "$Recycle.Bin", "System Volume Information", "Library",
|
|
27
|
+
"Windows", "Program Files", "Program Files (x86)", "ProgramData",
|
|
28
|
+
))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SearchTimeout(Exception):
|
|
32
|
+
"""A file walk took too long (searching a whole disk or home folder)."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def skip_dir(name: str, path: str = "") -> bool:
|
|
36
|
+
if name in IGNORE_DIRS or name.endswith(".egg-info") or name.lower() in WALK_SKIP:
|
|
37
|
+
return True
|
|
38
|
+
isjunction = getattr(os.path, "isjunction", None)
|
|
39
|
+
return bool(path and isjunction and isjunction(path))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def glob_regex(pattern: str) -> re.Pattern[str]:
|
|
43
|
+
"""Glob with ** support -> regex over '/'-separated relative paths."""
|
|
44
|
+
out, i = [], 0
|
|
45
|
+
pattern = pattern.replace("\\", "/").lstrip("./") if pattern not in (".", "./") else "*"
|
|
46
|
+
while i < len(pattern):
|
|
47
|
+
if pattern.startswith("**/", i):
|
|
48
|
+
out.append("(?:.*/)?")
|
|
49
|
+
i += 3
|
|
50
|
+
elif pattern.startswith("**", i):
|
|
51
|
+
out.append(".*")
|
|
52
|
+
i += 2
|
|
53
|
+
elif pattern[i] == "*":
|
|
54
|
+
out.append("[^/]*")
|
|
55
|
+
i += 1
|
|
56
|
+
elif pattern[i] == "?":
|
|
57
|
+
out.append("[^/]")
|
|
58
|
+
i += 1
|
|
59
|
+
elif pattern[i] == "[":
|
|
60
|
+
j = pattern.find("]", i)
|
|
61
|
+
if j == -1:
|
|
62
|
+
out.append(re.escape("["))
|
|
63
|
+
i += 1
|
|
64
|
+
else:
|
|
65
|
+
out.append("[" + pattern[i + 1:j].replace("!", "^", 1) + "]")
|
|
66
|
+
i = j + 1
|
|
67
|
+
else:
|
|
68
|
+
out.append(re.escape(pattern[i]))
|
|
69
|
+
i += 1
|
|
70
|
+
return re.compile("".join(out), re.IGNORECASE if sys.platform == "win32" else 0)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class ToolError(Exception):
|
|
74
|
+
"""Expected failure; the message is shown to the model so it can fix its call."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class ToolResult:
|
|
79
|
+
output: str # what the model sees
|
|
80
|
+
title: str = "" # short line for the UI
|
|
81
|
+
diff: str | None = None # unified diff for file changes
|
|
82
|
+
error: bool = False
|
|
83
|
+
added: int = 0
|
|
84
|
+
removed: int = 0
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class ToolContext:
|
|
89
|
+
root: Path
|
|
90
|
+
read_files: dict[Path, float] = field(default_factory=dict) # path -> mtime when last read
|
|
91
|
+
before_write: Callable[[Path], None] | None = None # snapshot hook used by /undo
|
|
92
|
+
|
|
93
|
+
def about_to_write(self, p: Path) -> None:
|
|
94
|
+
if self.before_write is not None:
|
|
95
|
+
self.before_write(p)
|
|
96
|
+
|
|
97
|
+
def resolve(self, raw: str | None, must_exist: bool = False) -> Path:
|
|
98
|
+
if not raw or not str(raw).strip():
|
|
99
|
+
raw = "."
|
|
100
|
+
p = Path(os.path.expanduser(str(raw)))
|
|
101
|
+
p = (p if p.is_absolute() else self.root / p).resolve()
|
|
102
|
+
root = self.root.resolve()
|
|
103
|
+
if p != root and root not in p.parents:
|
|
104
|
+
raise ToolError(f"Path is outside the project folder: {raw}")
|
|
105
|
+
if must_exist and not p.exists():
|
|
106
|
+
raise ToolError(f"Not found: {self.rel(p)}")
|
|
107
|
+
return p
|
|
108
|
+
|
|
109
|
+
def rel(self, p: Path) -> str:
|
|
110
|
+
try:
|
|
111
|
+
return p.resolve().relative_to(self.root.resolve()).as_posix() or "."
|
|
112
|
+
except ValueError:
|
|
113
|
+
return str(p)
|
|
114
|
+
|
|
115
|
+
def mark_read(self, p: Path) -> None:
|
|
116
|
+
self.read_files[p] = p.stat().st_mtime
|
|
117
|
+
|
|
118
|
+
def check_fresh(self, p: Path) -> None:
|
|
119
|
+
"""Edits require a prior read, and the file must not have changed since."""
|
|
120
|
+
if p not in self.read_files:
|
|
121
|
+
raise ToolError(f"Read {self.rel(p)} with the read tool before changing it.")
|
|
122
|
+
if p.stat().st_mtime != self.read_files[p]:
|
|
123
|
+
raise ToolError(f"{self.rel(p)} changed since you last read it. Read it again first.")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class Tool:
|
|
127
|
+
name: ClassVar[str]
|
|
128
|
+
kind: ClassVar[Kind] = "read"
|
|
129
|
+
description: ClassVar[str]
|
|
130
|
+
parameters: ClassVar[dict[str, Any]]
|
|
131
|
+
|
|
132
|
+
def schema(self) -> dict[str, Any]:
|
|
133
|
+
return {"type": "function", "function": {
|
|
134
|
+
"name": self.name, "description": self.description, "parameters": self.parameters}}
|
|
135
|
+
|
|
136
|
+
def title(self, args: dict[str, Any]) -> str:
|
|
137
|
+
"""Short description for the UI, e.g. 'read src/app.py'."""
|
|
138
|
+
return self.name
|
|
139
|
+
|
|
140
|
+
def preview(self, args: dict[str, Any], ctx: ToolContext) -> str | None:
|
|
141
|
+
"""What to show in the permission dialog (a diff or a command)."""
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
async def run(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
145
|
+
"""File tools do blocking disk work: run it in a thread so the interface never freezes."""
|
|
146
|
+
return await asyncio.to_thread(self.run_sync, args, ctx)
|
|
147
|
+
|
|
148
|
+
def run_sync(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
149
|
+
raise NotImplementedError
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def require(args: dict[str, Any], key: str, kind: type = str) -> Any:
|
|
153
|
+
value = args.get(key)
|
|
154
|
+
if not isinstance(value, kind) or (kind is str and value == "" and key != "new_string"):
|
|
155
|
+
raise ToolError(f"Parameter '{key}' is required ({kind.__name__}).")
|
|
156
|
+
return value
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def make_diff(old: str, new: str, path: str) -> tuple[str, int, int]:
|
|
160
|
+
lines = list(difflib.unified_diff(old.splitlines(keepends=True), new.splitlines(keepends=True),
|
|
161
|
+
fromfile=f"a/{path}", tofile=f"b/{path}", n=3))
|
|
162
|
+
added = sum(1 for ln in lines if ln.startswith("+") and not ln.startswith("+++"))
|
|
163
|
+
removed = sum(1 for ln in lines if ln.startswith("-") and not ln.startswith("---"))
|
|
164
|
+
text = "".join(ln if ln.endswith("\n") else ln + "\n" for ln in lines)
|
|
165
|
+
return text, added, removed
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def truncate(text: str, limit: int = 30_000) -> str:
|
|
169
|
+
if len(text) <= limit:
|
|
170
|
+
return text
|
|
171
|
+
head, tail = text[: limit // 2], text[-limit // 2:]
|
|
172
|
+
return f"{head}\n\n… [{len(text) - limit} characters cut] …\n\n{tail}"
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def is_binary(p: Path) -> bool:
|
|
176
|
+
try:
|
|
177
|
+
with open(p, "rb") as f:
|
|
178
|
+
return b"\0" in f.read(8192)
|
|
179
|
+
except OSError:
|
|
180
|
+
return False
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def read_text(p: Path) -> str:
|
|
184
|
+
data = p.read_bytes()
|
|
185
|
+
for enc in ("utf-8", "utf-8-sig", "cp1251"):
|
|
186
|
+
try:
|
|
187
|
+
return data.decode(enc)
|
|
188
|
+
except UnicodeDecodeError:
|
|
189
|
+
continue
|
|
190
|
+
return data.decode("utf-8", errors="replace")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def walk_files(base: Path, deadline: float | None = None):
|
|
194
|
+
"""All files under base, skipping ignored folders. Raises SearchTimeout after ``deadline``."""
|
|
195
|
+
if base.is_file():
|
|
196
|
+
yield base
|
|
197
|
+
return
|
|
198
|
+
for dirpath, dirnames, filenames in os.walk(base, followlinks=False):
|
|
199
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
200
|
+
raise SearchTimeout
|
|
201
|
+
dirnames[:] = sorted(d for d in dirnames if not skip_dir(d, os.path.join(dirpath, d)))
|
|
202
|
+
for name in sorted(filenames):
|
|
203
|
+
yield Path(dirpath) / name
|
anixcode/tools/files.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""File tools: read, write, edit, ls, glob."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from ..i18n import tr
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import time
|
|
10
|
+
|
|
11
|
+
from .base import (
|
|
12
|
+
SearchTimeout, Tool, ToolContext, ToolError, ToolResult, glob_regex, is_binary, make_diff, read_text, require,
|
|
13
|
+
skip_dir, walk_files,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
MAX_READ_LINES = 2000
|
|
17
|
+
MAX_LINE = 2000
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ReadTool(Tool):
|
|
21
|
+
name = "read"
|
|
22
|
+
description = (
|
|
23
|
+
"Read a text file. Returns lines prefixed with line numbers. For big files use offset "
|
|
24
|
+
"(1-based line) and limit. Always read a file before editing it."
|
|
25
|
+
)
|
|
26
|
+
parameters = {"type": "object", "properties": {
|
|
27
|
+
"path": {"type": "string", "description": "File path relative to the project root"},
|
|
28
|
+
"offset": {"type": "integer", "description": "First line to read (1-based)"},
|
|
29
|
+
"limit": {"type": "integer", "description": f"Number of lines (default {MAX_READ_LINES})"},
|
|
30
|
+
}, "required": ["path"]}
|
|
31
|
+
|
|
32
|
+
def title(self, args: dict[str, Any]) -> str:
|
|
33
|
+
return f"read {args.get('path', '')}"
|
|
34
|
+
|
|
35
|
+
def run_sync(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
36
|
+
p = ctx.resolve(require(args, "path"), must_exist=True)
|
|
37
|
+
if p.is_dir():
|
|
38
|
+
raise ToolError(f"{ctx.rel(p)} is a folder. Use ls.")
|
|
39
|
+
if p.stat().st_size > 10 * 1024 * 1024:
|
|
40
|
+
raise ToolError("File is larger than 10 MB.")
|
|
41
|
+
if is_binary(p):
|
|
42
|
+
raise ToolError(f"{ctx.rel(p)} is a binary file.")
|
|
43
|
+
lines = read_text(p).splitlines()
|
|
44
|
+
offset = max(1, int(args.get("offset") or 1))
|
|
45
|
+
limit = max(1, min(int(args.get("limit") or MAX_READ_LINES), MAX_READ_LINES))
|
|
46
|
+
chunk = lines[offset - 1: offset - 1 + limit]
|
|
47
|
+
width = len(str(offset + len(chunk)))
|
|
48
|
+
body = "\n".join(
|
|
49
|
+
f"{i:>{width}}\t{ln if len(ln) <= MAX_LINE else ln[:MAX_LINE] + '…'}"
|
|
50
|
+
for i, ln in enumerate(chunk, start=offset)
|
|
51
|
+
)
|
|
52
|
+
ctx.mark_read(p)
|
|
53
|
+
end = offset + len(chunk) - 1
|
|
54
|
+
if not lines:
|
|
55
|
+
body = "(empty file)"
|
|
56
|
+
elif end < len(lines):
|
|
57
|
+
body += f"\n\n(lines {offset}-{end} of {len(lines)}; use offset={end + 1} to read more)"
|
|
58
|
+
return ToolResult(body, title=tr('{0} строк', len(chunk)))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class WriteTool(Tool):
|
|
62
|
+
name = "write"
|
|
63
|
+
kind = "edit"
|
|
64
|
+
description = (
|
|
65
|
+
"Create a new file or fully overwrite an existing one. Prefer the edit tool for changes to "
|
|
66
|
+
"existing files. Overwriting requires reading the file first."
|
|
67
|
+
)
|
|
68
|
+
parameters = {"type": "object", "properties": {
|
|
69
|
+
"path": {"type": "string"}, "content": {"type": "string", "description": "Full file content"},
|
|
70
|
+
}, "required": ["path", "content"]}
|
|
71
|
+
|
|
72
|
+
def title(self, args: dict[str, Any]) -> str:
|
|
73
|
+
return f"write {args.get('path', '')}"
|
|
74
|
+
|
|
75
|
+
def _plan(self, args: dict[str, Any], ctx: ToolContext) -> tuple[Path, str, str]:
|
|
76
|
+
p = ctx.resolve(require(args, "path"))
|
|
77
|
+
content = args.get("content")
|
|
78
|
+
if not isinstance(content, str):
|
|
79
|
+
raise ToolError("Parameter 'content' is required (string).")
|
|
80
|
+
if p.is_dir():
|
|
81
|
+
raise ToolError(f"{ctx.rel(p)} is a folder.")
|
|
82
|
+
old = ""
|
|
83
|
+
if p.exists():
|
|
84
|
+
ctx.check_fresh(p)
|
|
85
|
+
old = read_text(p)
|
|
86
|
+
return p, old, content
|
|
87
|
+
|
|
88
|
+
def preview(self, args: dict[str, Any], ctx: ToolContext) -> str | None:
|
|
89
|
+
try:
|
|
90
|
+
p, old, new = self._plan(args, ctx)
|
|
91
|
+
except ToolError:
|
|
92
|
+
return None
|
|
93
|
+
return make_diff(old, new, ctx.rel(p))[0]
|
|
94
|
+
|
|
95
|
+
def run_sync(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
96
|
+
p, old, new = self._plan(args, ctx)
|
|
97
|
+
existed = p.exists()
|
|
98
|
+
ctx.about_to_write(p)
|
|
99
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
100
|
+
p.write_text(new, encoding="utf-8", newline="")
|
|
101
|
+
ctx.mark_read(p)
|
|
102
|
+
diff, added, removed = make_diff(old, new, ctx.rel(p))
|
|
103
|
+
verb = "Updated" if existed else "Created"
|
|
104
|
+
return ToolResult(f"{verb} {ctx.rel(p)} ({len(new.splitlines())} lines).", title=ctx.rel(p),
|
|
105
|
+
diff=diff, added=added, removed=removed)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class EditTool(Tool):
|
|
109
|
+
name = "edit"
|
|
110
|
+
kind = "edit"
|
|
111
|
+
description = (
|
|
112
|
+
"Replace an exact piece of text in a file. old_string must match the file exactly (including "
|
|
113
|
+
"indentation) and be unique; include a few surrounding lines to make it unique, or set "
|
|
114
|
+
"replace_all to change every occurrence. Read the file first."
|
|
115
|
+
)
|
|
116
|
+
parameters = {"type": "object", "properties": {
|
|
117
|
+
"path": {"type": "string"},
|
|
118
|
+
"old_string": {"type": "string", "description": "Exact text to replace"},
|
|
119
|
+
"new_string": {"type": "string", "description": "Replacement text"},
|
|
120
|
+
"replace_all": {"type": "boolean", "description": "Replace every occurrence (default false)"},
|
|
121
|
+
}, "required": ["path", "old_string", "new_string"]}
|
|
122
|
+
|
|
123
|
+
def title(self, args: dict[str, Any]) -> str:
|
|
124
|
+
return f"edit {args.get('path', '')}"
|
|
125
|
+
|
|
126
|
+
def _plan(self, args: dict[str, Any], ctx: ToolContext) -> tuple[Path, str, str]:
|
|
127
|
+
p = ctx.resolve(require(args, "path"), must_exist=True)
|
|
128
|
+
old_s, new_s = require(args, "old_string"), require(args, "new_string")
|
|
129
|
+
if old_s == new_s:
|
|
130
|
+
raise ToolError("old_string and new_string are identical.")
|
|
131
|
+
ctx.check_fresh(p)
|
|
132
|
+
text = read_text(p)
|
|
133
|
+
if old_s not in text and "\r\n" in text: # model wrote \n, file uses CRLF
|
|
134
|
+
old_s, new_s = old_s.replace("\n", "\r\n"), new_s.replace("\n", "\r\n")
|
|
135
|
+
count = text.count(old_s)
|
|
136
|
+
if count == 0:
|
|
137
|
+
raise ToolError("old_string was not found. Re-read the file and copy the text exactly.")
|
|
138
|
+
if count > 1 and not args.get("replace_all"):
|
|
139
|
+
raise ToolError(f"old_string was found {count} times. Add surrounding lines to make it unique "
|
|
140
|
+
"or set replace_all=true.")
|
|
141
|
+
new_text = text.replace(old_s, new_s) if args.get("replace_all") else text.replace(old_s, new_s, 1)
|
|
142
|
+
return p, text, new_text
|
|
143
|
+
|
|
144
|
+
def preview(self, args: dict[str, Any], ctx: ToolContext) -> str | None:
|
|
145
|
+
try:
|
|
146
|
+
p, old, new = self._plan(args, ctx)
|
|
147
|
+
except ToolError:
|
|
148
|
+
return None
|
|
149
|
+
return make_diff(old, new, ctx.rel(p))[0]
|
|
150
|
+
|
|
151
|
+
def run_sync(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
152
|
+
p, old, new = self._plan(args, ctx)
|
|
153
|
+
ctx.about_to_write(p)
|
|
154
|
+
p.write_text(new, encoding="utf-8", newline="")
|
|
155
|
+
ctx.mark_read(p)
|
|
156
|
+
diff, added, removed = make_diff(old, new, ctx.rel(p))
|
|
157
|
+
return ToolResult(f"Edited {ctx.rel(p)} (+{added} -{removed}).", title=ctx.rel(p), diff=diff,
|
|
158
|
+
added=added, removed=removed)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class LsTool(Tool):
|
|
162
|
+
name = "ls"
|
|
163
|
+
description = "List a folder as a tree (ignores .git, node_modules, virtualenvs, build folders)."
|
|
164
|
+
parameters = {"type": "object", "properties": {
|
|
165
|
+
"path": {"type": "string", "description": "Folder (default: project root)"},
|
|
166
|
+
"depth": {"type": "integer", "description": "How deep to go (default 2, max 5)"},
|
|
167
|
+
}}
|
|
168
|
+
LIMIT = 400
|
|
169
|
+
|
|
170
|
+
def title(self, args: dict[str, Any]) -> str:
|
|
171
|
+
return f"ls {args.get('path') or '.'}"
|
|
172
|
+
|
|
173
|
+
def run_sync(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
174
|
+
base = ctx.resolve(args.get("path"), must_exist=True)
|
|
175
|
+
if not base.is_dir():
|
|
176
|
+
raise ToolError(f"{ctx.rel(base)} is not a folder.")
|
|
177
|
+
depth = max(1, min(int(args.get("depth") or 2), 5))
|
|
178
|
+
lines: list[str] = [f"{ctx.rel(base)}/"]
|
|
179
|
+
count = 0
|
|
180
|
+
|
|
181
|
+
def walk(folder: Path, level: int) -> None:
|
|
182
|
+
nonlocal count
|
|
183
|
+
try:
|
|
184
|
+
entries = sorted(folder.iterdir(), key=lambda e: (not e.is_dir(), e.name.lower()))
|
|
185
|
+
except OSError:
|
|
186
|
+
return
|
|
187
|
+
for e in entries:
|
|
188
|
+
if count >= self.LIMIT or (e.is_dir() and skip_dir(e.name, str(e))):
|
|
189
|
+
continue
|
|
190
|
+
count += 1
|
|
191
|
+
lines.append(f"{' ' * level}{e.name}{'/' if e.is_dir() else ''}")
|
|
192
|
+
if e.is_dir() and level < depth:
|
|
193
|
+
walk(e, level + 1)
|
|
194
|
+
|
|
195
|
+
walk(base, 1)
|
|
196
|
+
if count >= self.LIMIT:
|
|
197
|
+
lines.append(f"… (stopped at {self.LIMIT} entries)")
|
|
198
|
+
return ToolResult("\n".join(lines), title=tr('{0} элементов', count))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class GlobTool(Tool):
|
|
202
|
+
name = "glob"
|
|
203
|
+
description = ("Find files by glob pattern, newest first. 'src/**/*.ts' matches paths; a pattern without '/' "
|
|
204
|
+
"like '*.py' or 'calc.py' matches file names in all subfolders.")
|
|
205
|
+
parameters = {"type": "object", "properties": {
|
|
206
|
+
"pattern": {"type": "string"}, "path": {"type": "string", "description": "Folder to search in"},
|
|
207
|
+
}, "required": ["pattern"]}
|
|
208
|
+
LIMIT = 100
|
|
209
|
+
TIME_LIMIT = 10.0
|
|
210
|
+
|
|
211
|
+
def title(self, args: dict[str, Any]) -> str:
|
|
212
|
+
return f"glob {args.get('pattern', '')}"
|
|
213
|
+
|
|
214
|
+
def run_sync(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
215
|
+
pattern = require(args, "pattern").replace("\\", "/")
|
|
216
|
+
base = ctx.resolve(args.get("path"), must_exist=True)
|
|
217
|
+
regex = glob_regex(pattern)
|
|
218
|
+
by_name = "/" not in pattern.strip("/")
|
|
219
|
+
found: list[Path] = []
|
|
220
|
+
timed_out = False
|
|
221
|
+
try:
|
|
222
|
+
for p in walk_files(base, deadline=time.monotonic() + self.TIME_LIMIT):
|
|
223
|
+
target = p.name if by_name else p.relative_to(base).as_posix()
|
|
224
|
+
if regex.fullmatch(target):
|
|
225
|
+
found.append(p)
|
|
226
|
+
if len(found) >= 5000:
|
|
227
|
+
break
|
|
228
|
+
except SearchTimeout:
|
|
229
|
+
timed_out = True
|
|
230
|
+
|
|
231
|
+
def mtime(p: Path) -> float:
|
|
232
|
+
try:
|
|
233
|
+
return os.stat(p).st_mtime
|
|
234
|
+
except OSError:
|
|
235
|
+
return 0.0
|
|
236
|
+
|
|
237
|
+
found.sort(key=mtime, reverse=True)
|
|
238
|
+
shown = [ctx.rel(p) for p in found[: self.LIMIT]]
|
|
239
|
+
out = "\n".join(shown) if shown else "No files found."
|
|
240
|
+
if len(found) > self.LIMIT:
|
|
241
|
+
out += f"\n… and {len(found) - self.LIMIT} more"
|
|
242
|
+
if timed_out:
|
|
243
|
+
out += (f"\n(search stopped after {self.TIME_LIMIT:.0f}s: the folder is huge. "
|
|
244
|
+
"Pass a narrower path, or ask the user to open the right project folder.)")
|
|
245
|
+
return ToolResult(out, title=tr('{0} файлов', len(found)) + (tr(" · стоп по времени") if timed_out else ""))
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
__all__ = ["ReadTool", "WriteTool", "EditTool", "LsTool", "GlobTool", "walk_files"]
|
anixcode/tools/search.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""grep: regex search in files (uses ripgrep when installed)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from ..i18n import tr
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import fnmatch
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
from .base import (
|
|
16
|
+
IGNORE_DIRS, WALK_SKIP, SearchTimeout, Tool, ToolContext, ToolError, ToolResult, is_binary, read_text, require,
|
|
17
|
+
walk_files,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
LIMIT = 100
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class GrepTool(Tool):
|
|
24
|
+
name = "grep"
|
|
25
|
+
description = (
|
|
26
|
+
"Search file contents with a regular expression. Returns path:line: text. Use include to filter "
|
|
27
|
+
"files, e.g. '*.py'."
|
|
28
|
+
)
|
|
29
|
+
parameters = {"type": "object", "properties": {
|
|
30
|
+
"pattern": {"type": "string", "description": "Regular expression"},
|
|
31
|
+
"path": {"type": "string", "description": "Folder or file to search (default: project root)"},
|
|
32
|
+
"include": {"type": "string", "description": "File name glob, e.g. '*.ts'"},
|
|
33
|
+
}, "required": ["pattern"]}
|
|
34
|
+
|
|
35
|
+
def title(self, args: dict[str, Any]) -> str:
|
|
36
|
+
return f"grep {args.get('pattern', '')}"
|
|
37
|
+
|
|
38
|
+
async def run(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
39
|
+
pattern = require(args, "pattern")
|
|
40
|
+
try:
|
|
41
|
+
regex = re.compile(pattern)
|
|
42
|
+
except re.error as e:
|
|
43
|
+
raise ToolError(f"Bad regular expression: {e}") from None
|
|
44
|
+
base = ctx.resolve(args.get("path"), must_exist=True)
|
|
45
|
+
include = args.get("include") or None
|
|
46
|
+
rg = shutil.which("rg")
|
|
47
|
+
if rg:
|
|
48
|
+
matches = await self._ripgrep(rg, pattern, str(base), include, ctx)
|
|
49
|
+
else:
|
|
50
|
+
matches = await asyncio.to_thread(self._python, regex, base, include, ctx)
|
|
51
|
+
if not matches:
|
|
52
|
+
return ToolResult("No matches.", title=tr("нет совпадений"))
|
|
53
|
+
out = "\n".join(matches[:LIMIT])
|
|
54
|
+
if len(matches) > LIMIT:
|
|
55
|
+
out += f"\n… more than {LIMIT} matches, narrow the search"
|
|
56
|
+
return ToolResult(out, title=tr('{0}{1} совпадений', min(len(matches), LIMIT), '+' if len(matches) > LIMIT else ''))
|
|
57
|
+
|
|
58
|
+
async def _ripgrep(self, rg: str, pattern: str, base: str, include: str | None, ctx: ToolContext) -> list[str]:
|
|
59
|
+
cmd = [rg, "--line-number", "--no-heading", "--color", "never", "--max-columns", "300",
|
|
60
|
+
"--max-count", "50", "--path-separator", "/", "-e", pattern]
|
|
61
|
+
for d in sorted(IGNORE_DIRS) + sorted(WALK_SKIP):
|
|
62
|
+
cmd += ["--glob", f"!{d}/"]
|
|
63
|
+
if include:
|
|
64
|
+
cmd += ["--glob", include]
|
|
65
|
+
target = ctx.rel(Path(base))
|
|
66
|
+
cmd.append(target if target != "." else ".")
|
|
67
|
+
# Run from the project root so paths come back relative (no "C:" drive colons to trip over).
|
|
68
|
+
proc = await asyncio.create_subprocess_exec(*cmd, cwd=ctx.root, stdout=asyncio.subprocess.PIPE,
|
|
69
|
+
stderr=asyncio.subprocess.DEVNULL)
|
|
70
|
+
try:
|
|
71
|
+
out, _ = await asyncio.wait_for(proc.communicate(), timeout=30)
|
|
72
|
+
except asyncio.TimeoutError:
|
|
73
|
+
proc.kill()
|
|
74
|
+
return ["(search stopped after 30s: pass a narrower path)"]
|
|
75
|
+
lines = []
|
|
76
|
+
for line in out.decode("utf-8", errors="replace").splitlines():
|
|
77
|
+
lines.append(line[2:] if line.startswith("./") else line)
|
|
78
|
+
if len(lines) > LIMIT:
|
|
79
|
+
break
|
|
80
|
+
return lines
|
|
81
|
+
|
|
82
|
+
@staticmethod
|
|
83
|
+
def _python(regex: re.Pattern[str], base, include: str | None, ctx: ToolContext) -> list[str]:
|
|
84
|
+
out: list[str] = []
|
|
85
|
+
files = walk_files(base, deadline=time.monotonic() + 15)
|
|
86
|
+
while True:
|
|
87
|
+
try:
|
|
88
|
+
p = next(files)
|
|
89
|
+
except StopIteration:
|
|
90
|
+
break
|
|
91
|
+
except SearchTimeout:
|
|
92
|
+
out.append("(search stopped after 15s: the folder is huge, pass a narrower path)")
|
|
93
|
+
break
|
|
94
|
+
if include and not fnmatch.fnmatch(p.name, include):
|
|
95
|
+
continue
|
|
96
|
+
try:
|
|
97
|
+
if p.stat().st_size > 2 * 1024 * 1024 or is_binary(p):
|
|
98
|
+
continue
|
|
99
|
+
text = read_text(p)
|
|
100
|
+
except OSError:
|
|
101
|
+
continue
|
|
102
|
+
for i, line in enumerate(text.splitlines(), 1):
|
|
103
|
+
if regex.search(line):
|
|
104
|
+
out.append(f"{ctx.rel(p)}:{i}: {line.strip()[:300]}")
|
|
105
|
+
if len(out) > LIMIT:
|
|
106
|
+
return out
|
|
107
|
+
return out
|
anixcode/tools/shell.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""bash: run a shell command in the project folder (PowerShell on Windows)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import signal
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .base import Tool, ToolContext, ToolError, ToolResult, require, truncate
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def shell_name() -> str:
|
|
16
|
+
return "PowerShell" if sys.platform == "win32" else "bash"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _command(cmd: str) -> list[str]:
|
|
20
|
+
if sys.platform == "win32":
|
|
21
|
+
exe = shutil.which("pwsh") or "powershell"
|
|
22
|
+
prefix = "[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; $ProgressPreference='SilentlyContinue'; "
|
|
23
|
+
return [exe, "-NoProfile", "-NonInteractive", "-Command", prefix + cmd]
|
|
24
|
+
return [shutil.which("bash") or "/bin/sh", "-c", cmd]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
async def _kill(proc: asyncio.subprocess.Process) -> None:
|
|
28
|
+
if proc.returncode is not None:
|
|
29
|
+
return
|
|
30
|
+
try:
|
|
31
|
+
if sys.platform == "win32":
|
|
32
|
+
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], capture_output=True, check=False)
|
|
33
|
+
else:
|
|
34
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
35
|
+
except (OSError, ProcessLookupError):
|
|
36
|
+
pass
|
|
37
|
+
try:
|
|
38
|
+
await asyncio.wait_for(proc.wait(), timeout=5)
|
|
39
|
+
except asyncio.TimeoutError:
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class BashTool(Tool):
|
|
44
|
+
name = "bash"
|
|
45
|
+
kind = "exec"
|
|
46
|
+
description = (
|
|
47
|
+
f"Run a {shell_name()} command in the project folder and return its output (stdout+stderr). "
|
|
48
|
+
"Use it for tests, builds, git, package managers. Do not use it to read or edit files: use the "
|
|
49
|
+
"file tools. Interactive commands are not supported."
|
|
50
|
+
)
|
|
51
|
+
parameters = {"type": "object", "properties": {
|
|
52
|
+
"command": {"type": "string"},
|
|
53
|
+
"timeout": {"type": "integer", "description": "Seconds (default 120, max 600)"},
|
|
54
|
+
"description": {"type": "string", "description": "5-10 words on what the command does"},
|
|
55
|
+
}, "required": ["command"]}
|
|
56
|
+
|
|
57
|
+
def title(self, args: dict[str, Any]) -> str:
|
|
58
|
+
cmd = " ".join(str(args.get("command", "")).split())
|
|
59
|
+
return cmd if len(cmd) <= 100 else cmd[:99] + "…"
|
|
60
|
+
|
|
61
|
+
def preview(self, args: dict[str, Any], ctx: ToolContext) -> str | None:
|
|
62
|
+
return str(args.get("command", ""))
|
|
63
|
+
|
|
64
|
+
async def run(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
65
|
+
cmd = require(args, "command")
|
|
66
|
+
timeout = max(1, min(int(args.get("timeout") or 120), 600))
|
|
67
|
+
extra = {"start_new_session": True} if sys.platform != "win32" else {
|
|
68
|
+
"creationflags": subprocess.CREATE_NO_WINDOW}
|
|
69
|
+
try:
|
|
70
|
+
proc = await asyncio.create_subprocess_exec(
|
|
71
|
+
*_command(cmd), cwd=ctx.root, stdin=asyncio.subprocess.DEVNULL,
|
|
72
|
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, **extra)
|
|
73
|
+
except OSError as e:
|
|
74
|
+
raise ToolError(f"Could not start the shell: {e}") from None
|
|
75
|
+
try:
|
|
76
|
+
out, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
|
77
|
+
except asyncio.TimeoutError:
|
|
78
|
+
await _kill(proc)
|
|
79
|
+
return ToolResult(f"Command timed out after {timeout}s and was stopped.", title=f"⏱ {timeout}s", error=True)
|
|
80
|
+
except asyncio.CancelledError:
|
|
81
|
+
await _kill(proc)
|
|
82
|
+
raise
|
|
83
|
+
text = truncate(out.decode("utf-8", errors="replace").replace("\r\n", "\n"))
|
|
84
|
+
code = proc.returncode
|
|
85
|
+
body = (text.rstrip() or "(no output)") + f"\n\n[exit code {code}]"
|
|
86
|
+
return ToolResult(body, title=f"→ {code}", error=code != 0)
|
anixcode/tui/__init__.py
ADDED
|
File without changes
|