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.
Files changed (64) hide show
  1. rigcode/__init__.py +4 -0
  2. rigcode/__main__.py +4 -0
  3. rigcode/agent/__init__.py +0 -0
  4. rigcode/agent/loop.py +627 -0
  5. rigcode/agent/mentions.py +70 -0
  6. rigcode/agent/prompts.py +195 -0
  7. rigcode/agent/runtime.py +535 -0
  8. rigcode/agent/session.py +165 -0
  9. rigcode/agent/state.py +161 -0
  10. rigcode/cli.py +283 -0
  11. rigcode/config.py +284 -0
  12. rigcode/doctor.py +158 -0
  13. rigcode/extensions.py +275 -0
  14. rigcode/hooks.py +142 -0
  15. rigcode/llm/__init__.py +0 -0
  16. rigcode/llm/client.py +259 -0
  17. rigcode/llm/probe.py +229 -0
  18. rigcode/llm/stream.py +240 -0
  19. rigcode/llm/textmode.py +161 -0
  20. rigcode/llm/types.py +92 -0
  21. rigcode/llm/wire.py +76 -0
  22. rigcode/mcp.py +329 -0
  23. rigcode/permissions.py +221 -0
  24. rigcode/prompts/agents/coder.md +13 -0
  25. rigcode/prompts/agents/debugger.md +14 -0
  26. rigcode/prompts/agents/explore.md +22 -0
  27. rigcode/prompts/agents/plan.md +21 -0
  28. rigcode/prompts/agents/researcher.md +14 -0
  29. rigcode/prompts/agents/reviewer.md +18 -0
  30. rigcode/prompts/agents/verifier.md +15 -0
  31. rigcode/prompts/commit.md +5 -0
  32. rigcode/prompts/compact.md +24 -0
  33. rigcode/prompts/init.md +10 -0
  34. rigcode/prompts/system.md +27 -0
  35. rigcode/tools/__init__.py +0 -0
  36. rigcode/tools/base.py +245 -0
  37. rigcode/tools/bashsafety.py +262 -0
  38. rigcode/tools/editmatch.py +367 -0
  39. rigcode/tools/files.py +534 -0
  40. rigcode/tools/interact.py +69 -0
  41. rigcode/tools/search.py +309 -0
  42. rigcode/tools/shell.py +424 -0
  43. rigcode/tools/skill.py +37 -0
  44. rigcode/tools/task.py +54 -0
  45. rigcode/tools/todo.py +62 -0
  46. rigcode/tools/web.py +346 -0
  47. rigcode/ui/__init__.py +0 -0
  48. rigcode/ui/base.py +69 -0
  49. rigcode/ui/commands.py +581 -0
  50. rigcode/ui/plain.py +321 -0
  51. rigcode/ui/render.py +207 -0
  52. rigcode/ui/terminal.py +1154 -0
  53. rigcode/utils/__init__.py +0 -0
  54. rigcode/utils/files.py +176 -0
  55. rigcode/utils/frontmatter.py +38 -0
  56. rigcode/utils/globmatch.py +91 -0
  57. rigcode/utils/jsonrepair.py +110 -0
  58. rigcode/utils/paths.py +83 -0
  59. rigcode/utils/text.py +105 -0
  60. rigcode-0.1.0.dist-info/METADATA +203 -0
  61. rigcode-0.1.0.dist-info/RECORD +64 -0
  62. rigcode-0.1.0.dist-info/WHEEL +4 -0
  63. rigcode-0.1.0.dist-info/entry_points.txt +2 -0
  64. rigcode-0.1.0.dist-info/licenses/LICENSE +21 -0
