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/shell.py
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
"""Shell tools: Bash (foreground/background), BashOutput, KillShell."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import base64
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shlex
|
|
9
|
+
import shutil
|
|
10
|
+
import signal
|
|
11
|
+
import subprocess
|
|
12
|
+
import time
|
|
13
|
+
import uuid
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from rigcode.tools.base import Tool, ToolContext, ToolResult
|
|
18
|
+
from rigcode.tools.bashsafety import is_read_only_command
|
|
19
|
+
from rigcode.utils.paths import IS_WINDOWS, rigcode_home
|
|
20
|
+
from rigcode.utils.text import decode_output, strip_ansi, truncate_middle
|
|
21
|
+
|
|
22
|
+
MARKER = "__RIGCODE_CWD__"
|
|
23
|
+
DEFAULT_TIMEOUT = 120
|
|
24
|
+
MAX_TIMEOUT = 600
|
|
25
|
+
MAX_CAPTURE = 8 * 1024 * 1024
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class ShellSpec:
|
|
30
|
+
kind: str # bash | powershell | cmd | sh
|
|
31
|
+
exe: str
|
|
32
|
+
name: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _git_bash_candidates() -> list[str]:
|
|
36
|
+
cands = []
|
|
37
|
+
git = shutil.which("git")
|
|
38
|
+
if git:
|
|
39
|
+
root = Path(git).resolve().parent.parent # .../Git/cmd/git.exe -> .../Git
|
|
40
|
+
cands += [str(root / "bin" / "bash.exe"), str(root / "usr" / "bin" / "bash.exe")]
|
|
41
|
+
for base in (os.environ.get("ProgramFiles", r"C:\Program Files"), os.environ.get("ProgramFiles(x86)", ""),
|
|
42
|
+
os.path.join(os.environ.get("LOCALAPPDATA", ""), "Programs")):
|
|
43
|
+
if base:
|
|
44
|
+
cands.append(os.path.join(base, "Git", "bin", "bash.exe"))
|
|
45
|
+
return cands
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def resolve_shell(setting: str = "auto") -> ShellSpec:
|
|
49
|
+
setting = (setting or "auto").strip()
|
|
50
|
+
low = setting.lower()
|
|
51
|
+
if low in ("auto", "bash", "git-bash", "gitbash"):
|
|
52
|
+
if IS_WINDOWS:
|
|
53
|
+
for cand in _git_bash_candidates():
|
|
54
|
+
if cand and os.path.exists(cand):
|
|
55
|
+
return ShellSpec("bash", cand, "Git Bash")
|
|
56
|
+
if low != "auto":
|
|
57
|
+
raise RuntimeError("Git Bash not found; install Git for Windows or set \"shell\": \"powershell\"")
|
|
58
|
+
else:
|
|
59
|
+
exe = shutil.which("bash") or shutil.which("sh") or "/bin/sh"
|
|
60
|
+
return ShellSpec("bash" if exe.endswith("bash") else "sh", exe, os.path.basename(exe))
|
|
61
|
+
if low in ("auto", "powershell", "pwsh"):
|
|
62
|
+
exe = shutil.which("pwsh") or shutil.which("powershell") or "powershell.exe"
|
|
63
|
+
return ShellSpec("powershell", exe, "PowerShell")
|
|
64
|
+
if low == "cmd":
|
|
65
|
+
return ShellSpec("cmd", os.environ.get("COMSPEC", "cmd.exe"), "cmd.exe")
|
|
66
|
+
if low == "sh":
|
|
67
|
+
return ShellSpec("sh", shutil.which("sh") or "/bin/sh", "sh")
|
|
68
|
+
name = os.path.basename(setting).lower()
|
|
69
|
+
kind = "powershell" if "pwsh" in name or "powershell" in name else "cmd" if name.startswith("cmd") else "bash"
|
|
70
|
+
return ShellSpec(kind, setting, os.path.basename(setting))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _child_env() -> dict:
|
|
74
|
+
env = dict(os.environ)
|
|
75
|
+
env.update({
|
|
76
|
+
"PAGER": "cat", "GIT_PAGER": "cat", "GIT_TERMINAL_PROMPT": "0", "GIT_EDITOR": "true",
|
|
77
|
+
"PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1", "NO_COLOR": "1", "CLICOLOR": "0",
|
|
78
|
+
"RIGCODE": "1",
|
|
79
|
+
})
|
|
80
|
+
return env
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def build_invocation(spec: ShellSpec, command: str, cwd: Path, track_cwd: bool = True) -> list[str]:
|
|
84
|
+
if spec.kind in ("bash", "sh"):
|
|
85
|
+
cwd_s = str(cwd).replace("\\", "/")
|
|
86
|
+
pwd_cmd = '"$(pwd -W 2>/dev/null || pwd)"' if spec.kind == "bash" else '"$(pwd)"'
|
|
87
|
+
script = f"cd {shlex.quote(cwd_s)} || exit 1\n{command}\n"
|
|
88
|
+
if track_cwd:
|
|
89
|
+
script += f"__kc_ec=$?\nprintf '\\n{MARKER}%s\\n' {pwd_cmd}\nexit $__kc_ec\n"
|
|
90
|
+
return [spec.exe, "-c", script]
|
|
91
|
+
if spec.kind == "powershell":
|
|
92
|
+
lit = str(cwd).replace("'", "''")
|
|
93
|
+
script = (
|
|
94
|
+
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $OutputEncoding = [System.Text.Encoding]::UTF8\n"
|
|
95
|
+
"$ProgressPreference = 'SilentlyContinue'\n"
|
|
96
|
+
f"Set-Location -LiteralPath '{lit}'\n$global:LASTEXITCODE = 0\n{command}\n"
|
|
97
|
+
"$__kc_ok = $?\n$__kc_ec = if ($LASTEXITCODE) { $LASTEXITCODE } elseif ($__kc_ok) { 0 } else { 1 }\n"
|
|
98
|
+
)
|
|
99
|
+
if track_cwd:
|
|
100
|
+
script += f"Write-Output \"`n{MARKER}$((Get-Location).Path)\"\n"
|
|
101
|
+
script += "exit $__kc_ec\n"
|
|
102
|
+
enc = base64.b64encode(script.encode("utf-16-le")).decode("ascii")
|
|
103
|
+
return [spec.exe, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", enc]
|
|
104
|
+
# cmd.exe
|
|
105
|
+
tail = f" & echo. & echo {MARKER}%CD%" if track_cwd else ""
|
|
106
|
+
return [spec.exe, "/d", "/s", "/c", f'cd /d "{cwd}" && ({command}){tail}']
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _kill_tree(proc: asyncio.subprocess.Process) -> None:
|
|
110
|
+
if proc.returncode is not None:
|
|
111
|
+
return
|
|
112
|
+
try:
|
|
113
|
+
if IS_WINDOWS:
|
|
114
|
+
subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)], capture_output=True, timeout=10)
|
|
115
|
+
else:
|
|
116
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
117
|
+
except (OSError, subprocess.SubprocessError):
|
|
118
|
+
try:
|
|
119
|
+
proc.kill()
|
|
120
|
+
except OSError:
|
|
121
|
+
pass
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _clean(raw: str) -> str:
|
|
125
|
+
text = strip_ansi(raw).replace("\r\n", "\n")
|
|
126
|
+
if "\r" in text: # progress bars: keep the final state of each line
|
|
127
|
+
text = "\n".join(line.rstrip("\r").rsplit("\r", 1)[-1] for line in text.split("\n"))
|
|
128
|
+
return text
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _extract_cwd(text: str) -> tuple[str, str | None]:
|
|
132
|
+
idx = text.rfind(MARKER)
|
|
133
|
+
if idx == -1:
|
|
134
|
+
return text, None
|
|
135
|
+
line_end = text.find("\n", idx)
|
|
136
|
+
new_cwd = text[idx + len(MARKER): line_end if line_end != -1 else None].strip()
|
|
137
|
+
before = text[:idx]
|
|
138
|
+
if before.endswith("\n"):
|
|
139
|
+
before = before[:-1]
|
|
140
|
+
after = text[line_end + 1:] if line_end != -1 else ""
|
|
141
|
+
return (before + after).rstrip("\n"), (new_cwd or None)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _normalize_cwd(raw: str) -> Path | None:
|
|
145
|
+
if IS_WINDOWS:
|
|
146
|
+
m = re.match(r"^/([a-zA-Z])(/.*)?$", raw)
|
|
147
|
+
if m:
|
|
148
|
+
raw = f"{m.group(1).upper()}:{m.group(2) or '/'}"
|
|
149
|
+
p = Path(raw)
|
|
150
|
+
return p if p.is_dir() else None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def save_full_output(text: str) -> Path | None:
|
|
154
|
+
try:
|
|
155
|
+
d = rigcode_home() / "tmp"
|
|
156
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
157
|
+
p = d / f"output-{time.strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:6]}.txt"
|
|
158
|
+
p.write_text(text, encoding="utf-8")
|
|
159
|
+
return p
|
|
160
|
+
except OSError:
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
async def _spawn(argv: list[str], cwd: Path) -> asyncio.subprocess.Process:
|
|
165
|
+
kwargs: dict = {}
|
|
166
|
+
if not IS_WINDOWS:
|
|
167
|
+
kwargs["start_new_session"] = True
|
|
168
|
+
else:
|
|
169
|
+
kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
170
|
+
return await asyncio.create_subprocess_exec(
|
|
171
|
+
*argv, cwd=str(cwd), stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
|
|
172
|
+
stderr=asyncio.subprocess.STDOUT, env=_child_env(), **kwargs)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class BashTool(Tool):
|
|
176
|
+
name = "Bash"
|
|
177
|
+
kind = "exec"
|
|
178
|
+
parameters = {
|
|
179
|
+
"type": "object",
|
|
180
|
+
"properties": {
|
|
181
|
+
"command": {"type": "string", "description": "The command to run"},
|
|
182
|
+
"timeout": {"type": "integer", "description": f"Seconds before the command is killed (default {DEFAULT_TIMEOUT}, max {MAX_TIMEOUT})"},
|
|
183
|
+
"run_in_background": {"type": "boolean", "description": "Start without waiting (servers, watchers); read output with BashOutput"},
|
|
184
|
+
},
|
|
185
|
+
"required": ["command"],
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
def __init__(self, spec: ShellSpec):
|
|
189
|
+
self.spec = spec
|
|
190
|
+
shell_note = {
|
|
191
|
+
"bash": f"{spec.name} (bash syntax{', running on Windows: use forward slashes, /c/... or C:/... paths' if IS_WINDOWS else ''})",
|
|
192
|
+
"sh": "POSIX sh",
|
|
193
|
+
"powershell": "PowerShell (use PowerShell syntax, not bash)",
|
|
194
|
+
"cmd": "cmd.exe (Windows batch syntax)",
|
|
195
|
+
}[spec.kind]
|
|
196
|
+
self.description = (
|
|
197
|
+
f"Run a shell command in {shell_note} and return combined stdout/stderr and the exit code. The working "
|
|
198
|
+
"directory persists between calls (cd works); environment variables do not. Use Read/Grep/Glob/Edit "
|
|
199
|
+
"instead of cat/grep/find/sed for files. Never run interactive programs (editors, pagers, prompts); "
|
|
200
|
+
"pass non-interactive flags. For servers or watchers use run_in_background=true."
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
aliases = {"cmd": "command", "script": "command", "background": "run_in_background"}
|
|
204
|
+
|
|
205
|
+
def permission_target(self, args: dict) -> str:
|
|
206
|
+
return str(args.get("command", ""))
|
|
207
|
+
|
|
208
|
+
def is_read_only(self, args: dict) -> bool:
|
|
209
|
+
return is_read_only_command(str(args.get("command", "")))
|
|
210
|
+
|
|
211
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
212
|
+
command = str(args.get("command", "")).strip()
|
|
213
|
+
if not command:
|
|
214
|
+
return ToolResult.error("command is empty")
|
|
215
|
+
if args.get("run_in_background"):
|
|
216
|
+
if not ctx.rt.settings.get("tools.background_shells", True):
|
|
217
|
+
return ToolResult.error("Background commands are disabled in settings (tools.background_shells).")
|
|
218
|
+
return await ctx.rt.shells.start(self.spec, command, ctx.cwd)
|
|
219
|
+
timeout = int(args.get("timeout") or DEFAULT_TIMEOUT)
|
|
220
|
+
if timeout > MAX_TIMEOUT * 10: # looks like milliseconds
|
|
221
|
+
timeout //= 1000
|
|
222
|
+
timeout = max(1, min(timeout, MAX_TIMEOUT))
|
|
223
|
+
argv = build_invocation(self.spec, command, ctx.cwd)
|
|
224
|
+
try:
|
|
225
|
+
proc = await _spawn(argv, ctx.cwd)
|
|
226
|
+
except OSError as e:
|
|
227
|
+
return ToolResult.error(f"Failed to start {self.spec.name}: {e}")
|
|
228
|
+
chunks: list[bytes] = []
|
|
229
|
+
size = 0
|
|
230
|
+
started = time.monotonic()
|
|
231
|
+
on_output = getattr(ctx.agent, "on_tool_output", None)
|
|
232
|
+
|
|
233
|
+
async def pump() -> None:
|
|
234
|
+
nonlocal size
|
|
235
|
+
assert proc.stdout is not None
|
|
236
|
+
while True:
|
|
237
|
+
data = await proc.stdout.read(65536)
|
|
238
|
+
if not data:
|
|
239
|
+
break
|
|
240
|
+
if size < MAX_CAPTURE:
|
|
241
|
+
chunks.append(data)
|
|
242
|
+
size += len(data)
|
|
243
|
+
if on_output:
|
|
244
|
+
try:
|
|
245
|
+
on_output(ctx.call_id, decode_output(data))
|
|
246
|
+
except Exception: # noqa: BLE001 - UI must not break tools
|
|
247
|
+
pass
|
|
248
|
+
await proc.wait()
|
|
249
|
+
|
|
250
|
+
timed_out = False
|
|
251
|
+
try:
|
|
252
|
+
await asyncio.wait_for(pump(), timeout=timeout)
|
|
253
|
+
except asyncio.TimeoutError:
|
|
254
|
+
timed_out = True
|
|
255
|
+
_kill_tree(proc)
|
|
256
|
+
try:
|
|
257
|
+
await asyncio.wait_for(proc.wait(), 5)
|
|
258
|
+
except asyncio.TimeoutError:
|
|
259
|
+
pass
|
|
260
|
+
except asyncio.CancelledError:
|
|
261
|
+
_kill_tree(proc)
|
|
262
|
+
raise
|
|
263
|
+
elapsed = time.monotonic() - started
|
|
264
|
+
text, new_cwd = _extract_cwd(_clean(decode_output(b"".join(chunks))))
|
|
265
|
+
if new_cwd:
|
|
266
|
+
p = _normalize_cwd(new_cwd)
|
|
267
|
+
if p is not None:
|
|
268
|
+
ctx.rt.set_cwd(p)
|
|
269
|
+
code = proc.returncode
|
|
270
|
+
limit = int(ctx.rt.settings.get("context.max_tool_output_chars", 12000))
|
|
271
|
+
shown, truncated = truncate_middle(text, limit)
|
|
272
|
+
parts = []
|
|
273
|
+
if truncated:
|
|
274
|
+
saved = save_full_output(text)
|
|
275
|
+
parts.append(f"[Output was {len(text):,} chars; showing the start and end."
|
|
276
|
+
+ (f" Full output saved to {saved} - use Read/Grep on it if needed.]" if saved else "]"))
|
|
277
|
+
if shown.strip():
|
|
278
|
+
parts.append(shown)
|
|
279
|
+
elif not timed_out:
|
|
280
|
+
parts.append("(command completed with no output)")
|
|
281
|
+
if timed_out:
|
|
282
|
+
parts.append(f"[Command timed out after {timeout}s and was killed. Use a longer timeout or "
|
|
283
|
+
"run_in_background=true for long-running processes.]")
|
|
284
|
+
elif code:
|
|
285
|
+
parts.append(f"[Exit code: {code}]")
|
|
286
|
+
n_lines = text.count("\n") + 1 if text else 0
|
|
287
|
+
summary = (f"Timed out after {timeout}s" if timed_out else
|
|
288
|
+
f"Exit {code} · {n_lines} lines · {elapsed:.1f}s" if code else f"{n_lines} lines · {elapsed:.1f}s")
|
|
289
|
+
return ToolResult(content="\n".join(parts), is_error=bool(code) or timed_out, summary=summary,
|
|
290
|
+
display={"type": "output", "text": text[-4000:]})
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
@dataclass
|
|
294
|
+
class BackgroundShell:
|
|
295
|
+
id: str
|
|
296
|
+
command: str
|
|
297
|
+
proc: asyncio.subprocess.Process
|
|
298
|
+
started: float
|
|
299
|
+
buffer: list[str] = field(default_factory=list)
|
|
300
|
+
read_pos: int = 0
|
|
301
|
+
task: asyncio.Task | None = None
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class BackgroundShells:
|
|
305
|
+
def __init__(self) -> None:
|
|
306
|
+
self.shells: dict[str, BackgroundShell] = {}
|
|
307
|
+
self._n = 0
|
|
308
|
+
|
|
309
|
+
async def start(self, spec: ShellSpec, command: str, cwd: Path) -> ToolResult:
|
|
310
|
+
argv = build_invocation(spec, command, cwd, track_cwd=False)
|
|
311
|
+
try:
|
|
312
|
+
proc = await _spawn(argv, cwd)
|
|
313
|
+
except OSError as e:
|
|
314
|
+
return ToolResult.error(f"Failed to start background command: {e}")
|
|
315
|
+
self._n += 1
|
|
316
|
+
sid = f"bash_{self._n}"
|
|
317
|
+
shell = BackgroundShell(sid, command, proc, time.monotonic())
|
|
318
|
+
|
|
319
|
+
async def reader() -> None:
|
|
320
|
+
assert proc.stdout is not None
|
|
321
|
+
total = 0
|
|
322
|
+
while True:
|
|
323
|
+
data = await proc.stdout.read(65536)
|
|
324
|
+
if not data:
|
|
325
|
+
break
|
|
326
|
+
text = _clean(decode_output(data))
|
|
327
|
+
total += len(text)
|
|
328
|
+
shell.buffer.append(text)
|
|
329
|
+
if total > MAX_CAPTURE: # keep memory bounded
|
|
330
|
+
joined = "".join(shell.buffer)[-MAX_CAPTURE // 2:]
|
|
331
|
+
shell.read_pos = max(0, shell.read_pos - (len("".join(shell.buffer)) - len(joined)))
|
|
332
|
+
shell.buffer = [joined]
|
|
333
|
+
total = len(joined)
|
|
334
|
+
await proc.wait()
|
|
335
|
+
|
|
336
|
+
shell.task = asyncio.create_task(reader())
|
|
337
|
+
self.shells[sid] = shell
|
|
338
|
+
return ToolResult(content=f"Started in background as {sid} (pid {proc.pid}). Check output with "
|
|
339
|
+
f"BashOutput(bash_id='{sid}'); stop it with KillShell.",
|
|
340
|
+
summary=f"Background {sid}")
|
|
341
|
+
|
|
342
|
+
def read(self, sid: str, pattern: str | None = None) -> ToolResult:
|
|
343
|
+
shell = self.shells.get(sid)
|
|
344
|
+
if not shell:
|
|
345
|
+
known = ", ".join(self.shells) or "none"
|
|
346
|
+
return ToolResult.error(f"No background shell '{sid}'. Known: {known}")
|
|
347
|
+
text = "".join(shell.buffer)
|
|
348
|
+
new = text[shell.read_pos:]
|
|
349
|
+
shell.read_pos = len(text)
|
|
350
|
+
if pattern:
|
|
351
|
+
try:
|
|
352
|
+
rx = re.compile(pattern)
|
|
353
|
+
new = "\n".join(l for l in new.split("\n") if rx.search(l))
|
|
354
|
+
except re.error as e:
|
|
355
|
+
return ToolResult.error(f"Invalid filter regex: {e}")
|
|
356
|
+
code = shell.proc.returncode
|
|
357
|
+
status = "running" if code is None else f"exited with code {code}"
|
|
358
|
+
shown, _ = truncate_middle(new, 12000)
|
|
359
|
+
return ToolResult(content=f"[{sid}: {status}]\n" + (shown if shown.strip() else "(no new output)"),
|
|
360
|
+
summary=f"{sid} {status}")
|
|
361
|
+
|
|
362
|
+
async def kill(self, sid: str) -> ToolResult:
|
|
363
|
+
shell = self.shells.get(sid)
|
|
364
|
+
if not shell:
|
|
365
|
+
return ToolResult.error(f"No background shell '{sid}'.")
|
|
366
|
+
_kill_tree(shell.proc)
|
|
367
|
+
try:
|
|
368
|
+
await asyncio.wait_for(shell.proc.wait(), 5)
|
|
369
|
+
except asyncio.TimeoutError:
|
|
370
|
+
pass
|
|
371
|
+
return ToolResult(content=f"Killed {sid}.", summary=f"Killed {sid}")
|
|
372
|
+
|
|
373
|
+
async def kill_all(self) -> None:
|
|
374
|
+
for sid in list(self.shells):
|
|
375
|
+
if self.shells[sid].proc.returncode is None:
|
|
376
|
+
_kill_tree(self.shells[sid].proc)
|
|
377
|
+
|
|
378
|
+
def describe(self) -> list[str]:
|
|
379
|
+
out = []
|
|
380
|
+
for s in self.shells.values():
|
|
381
|
+
status = "running" if s.proc.returncode is None else f"exit {s.proc.returncode}"
|
|
382
|
+
out.append(f"{s.id} [{status}] {s.command[:60]}")
|
|
383
|
+
return out
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class BashOutputTool(Tool):
|
|
387
|
+
name = "BashOutput"
|
|
388
|
+
kind = "read"
|
|
389
|
+
read_only = True
|
|
390
|
+
description = "Get new output from a background command started with Bash(run_in_background=true)."
|
|
391
|
+
parameters = {
|
|
392
|
+
"type": "object",
|
|
393
|
+
"properties": {
|
|
394
|
+
"bash_id": {"type": "string", "description": "Id returned when the command was started"},
|
|
395
|
+
"filter": {"type": "string", "description": "Optional regex; only matching lines are returned"},
|
|
396
|
+
},
|
|
397
|
+
"required": ["bash_id"],
|
|
398
|
+
}
|
|
399
|
+
aliases = {"id": "bash_id", "shell_id": "bash_id"}
|
|
400
|
+
|
|
401
|
+
def permission_target(self, args: dict) -> str:
|
|
402
|
+
return str(args.get("bash_id", ""))
|
|
403
|
+
|
|
404
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
405
|
+
return ctx.rt.shells.read(str(args["bash_id"]), args.get("filter"))
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
class KillShellTool(Tool):
|
|
409
|
+
name = "KillShell"
|
|
410
|
+
kind = "exec"
|
|
411
|
+
read_only = True # only stops processes the agent started itself
|
|
412
|
+
description = "Stop a background command started with Bash(run_in_background=true)."
|
|
413
|
+
parameters = {
|
|
414
|
+
"type": "object",
|
|
415
|
+
"properties": {"bash_id": {"type": "string", "description": "Id of the background command"}},
|
|
416
|
+
"required": ["bash_id"],
|
|
417
|
+
}
|
|
418
|
+
aliases = {"id": "bash_id", "shell_id": "bash_id"}
|
|
419
|
+
|
|
420
|
+
def permission_target(self, args: dict) -> str:
|
|
421
|
+
return str(args.get("bash_id", ""))
|
|
422
|
+
|
|
423
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
424
|
+
return await ctx.rt.shells.kill(str(args["bash_id"]))
|
rigcode/tools/skill.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Skill: load a skill's full instructions on demand (progressive disclosure)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from rigcode.tools.base import Tool, ToolContext, ToolResult
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class SkillTool(Tool):
|
|
8
|
+
name = "Skill"
|
|
9
|
+
kind = "read"
|
|
10
|
+
read_only = True
|
|
11
|
+
description = ("Load the full instructions of a skill listed in your context, by name. Use it when the task "
|
|
12
|
+
"matches a skill's description, then follow the loaded instructions.")
|
|
13
|
+
parameters = {
|
|
14
|
+
"type": "object",
|
|
15
|
+
"properties": {
|
|
16
|
+
"name": {"type": "string", "description": "Skill name"},
|
|
17
|
+
"args": {"type": "string", "description": "Optional arguments for the skill"},
|
|
18
|
+
},
|
|
19
|
+
"required": ["name"],
|
|
20
|
+
}
|
|
21
|
+
aliases = {"skill": "name", "skill_name": "name", "arguments": "args"}
|
|
22
|
+
|
|
23
|
+
def permission_target(self, args: dict) -> str:
|
|
24
|
+
return str(args.get("name", ""))
|
|
25
|
+
|
|
26
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
27
|
+
name = str(args.get("name") or args.get("skill") or "").strip()
|
|
28
|
+
skill = ctx.rt.skills.get(name) or next(
|
|
29
|
+
(s for k, s in ctx.rt.skills.items() if k.lower() == name.lower()), None)
|
|
30
|
+
if skill is None:
|
|
31
|
+
known = ", ".join(sorted(ctx.rt.skills)) or "none"
|
|
32
|
+
return ToolResult.error(f"Unknown skill '{name}'. Available: {known}")
|
|
33
|
+
body = skill.load_body()
|
|
34
|
+
extra = f"\nArguments: {args['args']}" if args.get("args") else ""
|
|
35
|
+
return ToolResult(
|
|
36
|
+
content=f"Skill '{skill.name}' (files in {skill.directory}):{extra}\n\n{body}",
|
|
37
|
+
summary=f"Loaded skill {skill.name}")
|
rigcode/tools/task.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Task: delegate a self-contained job to a subagent with its own context."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from rigcode.tools.base import Tool, ToolContext, ToolResult
|
|
5
|
+
from rigcode.utils.text import truncate_middle
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TaskTool(Tool):
|
|
9
|
+
name = "Task"
|
|
10
|
+
kind = "agent"
|
|
11
|
+
read_only = True # the subagent's own tool calls go through permissions individually
|
|
12
|
+
aliases = {"agent": "subagent_type", "agent_type": "subagent_type", "type": "subagent_type",
|
|
13
|
+
"task": "prompt", "instructions": "prompt", "brief": "prompt", "title": "description"}
|
|
14
|
+
|
|
15
|
+
def __init__(self, agents: dict):
|
|
16
|
+
self.agents = agents
|
|
17
|
+
lines = [f"- {name}: {a.description}" for name, a in agents.items()]
|
|
18
|
+
self.description = (
|
|
19
|
+
"Delegate a self-contained task to a subagent that works in its own context and returns one final "
|
|
20
|
+
"report. Use it to keep your context small: broad exploration across many files, independent "
|
|
21
|
+
"research, reviewing or verifying a change. Don't delegate a read or search you can do in one or two "
|
|
22
|
+
"calls. The subagent may not see this conversation, so give a complete brief (goal, relevant paths, "
|
|
23
|
+
"constraints, what to return). Only its final report comes back to you.\nAgents:\n"
|
|
24
|
+
+ "\n".join(lines)
|
|
25
|
+
)
|
|
26
|
+
self.parameters = {
|
|
27
|
+
"type": "object",
|
|
28
|
+
"properties": {
|
|
29
|
+
"description": {"type": "string", "description": "3-6 word label for the task"},
|
|
30
|
+
"prompt": {"type": "string", "description": "Complete, self-contained brief for the subagent"},
|
|
31
|
+
"subagent_type": {"type": "string", "enum": list(agents) or ["general"]},
|
|
32
|
+
},
|
|
33
|
+
"required": ["description", "prompt", "subagent_type"],
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
def permission_target(self, args: dict) -> str:
|
|
37
|
+
return f"{args.get('subagent_type', '')}: {args.get('description', '')}"
|
|
38
|
+
|
|
39
|
+
def label(self, args: dict, ctx: ToolContext | None = None) -> str:
|
|
40
|
+
return f"Task[{args.get('subagent_type', '?')}]({args.get('description', '')})"
|
|
41
|
+
|
|
42
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
43
|
+
name = str(args.get("subagent_type") or "general")
|
|
44
|
+
agent_def = self.agents.get(name)
|
|
45
|
+
if agent_def is None:
|
|
46
|
+
return ToolResult.error(f"Unknown subagent_type '{name}'. Available: {', '.join(self.agents)}")
|
|
47
|
+
if getattr(ctx.agent, "depth", 0) >= 1:
|
|
48
|
+
return ToolResult.error("Subagents cannot start further subagents. Do the work directly.")
|
|
49
|
+
report, stats = await ctx.rt.run_subagent(agent_def, str(args.get("description", name)),
|
|
50
|
+
str(args.get("prompt", "")), ctx)
|
|
51
|
+
text, _ = truncate_middle(report or "(the subagent returned no report)", 16000)
|
|
52
|
+
footer = f"\n\n[{name} subagent: {stats}]"
|
|
53
|
+
return ToolResult(content=text + footer, summary=f"{name}: {stats}",
|
|
54
|
+
display={"type": "markdown", "text": report or ""})
|
rigcode/tools/todo.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""TodoWrite: the agent's visible task list."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from rigcode.agent.state import TodoItem
|
|
5
|
+
from rigcode.tools.base import Tool, ToolContext, ToolResult
|
|
6
|
+
|
|
7
|
+
_STATUS = {
|
|
8
|
+
"pending": "pending", "todo": "pending", "not_started": "pending", "open": "pending",
|
|
9
|
+
"in_progress": "in_progress", "in-progress": "in_progress", "doing": "in_progress", "active": "in_progress",
|
|
10
|
+
"started": "in_progress", "working": "in_progress",
|
|
11
|
+
"completed": "completed", "complete": "completed", "done": "completed", "finished": "completed",
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TodoWriteTool(Tool):
|
|
16
|
+
name = "TodoWrite"
|
|
17
|
+
kind = "read"
|
|
18
|
+
read_only = True
|
|
19
|
+
description = (
|
|
20
|
+
"Maintain your task list for multi-step work (3+ steps). Send the complete list every time. Keep "
|
|
21
|
+
"exactly one item in_progress while you work on it and mark items completed as soon as they are done. "
|
|
22
|
+
"Skip it for simple one- or two-step tasks."
|
|
23
|
+
)
|
|
24
|
+
parameters = {
|
|
25
|
+
"type": "object",
|
|
26
|
+
"properties": {
|
|
27
|
+
"todos": {
|
|
28
|
+
"type": "array",
|
|
29
|
+
"items": {
|
|
30
|
+
"type": "object",
|
|
31
|
+
"properties": {
|
|
32
|
+
"content": {"type": "string", "description": "The task, imperative form"},
|
|
33
|
+
"status": {"type": "string", "enum": ["pending", "in_progress", "completed"]},
|
|
34
|
+
},
|
|
35
|
+
"required": ["content", "status"],
|
|
36
|
+
},
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"required": ["todos"],
|
|
40
|
+
}
|
|
41
|
+
aliases = {"items": "todos", "tasks": "todos", "list": "todos", "todo_list": "todos"}
|
|
42
|
+
|
|
43
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
44
|
+
items = []
|
|
45
|
+
for raw in args.get("todos") or []:
|
|
46
|
+
if isinstance(raw, str):
|
|
47
|
+
items.append(TodoItem(content=raw))
|
|
48
|
+
continue
|
|
49
|
+
if not isinstance(raw, dict):
|
|
50
|
+
continue
|
|
51
|
+
content = raw.get("content") or raw.get("title") or raw.get("task") or raw.get("description") or ""
|
|
52
|
+
status = _STATUS.get(str(raw.get("status", "pending")).lower().strip(), "pending")
|
|
53
|
+
if content:
|
|
54
|
+
items.append(TodoItem(content=str(content), status=status, active_form=raw.get("activeForm")))
|
|
55
|
+
todos = ctx.agent.todos
|
|
56
|
+
todos.set(items)
|
|
57
|
+
done = sum(1 for t in items if t.status == "completed")
|
|
58
|
+
return ToolResult(
|
|
59
|
+
content=f"Todo list updated ({done}/{len(items)} done):\n{todos.render_text()}",
|
|
60
|
+
summary=f"Todos {done}/{len(items)}",
|
|
61
|
+
display={"type": "todos", "items": [vars(t) for t in items]},
|
|
62
|
+
)
|