rigcode 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.
- rigcode/__init__.py +4 -0
- rigcode/__main__.py +4 -0
- rigcode/agent/__init__.py +0 -0
- rigcode/agent/loop.py +627 -0
- rigcode/agent/mentions.py +70 -0
- rigcode/agent/prompts.py +195 -0
- rigcode/agent/runtime.py +535 -0
- rigcode/agent/session.py +165 -0
- rigcode/agent/state.py +161 -0
- rigcode/cli.py +283 -0
- rigcode/config.py +284 -0
- rigcode/doctor.py +158 -0
- rigcode/extensions.py +275 -0
- rigcode/hooks.py +142 -0
- rigcode/llm/__init__.py +0 -0
- rigcode/llm/client.py +259 -0
- rigcode/llm/probe.py +229 -0
- rigcode/llm/stream.py +240 -0
- rigcode/llm/textmode.py +161 -0
- rigcode/llm/types.py +92 -0
- rigcode/llm/wire.py +76 -0
- rigcode/mcp.py +329 -0
- rigcode/permissions.py +221 -0
- rigcode/prompts/agents/coder.md +13 -0
- rigcode/prompts/agents/debugger.md +14 -0
- rigcode/prompts/agents/explore.md +22 -0
- rigcode/prompts/agents/plan.md +21 -0
- rigcode/prompts/agents/researcher.md +14 -0
- rigcode/prompts/agents/reviewer.md +18 -0
- rigcode/prompts/agents/verifier.md +15 -0
- rigcode/prompts/commit.md +5 -0
- rigcode/prompts/compact.md +24 -0
- rigcode/prompts/init.md +10 -0
- rigcode/prompts/system.md +27 -0
- rigcode/tools/__init__.py +0 -0
- rigcode/tools/base.py +245 -0
- rigcode/tools/bashsafety.py +262 -0
- rigcode/tools/editmatch.py +367 -0
- rigcode/tools/files.py +534 -0
- rigcode/tools/interact.py +69 -0
- rigcode/tools/search.py +309 -0
- rigcode/tools/shell.py +424 -0
- rigcode/tools/skill.py +37 -0
- rigcode/tools/task.py +54 -0
- rigcode/tools/todo.py +62 -0
- rigcode/tools/web.py +346 -0
- rigcode/ui/__init__.py +0 -0
- rigcode/ui/base.py +69 -0
- rigcode/ui/commands.py +581 -0
- rigcode/ui/plain.py +321 -0
- rigcode/ui/render.py +207 -0
- rigcode/ui/terminal.py +1154 -0
- rigcode/utils/__init__.py +0 -0
- rigcode/utils/files.py +176 -0
- rigcode/utils/frontmatter.py +38 -0
- rigcode/utils/globmatch.py +91 -0
- rigcode/utils/jsonrepair.py +110 -0
- rigcode/utils/paths.py +83 -0
- rigcode/utils/text.py +105 -0
- rigcode-0.1.0.dist-info/METADATA +203 -0
- rigcode-0.1.0.dist-info/RECORD +64 -0
- rigcode-0.1.0.dist-info/WHEEL +4 -0
- rigcode-0.1.0.dist-info/entry_points.txt +2 -0
- rigcode-0.1.0.dist-info/licenses/LICENSE +21 -0
rigcode/tools/files.py
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
"""File tools: Read, Write, Edit, MultiEdit."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import difflib
|
|
6
|
+
import json
|
|
7
|
+
import warnings
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from rigcode.tools.base import Tool, ToolContext, ToolResult
|
|
11
|
+
from rigcode.tools.editmatch import EditError, apply_edit, find_omission_placeholder
|
|
12
|
+
from rigcode.utils.files import (
|
|
13
|
+
IMAGE_EXTENSIONS,
|
|
14
|
+
LFMap,
|
|
15
|
+
is_binary_file,
|
|
16
|
+
list_project_files,
|
|
17
|
+
read_text_file,
|
|
18
|
+
write_text_file,
|
|
19
|
+
)
|
|
20
|
+
from rigcode.utils.paths import display_path, resolve_path
|
|
21
|
+
from rigcode.utils.text import number_lines, one_line
|
|
22
|
+
|
|
23
|
+
DEFAULT_READ_LINES = 1000
|
|
24
|
+
MAX_LINE_CHARS = 2000
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _suggest_paths(path: Path, ctx: ToolContext, limit: int = 5) -> list[str]:
|
|
28
|
+
"""Similar existing paths to help the model recover from a wrong path."""
|
|
29
|
+
try:
|
|
30
|
+
files = list_project_files(ctx.rt.project_root, max_files=50_000)
|
|
31
|
+
except Exception: # noqa: BLE001 - suggestions are best effort
|
|
32
|
+
return []
|
|
33
|
+
name = path.name.lower()
|
|
34
|
+
same_name = [f for f in files if f.rsplit("/", 1)[-1].lower() == name]
|
|
35
|
+
if same_name:
|
|
36
|
+
return same_name[:limit]
|
|
37
|
+
names = {f.rsplit("/", 1)[-1]: f for f in files}
|
|
38
|
+
close = difflib.get_close_matches(path.name, list(names), n=limit, cutoff=0.7)
|
|
39
|
+
return [names[c] for c in close]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _not_found(path: Path, ctx: ToolContext) -> ToolResult:
|
|
43
|
+
shown = display_path(path, ctx.cwd)
|
|
44
|
+
msg = f"File does not exist: {shown} (working directory: {ctx.cwd})."
|
|
45
|
+
sugg = _suggest_paths(path, ctx)
|
|
46
|
+
if sugg:
|
|
47
|
+
msg += " Did you mean: " + ", ".join(sugg) + "?"
|
|
48
|
+
return ToolResult.error(msg, summary=f"Not found: {shown}")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def syntax_problem(path: Path, text: str) -> str | None:
|
|
52
|
+
ext = path.suffix.lower()
|
|
53
|
+
try:
|
|
54
|
+
if ext in (".py", ".pyw"):
|
|
55
|
+
with warnings.catch_warnings():
|
|
56
|
+
warnings.simplefilter("ignore")
|
|
57
|
+
compile(text, str(path), "exec", dont_inherit=True)
|
|
58
|
+
elif ext == ".json" and text.strip():
|
|
59
|
+
json.loads(text)
|
|
60
|
+
elif ext in (".yaml", ".yml"):
|
|
61
|
+
import yaml
|
|
62
|
+
list(yaml.safe_load_all(text))
|
|
63
|
+
elif ext == ".toml":
|
|
64
|
+
try:
|
|
65
|
+
import tomllib # type: ignore[import-not-found]
|
|
66
|
+
except ImportError:
|
|
67
|
+
return None
|
|
68
|
+
tomllib.loads(text)
|
|
69
|
+
except SyntaxError as e:
|
|
70
|
+
return f"Python syntax error at line {e.lineno}: {e.msg}"
|
|
71
|
+
except json.JSONDecodeError as e:
|
|
72
|
+
return f"JSON syntax error at line {e.lineno}, column {e.colno}: {e.msg}"
|
|
73
|
+
except Exception as e: # noqa: BLE001 - yaml/toml errors
|
|
74
|
+
return f"{ext[1:].upper()} syntax error: {one_line(str(e), 200)}"
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _syntax_warning(path: Path, before: str | None, after: str) -> str:
|
|
79
|
+
problem = syntax_problem(path, after)
|
|
80
|
+
if not problem:
|
|
81
|
+
return ""
|
|
82
|
+
if before is not None and syntax_problem(path, before):
|
|
83
|
+
return "" # already broken before this edit; don't nag
|
|
84
|
+
return f"\nWARNING: the file now has a syntax error - {problem}. Fix it before moving on."
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def make_diff(old: str, new: str, path_label: str, context: int = 2) -> tuple[str, int, int]:
|
|
88
|
+
diff = list(difflib.unified_diff(old.splitlines(), new.splitlines(), f"a/{path_label}", f"b/{path_label}",
|
|
89
|
+
n=context, lineterm=""))
|
|
90
|
+
added = sum(1 for l in diff if l.startswith("+") and not l.startswith("+++"))
|
|
91
|
+
removed = sum(1 for l in diff if l.startswith("-") and not l.startswith("---"))
|
|
92
|
+
return "\n".join(diff), added, removed
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _snippet(text: str, first_line: int, n_lines: int, pad: int = 3, cap: int = 30) -> str:
|
|
96
|
+
lines = text.split("\n")
|
|
97
|
+
start = max(1, first_line - pad)
|
|
98
|
+
end = min(len(lines), first_line + max(n_lines, 1) - 1 + pad)
|
|
99
|
+
if end - start + 1 > cap:
|
|
100
|
+
end = start + cap - 1
|
|
101
|
+
return number_lines(lines[start - 1:end], start)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _check_editable(path: Path, ctx: ToolContext, *, must_exist: bool, partial_ok: bool) -> ToolResult | None:
|
|
105
|
+
if path.exists() and path.is_dir():
|
|
106
|
+
return ToolResult.error(f"{display_path(path, ctx.cwd)} is a directory, not a file.")
|
|
107
|
+
if must_exist and not path.exists():
|
|
108
|
+
return _not_found(path, ctx)
|
|
109
|
+
if path.exists() and ctx.rt.settings.get("require_read_before_edit", True):
|
|
110
|
+
tracker = ctx.rt.file_state
|
|
111
|
+
if not tracker.was_read(path, partial_ok=partial_ok):
|
|
112
|
+
why = ("in full before overwriting it (you have only seen some of its lines)"
|
|
113
|
+
if tracker.was_read(path, partial_ok=True) else
|
|
114
|
+
"before modifying it (so your edit is based on its current contents)")
|
|
115
|
+
return ToolResult.error(f"You must Read {display_path(path, ctx.cwd)} {why}. Read it, then retry.",
|
|
116
|
+
summary="File not read yet")
|
|
117
|
+
if tracker.changed_since_read(path):
|
|
118
|
+
return ToolResult.error(
|
|
119
|
+
f"{display_path(path, ctx.cwd)} was modified since you last read it (by the user or another "
|
|
120
|
+
"process). Read it again, then redo your change.", summary="File changed since read")
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class ReadTool(Tool):
|
|
125
|
+
name = "Read"
|
|
126
|
+
kind = "read"
|
|
127
|
+
read_only = True
|
|
128
|
+
description = (
|
|
129
|
+
"Read a text file. Output lines are prefixed with their line number and a tab (cat -n style); that "
|
|
130
|
+
"prefix is not part of the file. Returns up to 1000 lines - for large files use Grep to find the "
|
|
131
|
+
"relevant region, then pass offset (1-based start line) and limit. Reading a directory lists it. "
|
|
132
|
+
"Issue several Read calls in one reply to read multiple files at once. Don't re-read a file you just "
|
|
133
|
+
"edited: the edit result already shows the updated lines."
|
|
134
|
+
)
|
|
135
|
+
parameters = {
|
|
136
|
+
"type": "object",
|
|
137
|
+
"properties": {
|
|
138
|
+
"file_path": {"type": "string", "description": "Absolute path, or relative to the working directory"},
|
|
139
|
+
"offset": {"type": "integer", "description": "1-based line number to start reading from"},
|
|
140
|
+
"limit": {"type": "integer", "description": "Maximum number of lines to return"},
|
|
141
|
+
},
|
|
142
|
+
"required": ["file_path"],
|
|
143
|
+
}
|
|
144
|
+
aliases = {"path": "file_path", "filepath": "file_path", "file": "file_path", "filename": "file_path",
|
|
145
|
+
"line_offset": "offset", "start_line": "offset", "n_lines": "limit", "lines": "limit",
|
|
146
|
+
"num_lines": "limit", "max_lines": "limit"}
|
|
147
|
+
|
|
148
|
+
def permission_target(self, args: dict) -> str:
|
|
149
|
+
return str(args.get("file_path", ""))
|
|
150
|
+
|
|
151
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
152
|
+
path = resolve_path(args["file_path"], ctx.cwd)
|
|
153
|
+
shown = display_path(path, ctx.cwd)
|
|
154
|
+
if not path.exists():
|
|
155
|
+
return _not_found(path, ctx)
|
|
156
|
+
if path.is_dir():
|
|
157
|
+
return self._list_dir(path, shown)
|
|
158
|
+
suffix = path.suffix.lower()
|
|
159
|
+
if suffix in IMAGE_EXTENSIONS:
|
|
160
|
+
return self._image(path, shown, ctx)
|
|
161
|
+
if suffix == ".ipynb":
|
|
162
|
+
return self._notebook(path, shown, ctx)
|
|
163
|
+
if suffix == ".pdf":
|
|
164
|
+
return self._pdf(path, shown, ctx)
|
|
165
|
+
if is_binary_file(path):
|
|
166
|
+
size = path.stat().st_size
|
|
167
|
+
return ToolResult.error(f"{shown} is a binary file ({size:,} bytes); it cannot be shown as text.",
|
|
168
|
+
summary="Binary file")
|
|
169
|
+
try:
|
|
170
|
+
tf = read_text_file(path)
|
|
171
|
+
except OSError as e:
|
|
172
|
+
return ToolResult.error(f"Could not read {shown}: {e}")
|
|
173
|
+
ctx.rt.file_state.record(path)
|
|
174
|
+
text = tf.text
|
|
175
|
+
if not text:
|
|
176
|
+
return ToolResult(content=f"(file {shown} exists but is empty)", summary="Empty file")
|
|
177
|
+
lines = text.split("\n")
|
|
178
|
+
if lines and lines[-1] == "":
|
|
179
|
+
lines.pop()
|
|
180
|
+
total = len(lines)
|
|
181
|
+
offset = max(1, int(args.get("offset") or 1))
|
|
182
|
+
limit = int(args.get("limit") or DEFAULT_READ_LINES)
|
|
183
|
+
if offset > total:
|
|
184
|
+
return ToolResult.error(f"offset {offset} is past the end of {shown} ({total} lines).")
|
|
185
|
+
budget = int(ctx.rt.settings.get("context.read_max_chars", 30000))
|
|
186
|
+
selected, used = [], 0
|
|
187
|
+
for line in lines[offset - 1: offset - 1 + limit]:
|
|
188
|
+
cost = min(len(line), MAX_LINE_CHARS) + 8
|
|
189
|
+
if selected and used + cost > budget:
|
|
190
|
+
break
|
|
191
|
+
selected.append(line)
|
|
192
|
+
used += cost
|
|
193
|
+
end = offset + len(selected) - 1
|
|
194
|
+
body = number_lines(selected, offset, MAX_LINE_CHARS)
|
|
195
|
+
notes = []
|
|
196
|
+
if end < total or offset > 1:
|
|
197
|
+
notes.append(f"[Showing lines {offset}-{end} of {total} total."
|
|
198
|
+
+ (f" Continue with offset={end + 1}.]" if end < total else "]"))
|
|
199
|
+
content = body + ("\n" + "\n".join(notes) if notes else "")
|
|
200
|
+
return ToolResult(content=content, summary=f"Read {len(selected)} line{'s' if len(selected) != 1 else ''}"
|
|
201
|
+
+ (f" (of {total})" if len(selected) < total else ""))
|
|
202
|
+
|
|
203
|
+
def _list_dir(self, path: Path, shown: str) -> ToolResult:
|
|
204
|
+
try:
|
|
205
|
+
entries = sorted(path.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower()))
|
|
206
|
+
except OSError as e:
|
|
207
|
+
return ToolResult.error(f"Cannot list {shown}: {e}")
|
|
208
|
+
lines = [e.name + ("/" if e.is_dir() else "") for e in entries[:500]]
|
|
209
|
+
extra = f"\n... and {len(entries) - 500} more" if len(entries) > 500 else ""
|
|
210
|
+
return ToolResult(content=f"{shown} is a directory with {len(entries)} entries:\n" + "\n".join(lines) + extra,
|
|
211
|
+
summary=f"Listed {len(entries)} entries")
|
|
212
|
+
|
|
213
|
+
def _image(self, path: Path, shown: str, ctx: ToolContext) -> ToolResult:
|
|
214
|
+
size = path.stat().st_size
|
|
215
|
+
if not ctx.rt.server.vision:
|
|
216
|
+
return ToolResult.error(f"{shown} is an image ({size:,} bytes). The current model/server has no vision "
|
|
217
|
+
"support, so it cannot be viewed.", summary="Image (no vision)")
|
|
218
|
+
if size > 10 * 1024 * 1024:
|
|
219
|
+
return ToolResult.error(f"{shown} is too large to attach ({size:,} bytes).")
|
|
220
|
+
mime = {"jpg": "jpeg"}.get(path.suffix.lower()[1:], path.suffix.lower()[1:])
|
|
221
|
+
data = base64.b64encode(path.read_bytes()).decode("ascii")
|
|
222
|
+
return ToolResult(content=f"Image {shown} ({size:,} bytes) is attached below.",
|
|
223
|
+
images=[{"mime": f"image/{mime}", "data": data}], summary="Read image")
|
|
224
|
+
|
|
225
|
+
def _notebook(self, path: Path, shown: str, ctx: ToolContext) -> ToolResult:
|
|
226
|
+
try:
|
|
227
|
+
nb = json.loads(path.read_text(encoding="utf-8"))
|
|
228
|
+
except (OSError, json.JSONDecodeError) as e:
|
|
229
|
+
return ToolResult.error(f"Could not parse notebook {shown}: {e}")
|
|
230
|
+
ctx.rt.file_state.record(path)
|
|
231
|
+
parts = []
|
|
232
|
+
for i, cell in enumerate(nb.get("cells", []), 1):
|
|
233
|
+
src = "".join(cell.get("source", []))
|
|
234
|
+
parts.append(f"## Cell {i} [{cell.get('cell_type', '?')}]\n{src}")
|
|
235
|
+
outs = []
|
|
236
|
+
for out in cell.get("outputs", []) or []:
|
|
237
|
+
if "text" in out:
|
|
238
|
+
outs.append("".join(out["text"]))
|
|
239
|
+
elif "data" in out and "text/plain" in out["data"]:
|
|
240
|
+
outs.append("".join(out["data"]["text/plain"]))
|
|
241
|
+
if outs:
|
|
242
|
+
joined = "\n".join(outs)
|
|
243
|
+
parts.append("Output:\n" + (joined[:2000] + "\n...[truncated]" if len(joined) > 2000 else joined))
|
|
244
|
+
return ToolResult(content="\n\n".join(parts) or "(empty notebook)",
|
|
245
|
+
summary=f"Read notebook ({len(nb.get('cells', []))} cells)")
|
|
246
|
+
|
|
247
|
+
def _pdf(self, path: Path, shown: str, ctx: ToolContext) -> ToolResult:
|
|
248
|
+
try:
|
|
249
|
+
from pypdf import PdfReader # type: ignore[import-not-found]
|
|
250
|
+
except ImportError:
|
|
251
|
+
return ToolResult.error(f"{shown} is a PDF. Install 'pypdf' (pip install pypdf) to extract its text.")
|
|
252
|
+
try:
|
|
253
|
+
reader = PdfReader(str(path))
|
|
254
|
+
texts = [f"--- page {i} ---\n{p.extract_text() or ''}" for i, p in enumerate(reader.pages[:50], 1)]
|
|
255
|
+
except Exception as e: # noqa: BLE001
|
|
256
|
+
return ToolResult.error(f"Could not read PDF {shown}: {e}")
|
|
257
|
+
text = "\n".join(texts)
|
|
258
|
+
budget = int(ctx.rt.settings.get("context.read_max_chars", 60000))
|
|
259
|
+
if len(text) > budget:
|
|
260
|
+
text = text[:budget] + "\n[truncated]"
|
|
261
|
+
return ToolResult(content=text, summary=f"Read PDF ({len(reader.pages)} pages)")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
class WriteTool(Tool):
|
|
265
|
+
name = "Write"
|
|
266
|
+
kind = "edit"
|
|
267
|
+
description = (
|
|
268
|
+
"Create a new file, or completely replace an existing file's contents. Prefer Edit for changing part of "
|
|
269
|
+
"an existing file. An existing file must be Read first. Parent directories are created as needed."
|
|
270
|
+
)
|
|
271
|
+
parameters = {
|
|
272
|
+
"type": "object",
|
|
273
|
+
"properties": {
|
|
274
|
+
"file_path": {"type": "string", "description": "Absolute path, or relative to the working directory"},
|
|
275
|
+
"content": {"type": "string", "description": "The full content to write"},
|
|
276
|
+
},
|
|
277
|
+
"required": ["file_path", "content"],
|
|
278
|
+
}
|
|
279
|
+
aliases = {"path": "file_path", "filepath": "file_path", "file": "file_path", "filename": "file_path",
|
|
280
|
+
"text": "content", "contents": "content", "data": "content", "file_text": "content"}
|
|
281
|
+
|
|
282
|
+
def permission_target(self, args: dict) -> str:
|
|
283
|
+
return str(args.get("file_path", ""))
|
|
284
|
+
|
|
285
|
+
def _plan(self, args: dict, ctx: ToolContext):
|
|
286
|
+
path = resolve_path(args["file_path"], ctx.cwd)
|
|
287
|
+
shown = display_path(path, ctx.cwd)
|
|
288
|
+
problem = _check_editable(path, ctx, must_exist=False, partial_ok=False)
|
|
289
|
+
if problem:
|
|
290
|
+
return problem
|
|
291
|
+
content = str(args.get("content", "")).replace("\r\n", "\n")
|
|
292
|
+
before, encoding, newline = None, "utf-8", "\n"
|
|
293
|
+
if path.exists():
|
|
294
|
+
try:
|
|
295
|
+
tf = read_text_file(path)
|
|
296
|
+
except OSError as e:
|
|
297
|
+
return ToolResult.error(f"Could not read existing {shown}: {e}")
|
|
298
|
+
before, encoding, newline = tf.text, tf.encoding, tf.newline
|
|
299
|
+
placeholder = find_omission_placeholder(content, before)
|
|
300
|
+
if placeholder:
|
|
301
|
+
return ToolResult.error(
|
|
302
|
+
f"content contains a placeholder ('{placeholder}') instead of real code. Writing it would "
|
|
303
|
+
"delete the code it stands for. Write the complete file, or use Edit for a partial change.",
|
|
304
|
+
summary="Rejected placeholder content")
|
|
305
|
+
return path, shown, content, before, encoding, newline
|
|
306
|
+
|
|
307
|
+
async def preview(self, args: dict, ctx: ToolContext):
|
|
308
|
+
plan = self._plan(args, ctx)
|
|
309
|
+
if isinstance(plan, ToolResult):
|
|
310
|
+
return plan
|
|
311
|
+
_path, shown, content, before, _enc, _nl = plan
|
|
312
|
+
if before is None:
|
|
313
|
+
return {"type": "new_file", "path": shown, "content": content}
|
|
314
|
+
diff, _a, _r = make_diff(before, content, shown)
|
|
315
|
+
return {"type": "diff", "path": shown, "diff": diff}
|
|
316
|
+
|
|
317
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
318
|
+
plan = self._plan(args, ctx)
|
|
319
|
+
if isinstance(plan, ToolResult):
|
|
320
|
+
return plan
|
|
321
|
+
path, shown, content, before, encoding, newline = plan
|
|
322
|
+
ctx.rt.checkpoints.snapshot(path)
|
|
323
|
+
try:
|
|
324
|
+
write_text_file(path, content, encoding, newline)
|
|
325
|
+
except (OSError, UnicodeEncodeError) as e:
|
|
326
|
+
return ToolResult.error(f"Could not write {shown}: {e}")
|
|
327
|
+
ctx.rt.file_state.record(path)
|
|
328
|
+
n_lines = content.count("\n") + (0 if content.endswith("\n") or not content else 1)
|
|
329
|
+
warning = _syntax_warning(path, before, content)
|
|
330
|
+
if before is not None:
|
|
331
|
+
diff, added, removed = make_diff(before, content, shown)
|
|
332
|
+
return ToolResult(content=f"Overwrote {shown} ({n_lines} lines).{warning}",
|
|
333
|
+
summary=f"Wrote {shown} (+{added} -{removed})",
|
|
334
|
+
display={"type": "diff", "path": shown, "diff": diff})
|
|
335
|
+
return ToolResult(content=f"Created {shown} ({n_lines} lines).{warning}",
|
|
336
|
+
summary=f"Created {shown} ({n_lines} lines)",
|
|
337
|
+
display={"type": "new_file", "path": shown, "content": content})
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
_EDIT_ALIASES = {"old": "old_string", "old_str": "old_string", "search": "old_string", "find": "old_string",
|
|
341
|
+
"new": "new_string", "new_str": "new_string", "replace": "new_string",
|
|
342
|
+
"replacement": "new_string", "replaceAll": "replace_all", "all": "replace_all"}
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
class EditTool(Tool):
|
|
346
|
+
name = "Edit"
|
|
347
|
+
kind = "edit"
|
|
348
|
+
description = (
|
|
349
|
+
"Replace text in an existing file: finds old_string and replaces it with new_string. Read the file first. "
|
|
350
|
+
"old_string must reproduce the current text exactly, including indentation, without the line-number "
|
|
351
|
+
"prefixes that Read shows. It must match exactly one place - include a few surrounding lines to make it "
|
|
352
|
+
"unique - or set replace_all=true to change every occurrence (e.g. a rename). For several separate "
|
|
353
|
+
"changes to one file, use MultiEdit."
|
|
354
|
+
)
|
|
355
|
+
parameters = {
|
|
356
|
+
"type": "object",
|
|
357
|
+
"properties": {
|
|
358
|
+
"file_path": {"type": "string", "description": "Absolute path, or relative to the working directory"},
|
|
359
|
+
"old_string": {"type": "string", "description": "Exact text to find"},
|
|
360
|
+
"new_string": {"type": "string", "description": "Replacement text"},
|
|
361
|
+
"replace_all": {"type": "boolean", "description": "Replace every occurrence (default false)"},
|
|
362
|
+
},
|
|
363
|
+
"required": ["file_path", "old_string", "new_string"],
|
|
364
|
+
}
|
|
365
|
+
aliases = {"path": "file_path", "filepath": "file_path", "file": "file_path", "filename": "file_path",
|
|
366
|
+
**_EDIT_ALIASES}
|
|
367
|
+
|
|
368
|
+
def permission_target(self, args: dict) -> str:
|
|
369
|
+
return str(args.get("file_path", ""))
|
|
370
|
+
|
|
371
|
+
@staticmethod
|
|
372
|
+
def _edits(args: dict) -> list[dict]:
|
|
373
|
+
return [{"old_string": args.get("old_string", ""), "new_string": args.get("new_string", ""),
|
|
374
|
+
"replace_all": bool(args.get("replace_all", False))}]
|
|
375
|
+
|
|
376
|
+
async def preview(self, args: dict, ctx: ToolContext):
|
|
377
|
+
return preview_edits(args["file_path"], self._edits(args), ctx)
|
|
378
|
+
|
|
379
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
380
|
+
return apply_edits(args["file_path"], self._edits(args), ctx)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
class MultiEditTool(Tool):
|
|
384
|
+
name = "MultiEdit"
|
|
385
|
+
kind = "edit"
|
|
386
|
+
description = (
|
|
387
|
+
"Apply several Edit-style replacements to one file atomically: edits run in order, each on the result of "
|
|
388
|
+
"the previous one, and nothing is written unless all succeed. Same matching rules as Edit."
|
|
389
|
+
)
|
|
390
|
+
parameters = {
|
|
391
|
+
"type": "object",
|
|
392
|
+
"properties": {
|
|
393
|
+
"file_path": {"type": "string", "description": "Absolute path, or relative to the working directory"},
|
|
394
|
+
"edits": {
|
|
395
|
+
"type": "array",
|
|
396
|
+
"description": "Ordered list of replacements",
|
|
397
|
+
"items": {
|
|
398
|
+
"type": "object",
|
|
399
|
+
"properties": {
|
|
400
|
+
"old_string": {"type": "string"},
|
|
401
|
+
"new_string": {"type": "string"},
|
|
402
|
+
"replace_all": {"type": "boolean"},
|
|
403
|
+
},
|
|
404
|
+
"required": ["old_string", "new_string"],
|
|
405
|
+
},
|
|
406
|
+
},
|
|
407
|
+
},
|
|
408
|
+
"required": ["file_path", "edits"],
|
|
409
|
+
}
|
|
410
|
+
aliases = {"path": "file_path", "filepath": "file_path", "file": "file_path", "filename": "file_path",
|
|
411
|
+
"edit": "edits", "changes": "edits", "replacements": "edits"}
|
|
412
|
+
|
|
413
|
+
def apply_aliases(self, args: dict) -> dict:
|
|
414
|
+
super().apply_aliases(args)
|
|
415
|
+
edits = args.get("edits")
|
|
416
|
+
if isinstance(edits, dict):
|
|
417
|
+
edits = [edits]
|
|
418
|
+
if isinstance(edits, list):
|
|
419
|
+
fixed = []
|
|
420
|
+
for e in edits:
|
|
421
|
+
if isinstance(e, dict):
|
|
422
|
+
e = dict(e)
|
|
423
|
+
for alias, canonical in _EDIT_ALIASES.items():
|
|
424
|
+
if alias in e and canonical not in e:
|
|
425
|
+
e[canonical] = e.pop(alias)
|
|
426
|
+
fixed.append(e)
|
|
427
|
+
args["edits"] = fixed
|
|
428
|
+
return args
|
|
429
|
+
|
|
430
|
+
def permission_target(self, args: dict) -> str:
|
|
431
|
+
return str(args.get("file_path", ""))
|
|
432
|
+
|
|
433
|
+
async def preview(self, args: dict, ctx: ToolContext):
|
|
434
|
+
if not args.get("edits"):
|
|
435
|
+
return ToolResult.error("edits is empty; provide at least one {old_string, new_string}.")
|
|
436
|
+
return preview_edits(args["file_path"], args["edits"], ctx)
|
|
437
|
+
|
|
438
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
439
|
+
if not args.get("edits"):
|
|
440
|
+
return ToolResult.error("edits is empty; provide at least one {old_string, new_string}.")
|
|
441
|
+
return apply_edits(args["file_path"], args["edits"], ctx)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _span_newline(raw: str, start: int, end: int, default: str) -> str:
|
|
445
|
+
"""Line ending to use for a replacement: the matched region's own style."""
|
|
446
|
+
seg = raw[start:end]
|
|
447
|
+
if "\n" in seg:
|
|
448
|
+
return "\r\n" if seg.count("\r\n") * 2 >= seg.count("\n") else "\n"
|
|
449
|
+
nxt = raw.find("\n", end)
|
|
450
|
+
if nxt == -1:
|
|
451
|
+
return default
|
|
452
|
+
return "\r\n" if nxt > 0 and raw[nxt - 1] == "\r" else "\n"
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _apply_outcome_to_raw(raw: str, outcome, default_newline: str) -> str:
|
|
456
|
+
"""Apply LF-view spans to the raw text, keeping each region's line endings."""
|
|
457
|
+
if "\r\n" not in raw:
|
|
458
|
+
return outcome.content
|
|
459
|
+
lfmap = LFMap(raw)
|
|
460
|
+
out = raw
|
|
461
|
+
for span in sorted(outcome.spans, key=lambda s: s.start, reverse=True):
|
|
462
|
+
a, b = lfmap.start(span.start), lfmap.end(span.end)
|
|
463
|
+
nl = _span_newline(raw, a, b, default_newline)
|
|
464
|
+
repl = span.replacement.replace("\n", nl) if nl == "\r\n" else span.replacement
|
|
465
|
+
out = out[:a] + repl + out[b:]
|
|
466
|
+
return out
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _compute_edits(raw_path: str, edits: list[dict], ctx: ToolContext):
|
|
470
|
+
"""Dry-run a list of edits. Returns a ToolResult on failure, else the planned change."""
|
|
471
|
+
path = resolve_path(raw_path, ctx.cwd)
|
|
472
|
+
shown = display_path(path, ctx.cwd)
|
|
473
|
+
problem = _check_editable(path, ctx, must_exist=True, partial_ok=True)
|
|
474
|
+
if problem:
|
|
475
|
+
return problem
|
|
476
|
+
try:
|
|
477
|
+
tf = read_text_file(path)
|
|
478
|
+
except OSError as e:
|
|
479
|
+
return ToolResult.error(f"Could not read {shown}: {e}")
|
|
480
|
+
raw, content = tf.raw, tf.text
|
|
481
|
+
notes: list[str] = []
|
|
482
|
+
first_line, last_new = 1, ""
|
|
483
|
+
for i, edit in enumerate(edits, 1):
|
|
484
|
+
if not isinstance(edit, dict):
|
|
485
|
+
return ToolResult.error(f"Edit {i} is not an object with old_string/new_string.")
|
|
486
|
+
old, new = str(edit.get("old_string", "")), str(edit.get("new_string", ""))
|
|
487
|
+
try:
|
|
488
|
+
outcome = apply_edit(content, old, new, bool(edit.get("replace_all", False)))
|
|
489
|
+
except EditError as e:
|
|
490
|
+
prefix = f"Edit {i} of {len(edits)} failed, so no changes were written: " if len(edits) > 1 else ""
|
|
491
|
+
return ToolResult.error(prefix + str(e), summary=one_line(f"Edit failed: {e}", 100))
|
|
492
|
+
raw = _apply_outcome_to_raw(raw, outcome, tf.newline)
|
|
493
|
+
content = outcome.content
|
|
494
|
+
if i == 1 or outcome.first_line < first_line:
|
|
495
|
+
first_line = outcome.first_line
|
|
496
|
+
last_new = outcome.new_text
|
|
497
|
+
if outcome.strategy != "exact":
|
|
498
|
+
notes.append(f"edit {i} matched after {outcome.strategy} normalization" if len(edits) > 1
|
|
499
|
+
else f"matched after {outcome.strategy} normalization")
|
|
500
|
+
if outcome.count > 1:
|
|
501
|
+
notes.append(f"{outcome.count} occurrences replaced" + (f" in edit {i}" if len(edits) > 1 else ""))
|
|
502
|
+
return path, shown, tf, raw, content, notes, first_line, last_new
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def preview_edits(raw_path: str, edits: list[dict], ctx: ToolContext):
|
|
506
|
+
plan = _compute_edits(raw_path, edits, ctx)
|
|
507
|
+
if isinstance(plan, ToolResult):
|
|
508
|
+
return plan
|
|
509
|
+
_path, shown, tf, _raw, content, _notes, _fl, _ln = plan
|
|
510
|
+
diff, _a, _r = make_diff(tf.text, content, shown)
|
|
511
|
+
return {"type": "diff", "path": shown, "diff": diff}
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def apply_edits(raw_path: str, edits: list[dict], ctx: ToolContext) -> ToolResult:
|
|
515
|
+
plan = _compute_edits(raw_path, edits, ctx)
|
|
516
|
+
if isinstance(plan, ToolResult):
|
|
517
|
+
return plan
|
|
518
|
+
path, shown, tf, raw, content, notes, first_line, last_new = plan
|
|
519
|
+
ctx.rt.checkpoints.snapshot(path)
|
|
520
|
+
try:
|
|
521
|
+
write_text_file(path, raw, tf.encoding, None)
|
|
522
|
+
except (OSError, UnicodeEncodeError) as e:
|
|
523
|
+
return ToolResult.error(f"Could not write {shown}: {e}")
|
|
524
|
+
ctx.rt.file_state.record(path)
|
|
525
|
+
diff, added, removed = make_diff(tf.text, content, shown)
|
|
526
|
+
warning = _syntax_warning(path, tf.text, content)
|
|
527
|
+
note = f" ({'; '.join(notes)})" if notes else ""
|
|
528
|
+
if len(edits) == 1:
|
|
529
|
+
snippet = _snippet(content, first_line, last_new.count("\n") + 1)
|
|
530
|
+
body = f"Edited {shown}{note}. Updated region:\n{snippet}{warning}"
|
|
531
|
+
else:
|
|
532
|
+
body = f"Applied {len(edits)} edits to {shown}{note} (+{added} -{removed} lines).{warning}"
|
|
533
|
+
return ToolResult(content=body, summary=f"Edited {shown} (+{added} -{removed})",
|
|
534
|
+
display={"type": "diff", "path": shown, "diff": diff})
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Tools that talk to the user: AskUser and ExitPlanMode."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from rigcode.tools.base import Tool, ToolContext, ToolResult
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AskUserTool(Tool):
|
|
8
|
+
name = "AskUser"
|
|
9
|
+
kind = "interact"
|
|
10
|
+
read_only = True
|
|
11
|
+
description = (
|
|
12
|
+
"Ask the user a question when you are blocked on a decision only they can make (ambiguous, high-impact "
|
|
13
|
+
"requirements; choosing between valid approaches). Offer 2-4 concrete options when possible. Don't ask "
|
|
14
|
+
"about things you can find out yourself, and don't ask for permission to proceed with the task."
|
|
15
|
+
)
|
|
16
|
+
parameters = {
|
|
17
|
+
"type": "object",
|
|
18
|
+
"properties": {
|
|
19
|
+
"question": {"type": "string", "description": "The question"},
|
|
20
|
+
"options": {"type": "array", "items": {"type": "string"}, "description": "Suggested answers"},
|
|
21
|
+
},
|
|
22
|
+
"required": ["question"],
|
|
23
|
+
}
|
|
24
|
+
aliases = {"choices": "options", "answers": "options", "text": "question", "prompt": "question"}
|
|
25
|
+
|
|
26
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
27
|
+
question = str(args.get("question", "")).strip()
|
|
28
|
+
options = [str(o) for o in (args.get("options") or []) if str(o).strip()][:6]
|
|
29
|
+
answer = await ctx.rt.ui.ask_user(question, options)
|
|
30
|
+
if answer is None:
|
|
31
|
+
return ToolResult(content="The user is not available to answer. Proceed with your best judgment and "
|
|
32
|
+
"state the assumption you made.", summary="No answer (non-interactive)")
|
|
33
|
+
return ToolResult(content=f"User answered: {answer}", summary=f"Answered: {answer[:60]}")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ExitPlanModeTool(Tool):
|
|
37
|
+
name = "ExitPlanMode"
|
|
38
|
+
kind = "interact"
|
|
39
|
+
read_only = True
|
|
40
|
+
description = (
|
|
41
|
+
"Plan mode only: present your finished implementation plan for approval. If approved you will be "
|
|
42
|
+
"allowed to make changes; if not, you get feedback to revise the plan."
|
|
43
|
+
)
|
|
44
|
+
parameters = {
|
|
45
|
+
"type": "object",
|
|
46
|
+
"properties": {"plan": {"type": "string", "description": "The plan, in concise Markdown"}},
|
|
47
|
+
"required": ["plan"],
|
|
48
|
+
}
|
|
49
|
+
aliases = {"content": "plan", "text": "plan"}
|
|
50
|
+
|
|
51
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
52
|
+
perms = ctx.rt.permissions
|
|
53
|
+
if perms.mode != "plan":
|
|
54
|
+
return ToolResult(content="Plan mode is not active - no approval needed. Continue with the task.",
|
|
55
|
+
summary="Not in plan mode")
|
|
56
|
+
plan = str(args.get("plan", "")).strip()
|
|
57
|
+
decision = await ctx.rt.ui.review_plan(plan)
|
|
58
|
+
if decision is None:
|
|
59
|
+
return ToolResult(content="Plan recorded, but nobody is available to approve it. Stay in plan mode "
|
|
60
|
+
"and stop here.", summary="Plan (no reviewer)", stop_turn=True)
|
|
61
|
+
approved, mode, feedback = decision
|
|
62
|
+
if approved:
|
|
63
|
+
perms.set_mode(mode or perms.previous_mode or "default")
|
|
64
|
+
return ToolResult(content=f"The user approved the plan. Plan mode is off (permission mode: {perms.mode}). "
|
|
65
|
+
"Implement the plan now, tracking progress with TodoWrite.",
|
|
66
|
+
summary="Plan approved", display={"type": "markdown", "text": plan})
|
|
67
|
+
return ToolResult(content="The user did not approve the plan. Still in plan mode. Feedback: "
|
|
68
|
+
+ (feedback or "(none)") + "\nRevise the plan accordingly.",
|
|
69
|
+
summary="Plan rejected", stop_turn=not feedback)
|