rigcode/ui/commands.py ADDED
@@ -0,0 +1,581 @@
1
+ """Built-in slash commands. Each handler is `async def handler(ui, rt, args: str)`.
2
+
3
+ `ui` is the front end (TerminalUI or PlainUI): out_line, out, out_ansi,
4
+ out_markdown, r (Renderer), choose, ask_text, run_turn, print_tool,
5
+ begin_activity/end_activity, request_exit, thinking_mode.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import json
11
+ import subprocess
12
+ import time
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from types import SimpleNamespace
17
+
18
+ from rich.table import Table
19
+ from rich.text import Text
20
+
21
+ from rigcode import __version__
22
+ from rigcode.agent.loop import _msg_text as message_text
23
+ from rigcode.agent.prompts import load_prompt
24
+ from rigcode.agent.session import SessionStore
25
+ from rigcode.config import add_permission_rule, settings_paths
26
+ from rigcode.permissions import MODE_ALIASES, MODE_DESCRIPTIONS, MODES, Rule
27
+ from rigcode.ui.render import render_diff
28
+ from rigcode.utils.paths import display_path, resolve_path
29
+ from rigcode.utils.text import est_tokens, fmt_duration, fmt_tokens, one_line
30
+
31
+
32
+ @dataclass
33
+ class Command:
34
+ name: str
35
+ description: str
36
+ run: Callable
37
+ aliases: tuple[str, ...] = ()
38
+ hint: str = ""
39
+ busy_ok: bool = False # safe to run while the agent is working
40
+
41
+
42
+ class CommandRegistry:
43
+ def __init__(self) -> None:
44
+ self.commands: dict[str, Command] = {}
45
+ self._alias: dict[str, str] = {}
46
+
47
+ def add(self, cmd: Command) -> None:
48
+ self.commands[cmd.name] = cmd
49
+ for a in cmd.aliases:
50
+ self._alias[a] = cmd.name
51
+
52
+ def find(self, name: str) -> Command | None:
53
+ name = name.lower()
54
+ return self.commands.get(name) or self.commands.get(self._alias.get(name, ""))
55
+
56
+ def entries(self, rt) -> list[tuple[str, str]]:
57
+ out = [(c.name, c.description) for c in self.commands.values()]
58
+ if rt is not None:
59
+ out += [(n, f"{c.description} (custom)") for n, c in rt.commands.items() if n not in self.commands]
60
+ return sorted(out)
61
+
62
+
63
+ _REGISTRY = CommandRegistry()
64
+
65
+
66
+ def command(name: str, description: str, *, aliases: tuple[str, ...] = (), hint: str = "", busy_ok: bool = False):
67
+ def deco(fn):
68
+ _REGISTRY.add(Command(name, description, fn, aliases, hint, busy_ok))
69
+ return fn
70
+ return deco
71
+
72
+
73
+ def build_registry() -> CommandRegistry:
74
+ return _REGISTRY
75
+
76
+
77
+ def _table(rows: list[tuple[str, str]], key_style: str = "bold") -> Table:
78
+ t = Table.grid(padding=(0, 2))
79
+ t.add_column(no_wrap=True)
80
+ t.add_column()
81
+ for k, v in rows:
82
+ t.add_row(Text(k, style=key_style), Text(v))
83
+ return t
84
+
85
+
86
+ def _print_rows(ui, rows: list[tuple[str, str]], indent: int = 2) -> None:
87
+ rendered = ui.r.ansi(_table(rows)).rstrip("\n")
88
+ ui.out_ansi("\n".join(" " * indent + l for l in rendered.split("\n")))
89
+
90
+
91
+ def _git(rt, *args: str, timeout: float = 15) -> tuple[int, str]:
92
+ try:
93
+ proc = subprocess.run(["git", *args], cwd=str(rt.cwd), capture_output=True, timeout=timeout)
94
+ except (OSError, subprocess.SubprocessError) as e:
95
+ return 1, str(e)
96
+ out = proc.stdout.decode("utf-8", errors="replace") + proc.stderr.decode("utf-8", errors="replace")
97
+ return proc.returncode, out
98
+
99
+
100
+ # ---------------------------------------------------------------- general
101
+
102
+ @command("help", "Show commands and keyboard shortcuts", aliases=("?",), busy_ok=True)
103
+ async def cmd_help(ui, rt, args: str) -> None:
104
+ rows = [(f"/{c.name}" + (f" {c.hint}" if c.hint else ""), c.description)
105
+ for c in sorted(_REGISTRY.commands.values(), key=lambda c: c.name)]
106
+ ui.out_line("\nCommands", "bold")
107
+ _print_rows(ui, rows)
108
+ if rt.commands:
109
+ ui.out_line("\nCustom commands", "bold")
110
+ _print_rows(ui, [(f"/{n}" + (f" {c.argument_hint}" if c.argument_hint else ""), c.description)
111
+ for n, c in sorted(rt.commands.items())])
112
+ ui.out_line("\nInput", "bold")
113
+ _print_rows(ui, [
114
+ ("Enter", "send (while the agent works: queue for its next step)"),
115
+ ("Alt+Enter, Ctrl+J, \\+Enter", "new line"),
116
+ ("Esc / Ctrl+C", "interrupt the agent; Ctrl+C twice on an empty prompt exits (or Ctrl+D)"),
117
+ ("Shift+Tab", "cycle permission mode: default → accept edits → plan"),
118
+ ("Ctrl+O / Ctrl+T", "toggle full thinking display / the todo list"),
119
+ ("@path", "attach a file or directory listing to your message (Tab completes)"),
120
+ ("!command", "run a shell command yourself; the agent sees the output"),
121
+ ("#note", "append a note to the project's AGENTS.md memory"),
122
+ ])
123
+
124
+
125
+ @command("exit", "Exit rigcode", aliases=("quit", "q"), busy_ok=True)
126
+ async def cmd_exit(ui, rt, args: str) -> None:
127
+ ui.request_exit()
128
+
129
+
130
+ @command("clear", "Start a new conversation (the prompt cache is kept)", aliases=("new", "reset"))
131
+ async def cmd_clear(ui, rt, args: str) -> None:
132
+ rt.new_conversation()
133
+ ui.out_line(" ⎿ Started a new conversation.", "class:dim")
134
+
135
+
136
+ @command("compact", "Summarize the conversation to free up context", hint="[what to focus on]")
137
+ async def cmd_compact(ui, rt, args: str) -> None:
138
+ await rt.main_agent.compact(args.strip() or None, reason="manual")
139
+
140
+
141
+ @command("status", "Version, model, server, session and context info", busy_ok=True)
142
+ async def cmd_status(ui, rt, args: str) -> None:
143
+ s = rt.server
144
+ ctx = rt.main_agent.context_tokens()
145
+ rows = [
146
+ ("rigcode", __version__),
147
+ ("Model", f"{rt.client.model} (effort {rt.effort or 'server default'}, tool calls: {rt.client.tool_mode})"),
148
+ ("Server", f"{rt.client.base_url} · " + (s.describe() if s.reachable else f"unreachable: {s.error}")),
149
+ ("Slots", f"pinned: main {rt.main_slot}, subagents {rt.sub_slots or '-'}" if rt.main_slot is not None
150
+ else "not pinned (the server restores each agent's cached state)"),
151
+ ("Subagents", f"context {rt.subagent_mode()}, up to {rt.subagent_concurrency} in parallel"
152
+ + (" (fresh only)" if rt.subagent_concurrency > 1 else "")),
153
+ ("Session", f"{rt.session.id} ({rt.session.path})"),
154
+ ("Directory", f"{rt.cwd} (project root {rt.project_root})"),
155
+ ("Permissions", f"{rt.permissions.mode} - {MODE_DESCRIPTIONS.get(rt.permissions.mode, '')}"),
156
+ ("Context", f"{fmt_tokens(ctx)} of {fmt_tokens(rt.context_window)} tokens; auto-compact at "
157
+ f"{fmt_tokens(rt.compact_threshold())}"),
158
+ ("Cache warm-up", rt.warmup_state),
159
+ ]
160
+ _print_rows(ui, rows)
161
+
162
+
163
+ # ---------------------------------------------------------------- context and usage
164
+
165
+ @command("context", "Show what is using the context window", busy_ok=True)
166
+ async def cmd_context(ui, rt, args: str) -> None:
167
+ agent = rt.main_agent
168
+ n_pre = agent.n_prefix()
169
+ tools = est_tokens(json.dumps(rt.tool_schemas)) if rt.client.tool_mode == "native" else 0
170
+ session = est_tokens(rt.project_context)
171
+ core = max(0, sum(est_tokens(m.get("content", "")) for m in agent.messages[:n_pre]) - session)
172
+ by_role = {"user": 0, "assistant": 0, "tool": 0}
173
+ reasoning = 0
174
+ for m in agent.messages[n_pre:]:
175
+ role = m.get("role", "user")
176
+ if role == "assistant" and m.get("reasoning_content"):
177
+ reasoning += est_tokens(m["reasoning_content"])
178
+ by_role[role] = by_role.get(role, 0) + est_tokens(message_text(m))
179
+ total = agent.context_tokens()
180
+ window = rt.context_window
181
+ rows = [
182
+ ("Tool definitions", tools), ("System prompt", core),
183
+ ("Project context (environment, repo map, memory)", session),
184
+ ("Your messages (incl. attachments)", by_role.get("user", 0)),
185
+ ("Assistant replies", by_role.get("assistant", 0) - reasoning),
186
+ ("Assistant reasoning", reasoning), ("Tool results", by_role.get("tool", 0)),
187
+ ]
188
+ _print_rows(ui, [(k, f"{fmt_tokens(v):>7} {100 * v / max(1, window):5.1f}%") for k, v in rows])
189
+ ui.out_line(f" Total ≈ {fmt_tokens(total)} of {fmt_tokens(window)} tokens "
190
+ f"({100 * total / max(1, window):.1f}%); auto-compact at {fmt_tokens(rt.compact_threshold())}. "
191
+ "Estimates; the server's count is exact after each reply.", "class:dim")
192
+
193
+
194
+ @command("cost", "Token usage, cache hits and speed for this session", aliases=("usage", "stats"), busy_ok=True)
195
+ async def cmd_cost(ui, rt, args: str) -> None:
196
+ u = rt.usage
197
+ rows = [
198
+ ("Requests", str(rt.requests)),
199
+ ("Prompt tokens", f"{u.prompt_tokens:,} ({u.cached_tokens:,} from cache, "
200
+ f"{100 * u.cached_tokens // max(1, u.prompt_tokens)}%)"),
201
+ ("Output tokens", f"{u.completion_tokens:,} (incl. reasoning)"),
202
+ ("Prompt processing", f"{u.prompt_tps:.1f} tok/s" if u.prompt_tps else "-"),
203
+ ("Generation", f"{u.gen_tps:.1f} tok/s" if u.gen_tps else "-"),
204
+ ("Session time", fmt_duration(time.time() - rt.started)),
205
+ ]
206
+ _print_rows(ui, rows)
207
+
208
+
209
+ # ---------------------------------------------------------------- model and modes
210
+
211
+ @command("model", "Show the model, or switch to a profile or model name", hint="[profile|model]")
212
+ async def cmd_model(ui, rt, args: str) -> None:
213
+ name = args.strip()
214
+ if not name:
215
+ s = rt.server
216
+ ui.out_line(f" Model: {rt.client.model} @ {rt.client.base_url}", "")
217
+ ui.out_line(" Server: " + (s.describe() if s.reachable else f"unreachable ({s.error})"), "class:dim")
218
+ if s.models:
219
+ ui.out_line(" Served models: " + ", ".join(s.models), "class:dim")
220
+ profiles = rt.settings.get("profiles", {}) or {}
221
+ if profiles:
222
+ ui.out_line(" Profiles: " + ", ".join(sorted(profiles)) + " (switch with /model <profile>)", "class:dim")
223
+ return
224
+ desc = await rt.switch_model(name)
225
+ ui.out_line(f" ⎿ Now using {desc}", "class:dim")
226
+ ui.out_line(" ⎿ The next request re-reads the whole conversation on the new model.", "class:dim")
227
+
228
+
229
+ @command("effort", "Show or set the reasoning effort", hint="[low|medium|high|max|none]", aliases=("reasoning",))
230
+ async def cmd_effort(ui, rt, args: str) -> None:
231
+ if not args.strip():
232
+ ui.out_line(f" Reasoning effort: {rt.effort or 'server default'} "
233
+ "(low = quick, high/max = slower and more thorough, none = no thinking)", "")
234
+ return
235
+ old = rt.effort
236
+ try:
237
+ new = rt.set_effort(args.strip())
238
+ except ValueError as e:
239
+ ui.out_line(str(e), "class:error")
240
+ return
241
+ ui.out_line(f" ⎿ Reasoning effort: {old or 'default'} → {new or 'default'}", "class:dim")
242
+ tokens = rt.main_agent.context_tokens()
243
+ if new != old and tokens > 2000:
244
+ speed = rt.usage.prompt_tps or 25.0
245
+ ui.out_line(f" ⎿ The effort setting is part of the prompt, so the next request re-reads the whole "
246
+ f"conversation (~{fmt_tokens(tokens)} tokens, about {fmt_duration(tokens / speed)} here).",
247
+ "class:warn")
248
+
249
+
250
+ @command("mode", "Show or set the permission mode", hint="[default|acceptEdits|plan|bypass]",
251
+ aliases=("permission-mode",), busy_ok=True)
252
+ async def cmd_mode(ui, rt, args: str) -> None:
253
+ want = args.strip()
254
+ if not want:
255
+ for m in MODES:
256
+ mark = "❯" if m == rt.permissions.mode else " "
257
+ ui.out_line(f" {mark} {m:<12} {MODE_DESCRIPTIONS[m]}", "bold" if m == rt.permissions.mode else "")
258
+ return
259
+ if want not in MODES and want.lower() not in MODE_ALIASES and want.lower() not in [m.lower() for m in MODES]:
260
+ ui.out_line(f"Unknown mode '{want}'. Modes: {', '.join(MODES)}", "class:error")
261
+ return
262
+ want = next((m for m in MODES if m.lower() == want.lower()), want)
263
+ mode = rt.set_mode(want)
264
+ ui.out_line(f" ⎿ Permission mode: {mode} - {MODE_DESCRIPTIONS[mode]}", "class:dim")
265
+
266
+
267
+ @command("plan", "Switch to plan mode (read-only investigation, then a plan for approval)", busy_ok=True)
268
+ async def cmd_plan(ui, rt, args: str) -> None:
269
+ rt.set_mode("plan")
270
+ ui.out_line(" ⎿ Plan mode on. The agent will investigate and propose a plan before changing anything.",
271
+ "class:dim")
272
+ if args.strip():
273
+ ui.submit_message(args.strip())
274
+
275
+
276
+ @command("thinking", "How to show the model's thinking", hint="[collapsed|full|hidden]", busy_ok=True)
277
+ async def cmd_thinking(ui, rt, args: str) -> None:
278
+ want = args.strip().lower()
279
+ if want not in ("collapsed", "full", "hidden"):
280
+ ui.out_line(f" Thinking display: {ui.thinking_mode} (choose collapsed, full or hidden; ctrl+o toggles)", "")
281
+ return
282
+ ui.thinking_mode = want
283
+ ui.out_line(f" ⎿ Thinking display: {want}", "class:dim")
284
+
285
+
286
+ # ---------------------------------------------------------------- permissions and tools
287
+
288
+ @command("permissions", "Show permission rules, or add one", hint="[allow|deny|ask <rule>]",
289
+ aliases=("perms", "allowed-tools"), busy_ok=True)
290
+ async def cmd_permissions(ui, rt, args: str) -> None:
291
+ parts = args.split(None, 1)
292
+ if len(parts) == 2 and parts[0] in ("allow", "deny", "ask"):
293
+ kind, rule = parts[0], parts[1].strip()
294
+ if Rule.parse(rule) is None:
295
+ ui.out_line(f"Invalid rule '{rule}'. Examples: Bash(npm test:*), Edit(src/**), WebFetch(domain:x.org)",
296
+ "class:error")
297
+ return
298
+ path = add_permission_rule(rt.project_root, rule, kind, "local")
299
+ lst = rt.settings.data.setdefault("permissions", {}).setdefault(kind, [])
300
+ if rule not in lst:
301
+ lst.append(rule)
302
+ ui.out_line(f" ⎿ Added {kind} rule {rule} (saved to {path})", "class:dim")
303
+ return
304
+ p = rt.permissions
305
+ ui.out_line(f" Mode: {p.mode} - {MODE_DESCRIPTIONS[p.mode]}", "bold")
306
+ for kind in ("allow", "ask", "deny"):
307
+ rules = list(rt.settings.get(f"permissions.{kind}", []) or [])
308
+ if kind == "allow":
309
+ rules += [f"{r} (this session)" for r in p.session_allow if r not in rules]
310
+ ui.out_line(f" {kind}: " + (", ".join(rules) if rules else "(none)"), "")
311
+ ui.out_line(" Workspace: " + ", ".join(str(w) for w in p.workspace), "class:dim")
312
+ paths = settings_paths(rt.project_root)
313
+ ui.out_line(f" Rules live in {paths['local']} (personal) or {paths['project']} (shared). "
314
+ "Add one with /permissions allow <rule>.", "class:dim")
315
+
316
+
317
+ @command("add-dir", "Let the agent edit files in another directory", hint="<path>")
318
+ async def cmd_add_dir(ui, rt, args: str) -> None:
319
+ if not args.strip():
320
+ ui.out_line("Usage: /add-dir <path>", "class:warn")
321
+ return
322
+ path = resolve_path(args.strip(), rt.cwd)
323
+ if not path.is_dir():
324
+ ui.out_line(f"Not a directory: {path}", "class:error")
325
+ return
326
+ if path not in rt.permissions.workspace:
327
+ rt.permissions.workspace.append(path)
328
+ rt.main_agent.add_reminder(f"The user added {path} to the workspace; you may work on files there too.")
329
+ ui.out_line(f" ⎿ Added {path} to the workspace for this session.", "class:dim")
330
+
331
+
332
+ @command("tools", "List the tools available to the agent", busy_ok=True)
333
+ async def cmd_tools(ui, rt, args: str) -> None:
334
+ rows = [(t.name, one_line(t.description.split(". ")[0], 90)) for t in rt.tools.all()]
335
+ _print_rows(ui, rows)
336
+
337
+
338
+ @command("agents", "List the subagents the main agent can delegate to", busy_ok=True)
339
+ async def cmd_agents(ui, rt, args: str) -> None:
340
+ rows = []
341
+ for name, a in sorted(rt.agents.items()):
342
+ tools = ", ".join(a.tools) if a.tools else "all tools"
343
+ flags = [a.source] + (["read-only"] if a.read_only else []) + ([f"effort {a.effort}"] if a.effort else [])
344
+ rows.append((name, f"{one_line(a.description, 80)}\n[{', '.join(flags)}; {tools}]"))
345
+ _print_rows(ui, rows or [("(none)", "")])
346
+ mode = rt.subagent_mode()
347
+ how = {"fork": "they start from a copy of this conversation",
348
+ "fresh": "they start from just the system prompt and their brief",
349
+ "auto": "they start from a copy of this conversation unless it is very large"}[mode]
350
+ ui.out_line(f" Subagent context: {mode} ({how}; agents.context). Add your own agents as Markdown files "
351
+ "in .rigcode/agents/ or .claude/agents/.", "class:dim")
352
+
353
+
354
+ @command("skills", "List available skills", busy_ok=True)
355
+ async def cmd_skills(ui, rt, args: str) -> None:
356
+ rows = [(s.name, f"{one_line(s.description, 90)} [{s.source}]") for s in sorted(rt.skills.values(), key=lambda s: s.name)]
357
+ _print_rows(ui, rows or [("(none)", "Add skills as <name>/SKILL.md under .rigcode/skills/ or .claude/skills/")])
358
+
359
+
360
+ @command("mcp", "Show MCP server status", busy_ok=True)
361
+ async def cmd_mcp(ui, rt, args: str) -> None:
362
+ lines = rt.mcp.status_lines()
363
+ if not lines:
364
+ ui.out_line(" No MCP servers configured (add them to .mcp.json or settings \"mcp_servers\").", "class:dim")
365
+ for line in lines:
366
+ ui.out_line(" " + line, "")
367
+
368
+
369
+ @command("memory", "Show the memory files loaded into the system prompt", busy_ok=True)
370
+ async def cmd_memory(ui, rt, args: str) -> None:
371
+ if not rt.memory:
372
+ ui.out_line(" No memory files loaded. Create AGENTS.md (or run /init); use #note to add lines.", "class:dim")
373
+ return
374
+ for m in rt.memory:
375
+ ui.out_line(f" {m.path} ({m.scope}, {len(m.content):,} chars)", "")
376
+ ui.out_line(" Edits take effect in the next session (the system prompt is fixed per session to keep the "
377
+ "cache warm). Use #note to tell the current session too.", "class:dim")
378
+
379
+
380
+ @command("bashes", "List background shells", aliases=("shells",), busy_ok=True)
381
+ async def cmd_bashes(ui, rt, args: str) -> None:
382
+ lines = rt.shells.describe()
383
+ for line in lines or ["No background shells."]:
384
+ ui.out_line(" " + line, "")
385
+
386
+
387
+ @command("todos", "Show the agent's todo list", busy_ok=True)
388
+ async def cmd_todos(ui, rt, args: str) -> None:
389
+ ui.out_line(" " + rt.main_agent.todos.render_text().replace("\n", "\n "), "")
390
+
391
+
392
+ # ---------------------------------------------------------------- workflows
393
+
394
+ @command("init", "Create or improve AGENTS.md for this project", hint="[instructions]")
395
+ async def cmd_init(ui, rt, args: str) -> None:
396
+ prompt = load_prompt("init")
397
+ if args.strip():
398
+ prompt += f"\n\nAdditional instructions from the user: {args.strip()}"
399
+ await ui.run_turn(prompt)
400
+
401
+
402
+ @command("commit", "Commit the current changes with a well-written message", hint="[instructions]")
403
+ async def cmd_commit(ui, rt, args: str) -> None:
404
+ prompt = load_prompt("commit")
405
+ if args.strip():
406
+ prompt += f"\n\nAdditional instructions from the user: {args.strip()}"
407
+ await ui.run_turn(prompt)
408
+
409
+
410
+ @command("review", "Review uncommitted changes with the reviewer subagent", hint="[focus]")
411
+ async def cmd_review(ui, rt, args: str) -> None:
412
+ agent_def = rt.agents.get("reviewer")
413
+ if agent_def is None:
414
+ ui.out_line("The reviewer agent is not available (disabled?).", "class:error")
415
+ return
416
+ brief = ("Review the uncommitted changes in this repository. Start with `git status --short` and `git diff HEAD` "
417
+ "(read untracked files that matter), then read the surrounding code as needed. Report concrete, verified "
418
+ "problems ranked by severity with file:line references, and end with a one-line overall assessment. "
419
+ "Skip style nitpicks unless they hide a bug.")
420
+ if args.strip():
421
+ brief += f"\nFocus on: {args.strip()}"
422
+ key = "review"
423
+ ui.begin_activity(key, "Task[reviewer](Review uncommitted changes)")
424
+ try:
425
+ report, stats = await rt.run_subagent(agent_def, "Review uncommitted changes", brief,
426
+ SimpleNamespace(agent=rt.main_agent, call_id=key))
427
+ finally:
428
+ ui.end_activity(key)
429
+ ui.out_markdown(report or "(the reviewer returned no report)", bullet="● ")
430
+ ui.out_line(f" ⎿ reviewer: {stats}", "class:faint")
431
+ if report:
432
+ rt.main_agent.add_reminder("The user ran /review. The reviewer subagent reported:\n\n" + report
433
+ + "\n\nThe user may ask you to address these findings.")
434
+
435
+
436
+ @command("diff", "Show uncommitted changes", busy_ok=True)
437
+ async def cmd_diff(ui, rt, args: str) -> None:
438
+ code, stat = await asyncio.to_thread(_git, rt, "diff", "HEAD", "--stat")
439
+ if code != 0:
440
+ code, stat = await asyncio.to_thread(_git, rt, "diff", "--stat")
441
+ if code != 0:
442
+ ui.out_line(f"git diff failed: {one_line(stat, 200)}", "class:error")
443
+ return
444
+ if not stat.strip():
445
+ ui.out_line(" No uncommitted changes to tracked files.", "class:dim")
446
+ return
447
+ ui.out_line(stat.rstrip(), "class:dim")
448
+ _, patch = await asyncio.to_thread(_git, rt, "diff", "HEAD")
449
+ budget = 300
450
+ for chunk in patch.split("diff --git ")[1:]:
451
+ header, _, body = chunk.partition("\n")
452
+ name = header.split(" b/")[-1] if " b/" in header else header
453
+ ui.out_line(f"\n {name}", "bold")
454
+ text = render_diff(body, max_lines=max(10, min(80, budget)), indent=2)
455
+ ui.out_ansi(ui.r.ansi(text))
456
+ budget -= 80
457
+ if budget <= 0:
458
+ ui.out_line(" … more files not shown", "class:faint")
459
+ break
460
+
461
+
462
+ @command("undo", "Revert the file changes from the agent's most recent turn that changed files",
463
+ aliases=("rewind",))
464
+ async def cmd_undo(ui, rt, args: str) -> None:
465
+ cp = rt.checkpoints.last_with_changes()
466
+ if cp is None:
467
+ ui.out_line(" Nothing to undo (no file changes recorded this session).", "class:dim")
468
+ return
469
+ files = [display_path(Path(p), rt.cwd) for p in cp.files]
470
+ shown = "\n".join(f" {f}" for f in files[:12]) + (f"\n … {len(files) - 12} more" if len(files) > 12 else "")
471
+ idx = await ui.choose(f"Revert {len(files)} file(s) changed during \"{one_line(cp.label, 50)}\"?\n{shown}",
472
+ ["Yes, revert them", "No"])
473
+ if idx != 0:
474
+ return
475
+ results = rt.checkpoints.undo_last()
476
+ for path, status in results:
477
+ ui.out_line(f" ⎿ {display_path(Path(path), rt.cwd)}: {status}", "class:dim")
478
+ rt.file_state.forget(Path(path))
479
+ rt.main_agent.add_reminder(
480
+ f"The user reverted the file changes from the turn \"{cp.label}\": {', '.join(files)}. Those files are back "
481
+ "to their earlier contents; Read them again before editing.")
482
+
483
+
484
+ # ---------------------------------------------------------------- sessions
485
+
486
+ @command("resume", "Resume a previous session in this project", hint="[session id]")
487
+ async def cmd_resume(ui, rt, args: str) -> None:
488
+ if args.strip():
489
+ path = SessionStore.resolve(rt.project_root, args.strip())
490
+ if path is None:
491
+ ui.out_line(f"No session matching '{args.strip()}'.", "class:error")
492
+ return
493
+ else:
494
+ infos = [i for i in SessionStore.list(rt.project_root, limit=15) if i.id != rt.session.id and i.n_messages]
495
+ if not infos:
496
+ ui.out_line(" No previous sessions in this project.", "class:dim")
497
+ return
498
+ labels = [f"{time.strftime('%m-%d %H:%M', time.localtime(i.mtime))} · {i.n_messages:>3} msgs · "
499
+ f"{one_line(i.title or '(untitled)', 60)}" for i in infos]
500
+ idx = await ui.choose("Resume which session?", labels)
501
+ if idx is None:
502
+ return
503
+ path = infos[idx].path
504
+ n = rt.resume(path)
505
+ last_user = next((message_text(m) for m in reversed(rt.main_agent.messages)
506
+ if m.get("role") == "user" and not m.get("_meta")), "")
507
+ how = "re-reading them in the background" if rt.warmup_state == "running" else "the first reply re-reads them"
508
+ ui.out_line(f" ⎿ Resumed {path.stem} ({n} messages, ~{fmt_tokens(rt.main_agent.context_tokens())} tokens; "
509
+ f"{how}).", "class:dim")
510
+ if last_user:
511
+ ui.out_line(f" ⎿ Last message: {one_line(last_user, 100)}", "class:faint")
512
+ reply = rt.main_agent.last_assistant_text()
513
+ if reply:
514
+ ui.out_markdown(reply[-3000:], bullet="● ")
515
+
516
+
517
+ @command("export", "Save the conversation as a Markdown file", hint="[path]")
518
+ async def cmd_export(ui, rt, args: str) -> None:
519
+ path = resolve_path(args.strip(), rt.cwd) if args.strip() else rt.cwd / f"rigcode-{rt.session.id}.md"
520
+ lines = [f"# rigcode session {rt.session.id}", "", f"Model: {rt.client.model} · exported {time.strftime('%Y-%m-%d %H:%M')}", ""]
521
+ for m in rt.main_agent.messages:
522
+ role = m.get("role")
523
+ if role == "system":
524
+ continue
525
+ if role == "user":
526
+ lines += ["## User" if not m.get("_meta") else "## (rigcode note)", "", message_text(m).strip(), ""]
527
+ elif role == "assistant":
528
+ if m.get("content"):
529
+ lines += ["## Assistant", "", m["content"].strip(), ""]
530
+ for tc in m.get("tool_calls") or []:
531
+ fn = tc.get("function", {})
532
+ lines += [f"**Tool call** `{fn.get('name')}`", "", "```json", fn.get("arguments", ""), "```", ""]
533
+ elif role == "tool":
534
+ body = (m.get("content") or "")[:4000]
535
+ lines += [f"**Result** ({m.get('name', 'tool')})", "", "```", body, "```", ""]
536
+ try:
537
+ path.write_text("\n".join(lines), encoding="utf-8")
538
+ except OSError as e:
539
+ ui.out_line(f"Could not write {path}: {e}", "class:error")
540
+ return
541
+ ui.out_line(f" ⎿ Exported to {path}", "class:dim")
542
+
543
+
544
+ # ---------------------------------------------------------------- settings and diagnostics
545
+
546
+ def _mask(data):
547
+ if isinstance(data, dict):
548
+ return {k: ("***" if any(s in k.lower() for s in ("key", "token", "secret", "password")) and v else _mask(v))
549
+ for k, v in data.items()}
550
+ if isinstance(data, list):
551
+ return [_mask(v) for v in data]
552
+ return data
553
+
554
+
555
+ @command("config", "Show settings, or set one for this session", hint="[key [value]]", busy_ok=True)
556
+ async def cmd_config(ui, rt, args: str) -> None:
557
+ key, _, value = args.strip().partition(" ")
558
+ if not key:
559
+ for src in rt.settings.sources:
560
+ state = "loaded" if src.loaded else ("error: " + src.error if src.error else "not present")
561
+ ui.out_line(f" {src.scope:<8} {src.path} ({state})", "class:dim")
562
+ text = json.dumps(_mask(rt.settings.data), indent=2, ensure_ascii=False)
563
+ ui.out_ansi(ui.r.markdown(f"```json\n{text}\n```"))
564
+ return
565
+ if not value.strip():
566
+ ui.out_line(f" {key} = {json.dumps(_mask(rt.settings.get(key)), ensure_ascii=False)}", "")
567
+ return
568
+ try:
569
+ parsed = json.loads(value)
570
+ except json.JSONDecodeError:
571
+ parsed = value.strip()
572
+ rt.settings.set(key, parsed)
573
+ ui.out_line(f" ⎿ {key} = {json.dumps(parsed, ensure_ascii=False)} for this session "
574
+ "(edit .rigcode/settings.json to make it permanent).", "class:dim")
575
+
576
+
577
+ @command("doctor", "Check the server connection, tools and configuration")
578
+ async def cmd_doctor(ui, rt, args: str) -> None:
579
+ from rigcode.doctor import run_doctor
580
+ await run_doctor(rt.settings, rt.project_root, lambda text, style="": ui.out_line(text, style),
581
+ chat_test="quick" not in args)