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/terminal.py ADDED
@@ -0,0 +1,1154 @@
1
+ """Interactive terminal front end.
2
+
3
+ The prompt stays live while the agent works: type ahead to queue a message (it
4
+ is delivered at the agent's next step), Esc or Ctrl+C interrupts. A live area
5
+ above the prompt shows progress, streaming text, running tools and subagents;
6
+ finished output is committed to the scrollback as rendered markdown.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import re
12
+ import time
13
+ import traceback
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ from prompt_toolkit import PromptSession, print_formatted_text
18
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
19
+ from prompt_toolkit.completion import Completer, Completion
20
+ from prompt_toolkit.filters import Condition, has_completions
21
+ from prompt_toolkit.formatted_text import ANSI, FormattedText
22
+ from prompt_toolkit.history import FileHistory, InMemoryHistory
23
+ from prompt_toolkit.key_binding import KeyBindings
24
+ from prompt_toolkit.keys import Keys
25
+ from prompt_toolkit.styles import Style
26
+ from prompt_toolkit.utils import get_cwidth
27
+
28
+ from rigcode import __version__
29
+ from rigcode.agent.mentions import expand_mentions
30
+ from rigcode.permissions import Decision
31
+ from rigcode.tools.base import ToolContext, ToolResult
32
+ from rigcode.ui.base import BaseUI
33
+ from rigcode.ui.render import BlockSplitter, Renderer, render_todos, term_width
34
+ from rigcode.utils.files import list_project_files
35
+ from rigcode.utils.text import fmt_duration, fmt_tokens, one_line, strip_ansi
36
+
37
+ SPINNER = "·✢✳✶✻✽✻✶✳✢"
38
+
39
+ STYLE = Style.from_dict({
40
+ "prompt": "bold",
41
+ "dim": "#8a8a8a",
42
+ "faint": "#626262",
43
+ "user": "#ffffff bg:#303030",
44
+ "user.prefix": "#8a8a8a bg:#303030",
45
+ "tool.bullet": "#5fd75f",
46
+ "tool.bullet.err": "#ff5f5f",
47
+ "tool.bullet.run": "#d7af5f",
48
+ "tool.label": "bold",
49
+ "error": "#ff5f5f",
50
+ "warn": "#ffaf00",
51
+ "ok": "#5fd75f",
52
+ "thinking": "italic #8a8a8a",
53
+ "spinner": "#d7875f",
54
+ "status": "#d7875f",
55
+ "hint": "#6c6c6c",
56
+ "dialog.title": "bold #87afd7",
57
+ "dialog.sel": "bold #87d7ff",
58
+ "dialog.opt": "",
59
+ "mode.plan": "#5fafaf",
60
+ "mode.accept": "#af87ff",
61
+ "mode.bypass": "#ff5f5f",
62
+ "bottom-toolbar": "noreverse #6c6c6c",
63
+ "placeholder": "#6c6c6c",
64
+ "agent": "bold #87afd7",
65
+ "queued": "italic #8a8a8a",
66
+ "banner": "bold #d7875f",
67
+ })
68
+
69
+
70
+ @dataclass
71
+ class AgentView:
72
+ agent: object
73
+ name: str
74
+ description: str = ""
75
+ phase: str = "idle" # idle | waiting | prompt | thinking | writing | calling | tools | compacting
76
+ started: float = field(default_factory=time.monotonic)
77
+ req_started: float = 0.0
78
+ gen_started: float | None = None
79
+ think_started: float | None = None
80
+ thought_printed: bool = False
81
+ think_tokens: int = 0
82
+ out_tokens: int = 0
83
+ progress: dict | None = None
84
+ reasoning_tail: str = ""
85
+ tool_name: str | None = None
86
+ tool_args_chars: int = 0
87
+ tool_calls: int = 0
88
+ recent_tools: list[str] = field(default_factory=list)
89
+ first_block: bool = True
90
+
91
+
92
+ @dataclass
93
+ class ToolView:
94
+ agent: object
95
+ label: str
96
+ started: float
97
+ output: str = ""
98
+
99
+
100
+ @dataclass
101
+ class Dialog:
102
+ title: str
103
+ options: list[str]
104
+ future: asyncio.Future
105
+ index: int = 0
106
+ text_option: int | None = None
107
+ typing: bool = False
108
+ text_label: str = ""
109
+
110
+
111
+ def _cut(line: str, width: int) -> int:
112
+ w = 0
113
+ for i, ch in enumerate(line):
114
+ w += get_cwidth(ch)
115
+ if w > width:
116
+ return max(1, i)
117
+ return len(line)
118
+
119
+
120
+ def wrap_lines(text: str, width: int) -> list[str]:
121
+ width = max(10, width)
122
+ out: list[str] = []
123
+ for raw in text.split("\n"):
124
+ line = raw.expandtabs(4)
125
+ while get_cwidth(line) > width:
126
+ n = _cut(line, width)
127
+ out.append(line[:n])
128
+ line = line[n:]
129
+ out.append(line)
130
+ return out
131
+
132
+
133
+ def tail_lines(text: str, n: int, width: int) -> list[str]:
134
+ clean = strip_ansi(text).replace("\r\n", "\n").replace("\r", "\n")
135
+ lines = [l for l in clean.split("\n") if l.strip()]
136
+ return [one_line(l, width) for l in lines[-n:]]
137
+
138
+
139
+ def _subsequence(needle: str, hay: str) -> bool:
140
+ it = iter(hay)
141
+ return all(ch in it for ch in needle)
142
+
143
+
144
+ class _Completer(Completer):
145
+ def __init__(self, ui: TerminalUI):
146
+ self.ui = ui
147
+ self._files: list[str] = []
148
+ self._dirs: list[str] = []
149
+ self._at = 0.0
150
+
151
+ def _project_files(self) -> tuple[list[str], list[str]]:
152
+ if time.monotonic() - self._at > 30 and self.ui.rt is not None:
153
+ try:
154
+ self._files = list_project_files(self.ui.rt.project_root, max_files=50_000)
155
+ except Exception: # noqa: BLE001
156
+ self._files = []
157
+ dirs = set()
158
+ for f in self._files:
159
+ parts = f.split("/")[:-1]
160
+ for i in range(1, len(parts) + 1):
161
+ dirs.add("/".join(parts[:i]) + "/")
162
+ self._dirs = sorted(dirs)
163
+ self._at = time.monotonic()
164
+ return self._files, self._dirs
165
+
166
+ def get_completions(self, document, complete_event):
167
+ text = document.text_before_cursor
168
+ if text.startswith("/") and " " not in text and "\n" not in text:
169
+ word = text[1:].lower()
170
+ for name, desc in self.ui.command_entries():
171
+ if name.lower().startswith(word):
172
+ yield Completion("/" + name, start_position=-len(text), display="/" + name,
173
+ display_meta=one_line(desc, 60))
174
+ return
175
+ m = re.search(r"(?:^|\s)@([^\s@\"]*)$", text)
176
+ if not m:
177
+ return
178
+ frag = m.group(1)
179
+ low = frag.lower().replace("\\", "/")
180
+ files, dirs = self._project_files()
181
+ scored = []
182
+ for f in dirs + files:
183
+ fl = f.lower()
184
+ if low and low not in fl and not _subsequence(low, fl):
185
+ continue
186
+ if not low:
187
+ rank = 0 if f.count("/") <= (1 if f.endswith("/") else 0) else 5
188
+ elif fl.startswith(low):
189
+ rank = 0
190
+ elif "/" + low in fl:
191
+ rank = 1
192
+ elif low in fl:
193
+ rank = 2
194
+ else:
195
+ rank = 3
196
+ scored.append((rank, len(f), f))
197
+ for _, _, f in sorted(scored)[:40]:
198
+ yield Completion(f, start_position=-len(frag), display=f)
199
+
200
+
201
+ class TerminalUI(BaseUI):
202
+ interactive = True
203
+
204
+ def __init__(self, settings, history_path: Path | None = None):
205
+ from rigcode.ui.commands import build_registry
206
+ self.settings = settings
207
+ self.rt = None
208
+ self.commands = build_registry()
209
+ self.r = Renderer()
210
+ self.thinking_mode = str(settings.get("ui.thinking", "collapsed"))
211
+ self.notify = str(settings.get("ui.notify", "bell"))
212
+ self.tool_output_lines = int(settings.get("ui.tool_output_lines", 6) or 6)
213
+ self.views: dict[int, AgentView] = {}
214
+ self.running: dict[str, ToolView] = {}
215
+ self.dialog: Dialog | None = None
216
+ self.queued: list[str] = []
217
+ self.task: asyncio.Task | None = None
218
+ self.task_label = ""
219
+ self.task_started = 0.0
220
+ self.splitter = BlockSplitter()
221
+ self.think_splitter = BlockSplitter()
222
+ self.warmup: dict = {"state": "off"}
223
+ self.show_todos = False
224
+ self.exit_requested = False
225
+ self._ctx_cache = (0.0, 0)
226
+ self._last_ctrl_c = 0.0
227
+ self._stash = None
228
+ self._ticker: asyncio.Task | None = None
229
+ history = InMemoryHistory()
230
+ if history_path is not None:
231
+ try:
232
+ history_path.parent.mkdir(parents=True, exist_ok=True)
233
+ history = FileHistory(str(history_path))
234
+ except OSError:
235
+ pass
236
+ self.session = PromptSession(
237
+ message=self._message, bottom_toolbar=self._toolbar, style=STYLE, history=history,
238
+ completer=_Completer(self), complete_while_typing=True, auto_suggest=AutoSuggestFromHistory(),
239
+ key_bindings=self._bindings(), erase_when_done=True, reserve_space_for_menu=0,
240
+ placeholder=self._placeholder, prompt_continuation=lambda w, n, s: " " * min(w, 2),
241
+ multiline=False, wrap_lines=True, mouse_support=False)
242
+ self.session.default_buffer.on_text_changed += self._on_text_changed
243
+ self.session.app.timeoutlen = 0.3
244
+ self.session.app.ttimeoutlen = 0.05
245
+
246
+ # ================================================================== output helpers
247
+ @property
248
+ def busy(self) -> bool:
249
+ return self.task is not None and not self.task.done()
250
+
251
+ def out(self, fragments: list[tuple[str, str]]) -> None:
252
+ print_formatted_text(FormattedText(fragments), style=STYLE, end="")
253
+
254
+ def out_line(self, text: str, style: str = "") -> None:
255
+ self.out([(style, text + "\n")])
256
+
257
+ def out_ansi(self, text: str) -> None:
258
+ if text.strip():
259
+ print_formatted_text(ANSI(text.rstrip("\n") + "\n"), end="")
260
+
261
+ def out_markdown(self, text: str, bullet: str | None = None, style: str | None = None) -> None:
262
+ width = term_width() - 2
263
+ rendered = self.r.markdown(text, width=width, style=style).strip("\n")
264
+ if not rendered.strip():
265
+ return
266
+ lines = rendered.split("\n")
267
+ first = bullet if bullet is not None else " "
268
+ self.out_ansi("\n" + "\n".join((first if i == 0 else " ") + l for i, l in enumerate(lines)))
269
+
270
+ def notice(self, level: str, text: str) -> None:
271
+ self.on_notice(level, text)
272
+
273
+ def _invalidate(self) -> None:
274
+ app = self.session.app
275
+ if app.is_running:
276
+ app.invalidate()
277
+
278
+ def _bell(self) -> None:
279
+ if self.notify == "bell":
280
+ try:
281
+ self.session.app.output.bell()
282
+ self.session.app.output.flush()
283
+ except Exception: # noqa: BLE001
284
+ pass
285
+
286
+ def command_entries(self) -> list[tuple[str, str]]:
287
+ return self.commands.entries(self.rt)
288
+
289
+ # ================================================================== live area
290
+ def _main_view(self) -> AgentView | None:
291
+ main = self.rt.main_agent if self.rt else None
292
+ return self.views.get(id(main)) if main is not None else None
293
+
294
+ def _phase_text(self, v: AgentView, now: float) -> str:
295
+ p = v.phase
296
+ if p == "waiting":
297
+ if self.warmup.get("state") == "running" and getattr(v.agent, "is_main", False):
298
+ return f"Waiting for the cache warm-up to finish{self._warmup_pct()}"
299
+ return "Waiting for the model"
300
+ if p == "prompt":
301
+ pr = v.progress or {}
302
+ total, cache, done = int(pr.get("total") or 0), int(pr.get("cache") or 0), int(pr.get("processed") or 0)
303
+ todo = max(1, total - cache)
304
+ got = max(0, done - cache)
305
+ text = f"Reading prompt {min(100, 100 * got // todo)}% ({fmt_tokens(got)}/{fmt_tokens(todo)} tokens"
306
+ if cache:
307
+ text += f", {fmt_tokens(cache)} cached"
308
+ text += ")"
309
+ ms = float(pr.get("time_ms") or 0)
310
+ if got > 0 and ms > 1000 and total > done:
311
+ text += f" · ~{fmt_duration((total - done) / (got / (ms / 1000)))} left"
312
+ return text
313
+ if p == "thinking":
314
+ secs = now - (v.think_started or now)
315
+ return f"Thinking · {v.think_tokens} tokens · {fmt_duration(secs)}"
316
+ if p == "writing":
317
+ rate = ""
318
+ if v.gen_started and now - v.gen_started > 2:
319
+ rate = f" · {(v.think_tokens + v.out_tokens) / (now - v.gen_started):.1f} tok/s"
320
+ return f"Writing · {v.out_tokens} tokens{rate}"
321
+ if p == "calling":
322
+ return f"Preparing {v.tool_name or 'tool'} call · ~{fmt_tokens(v.tool_args_chars / 3.5)} tokens"
323
+ if p == "tools":
324
+ n = sum(1 for t in self.running.values() if t.agent is v.agent)
325
+ return f"Running {n} tool{'s' if n != 1 else ''}" if n else "Working"
326
+ if p == "compacting":
327
+ return f"Compacting the conversation · {v.out_tokens} tokens"
328
+ return "Working"
329
+
330
+ def _warmup_pct(self) -> str:
331
+ pr = self.warmup
332
+ total, cache, done = int(pr.get("total") or 0), int(pr.get("cache") or 0), int(pr.get("processed") or 0)
333
+ if total <= 0:
334
+ return ""
335
+ return f" ({min(100, 100 * max(0, done - cache) // max(1, total - cache))}%)"
336
+
337
+ def _live(self, w: int) -> list[tuple[str, str]]:
338
+ now = time.monotonic()
339
+ rt = self.rt
340
+ main = rt.main_agent if rt else None
341
+ mv = self._main_view()
342
+ out: list[tuple[str, str]] = [("", "\n")]
343
+ if mv and mv.phase == "writing" and self.splitter.pending.strip():
344
+ for line in wrap_lines(self.splitter.pending.strip("\n"), w - 2)[-8:]:
345
+ out.append(("", " " + line + "\n"))
346
+ elif mv and mv.phase == "thinking" and self.thinking_mode != "hidden":
347
+ pending = self.think_splitter.pending if self.thinking_mode == "full" else mv.reasoning_tail
348
+ tail = " ".join(pending.split())
349
+ if tail:
350
+ for line in wrap_lines(tail, w - 4)[-2:]:
351
+ out.append(("class:thinking", " " + line + "\n"))
352
+ for cid, tv in list(self.running.items()):
353
+ if tv.agent is not main:
354
+ continue
355
+ out += [("class:tool.bullet.run", "● "), ("class:tool.label", one_line(tv.label, w - 14)),
356
+ ("class:dim", f" {fmt_duration(now - tv.started)}\n")]
357
+ if tv.output:
358
+ for i, line in enumerate(tail_lines(tv.output, 4, w - 6)):
359
+ out.append(("class:dim", (" ⎿ " if i == 0 else " ") + line + "\n"))
360
+ for sv in list(self.views.values()):
361
+ if getattr(sv.agent, "depth", 0) == 0 or getattr(sv.agent, "parent_call_id", "") != cid:
362
+ continue
363
+ out += [("class:dim", " ⎿ "), ("class:agent", sv.name),
364
+ ("class:dim", f" · {sv.tool_calls} tool calls · {fmt_duration(now - sv.started)} · "
365
+ f"{one_line(self._phase_text(sv, now), max(20, w - 50))}\n")]
366
+ for t in sv.recent_tools[-3:]:
367
+ out.append(("class:faint", f" {one_line(t, w - 8)}\n"))
368
+ if main is not None and main.todos.items:
369
+ open_items = main.todos.open_items()
370
+ if self.show_todos:
371
+ out.append(("class:dim", " Todos (ctrl+t to hide)\n"))
372
+ for t in main.todos.items:
373
+ mark = {"completed": "☒", "in_progress": "▸"}.get(t.status, "☐")
374
+ style = "class:faint" if t.status == "completed" else ("bold" if t.status == "in_progress" else "")
375
+ out.append((style, f" {mark} {one_line(t.content, w - 8)}\n"))
376
+ elif open_items and self.busy:
377
+ done = len(main.todos.items) - len(open_items)
378
+ cur = next((t for t in main.todos.items if t.status == "in_progress"), None)
379
+ text = f" ☐ {done}/{len(main.todos.items)} done"
380
+ if cur:
381
+ text += f" · ▸ {one_line(cur.active_form or cur.content, w - 30)}"
382
+ out.append(("class:dim", text + " (ctrl+t)\n"))
383
+ for q in self.queued:
384
+ out.append(("class:queued", f" ↳ queued: {one_line(q, w - 14)}\n"))
385
+ if self.busy:
386
+ spin = SPINNER[int(now * 8) % len(SPINNER)]
387
+ text = self._phase_text(mv, now) if mv and mv.phase != "idle" else (
388
+ "Working" if self.task_label == "turn" else f"Running {self.task_label}")
389
+ out += [("class:spinner", f"{spin} "), ("class:status", one_line(text, w - 30)),
390
+ ("class:dim", f" ({fmt_duration(now - self.task_started)} · esc to interrupt)\n")]
391
+ return out
392
+
393
+ def _message(self):
394
+ w = term_width() - 1
395
+ frags: list[tuple[str, str]] = []
396
+ if self.rt is not None and (self.busy or self.running or self.dialog or self.queued or self.show_todos):
397
+ frags.extend(self._live(w))
398
+ d = self.dialog
399
+ if d is not None:
400
+ frags.append(("class:dialog.title", "\n" + d.title + "\n"))
401
+ if d.typing:
402
+ frags.append(("class:faint", f" {d.text_label or 'Type your answer'} · Enter to send · Esc to go back\n"))
403
+ else:
404
+ for i, opt in enumerate(d.options):
405
+ sel = i == d.index
406
+ frags.append(("class:dialog.sel" if sel else "class:dialog.opt",
407
+ f"{'❯' if sel else ' '} {i + 1}. {one_line(opt, w - 6)}\n"))
408
+ frags.append(("class:faint", " ↑/↓ and Enter, or press a number · Esc to cancel\n"))
409
+ frags.append(("class:prompt", " ↳ " if d is not None and d.typing else "> "))
410
+ return frags
411
+
412
+ def _placeholder(self):
413
+ if self.dialog is not None:
414
+ return [("class:placeholder", "Type here…")] if self.dialog.typing else ""
415
+ if time.monotonic() - self._last_ctrl_c < 2:
416
+ return [("class:warn", "Press Ctrl+C again to exit")]
417
+ if self.busy:
418
+ return [("class:placeholder", "Type to queue a message (delivered at the agent's next step)")]
419
+ return [("class:placeholder", 'Ask rigcode… ("/" commands · "@" files · "!" shell · "#" memory)')]
420
+
421
+ def _ctx_tokens(self) -> int:
422
+ at, val = self._ctx_cache
423
+ if time.monotonic() - at > 0.5 and self.rt and self.rt.main_agent:
424
+ val = self.rt.main_agent.context_tokens()
425
+ self._ctx_cache = (time.monotonic(), val)
426
+ return val
427
+
428
+ def _toolbar(self):
429
+ rt = self.rt
430
+ if rt is None:
431
+ return ""
432
+ w = term_width() - 1
433
+ mode = rt.permissions.mode
434
+ if mode == "plan":
435
+ left = [("class:mode.plan", "⏸ plan mode on"), ("class:hint", " (shift+tab to cycle)")]
436
+ elif mode == "acceptEdits":
437
+ left = [("class:mode.accept", "⏵⏵ accept edits on"), ("class:hint", " (shift+tab to cycle)")]
438
+ elif mode == "bypass":
439
+ left = [("class:mode.bypass", "⚠ bypass permissions on")]
440
+ else:
441
+ left = [("class:hint", "/help · shift+tab: mode")]
442
+ parts = [rt.client.model, f"effort {rt.effort or 'default'}"]
443
+ ctx = self._ctx_tokens()
444
+ if ctx:
445
+ parts.append(f"ctx {fmt_tokens(ctx)}/{fmt_tokens(rt.context_window)}")
446
+ lu = rt.last_usage
447
+ if lu and lu.prompt_tokens:
448
+ parts.append(f"cache {100 * lu.cached_tokens // max(1, lu.prompt_tokens)}%")
449
+ ws = self.warmup.get("state")
450
+ if ws == "running":
451
+ parts.append(f"warming cache{self._warmup_pct()}")
452
+ right = " · ".join(parts)
453
+ used = sum(get_cwidth(t) for _, t in left) + get_cwidth(right)
454
+ return left + [("", " " * max(1, w - used)), ("class:hint", right)]
455
+
456
+ def _on_text_changed(self, buf) -> None:
457
+ text = buf.document.text_before_cursor
458
+ completing = (text.startswith("/") and " " not in text) or bool(re.search(r"(?:^|\s)@[^\s@]*$", text))
459
+ self.session.reserve_space_for_menu = 8 if completing else 0
460
+
461
+ def _ensure_ticker(self) -> None:
462
+ if self._ticker is None or self._ticker.done():
463
+ self._ticker = asyncio.create_task(self._tick())
464
+
465
+ async def _tick(self) -> None:
466
+ while self.busy or self.running or self.warmup.get("state") == "running":
467
+ self._invalidate()
468
+ await asyncio.sleep(0.125)
469
+ self._invalidate()
470
+
471
+ # ================================================================== key bindings
472
+ def _bindings(self) -> KeyBindings:
473
+ kb = KeyBindings()
474
+ selecting = Condition(lambda: self.dialog is not None and not self.dialog.typing)
475
+ typing = Condition(lambda: self.dialog is not None and self.dialog.typing)
476
+ no_dialog = Condition(lambda: self.dialog is None)
477
+ busy = Condition(lambda: self.busy)
478
+
479
+ @kb.add("up", filter=selecting, eager=True)
480
+ def _(e):
481
+ self.dialog.index = (self.dialog.index - 1) % max(1, len(self.dialog.options))
482
+
483
+ @kb.add("down", filter=selecting, eager=True)
484
+ def _(e):
485
+ self.dialog.index = (self.dialog.index + 1) % max(1, len(self.dialog.options))
486
+
487
+ @kb.add("enter", filter=selecting, eager=True)
488
+ def _(e):
489
+ self._choose(self.dialog.index)
490
+
491
+ for i in range(1, 10):
492
+ @kb.add(str(i), filter=selecting, eager=True)
493
+ def _(e, i=i):
494
+ if i <= len(self.dialog.options):
495
+ self._choose(i - 1)
496
+
497
+ @kb.add("escape", filter=selecting, eager=True)
498
+ def _(e):
499
+ self._resolve(None, "")
500
+
501
+ @kb.add(Keys.Any, filter=selecting)
502
+ def _(e):
503
+ pass # swallow typing while a choice is shown
504
+
505
+ @kb.add("enter", filter=typing, eager=True)
506
+ def _(e):
507
+ text = e.current_buffer.text
508
+ e.current_buffer.reset()
509
+ self._resolve(self.dialog.text_option, text)
510
+
511
+ @kb.add("escape", filter=typing, eager=True)
512
+ def _(e):
513
+ e.current_buffer.reset()
514
+ if self.dialog.options:
515
+ self.dialog.typing = False
516
+ else:
517
+ self._resolve(None, "")
518
+
519
+ @kb.add("c-c", eager=True)
520
+ def _(e):
521
+ if self.dialog is not None:
522
+ self._resolve(None, "")
523
+ return
524
+ if self.busy:
525
+ self.interrupt()
526
+ return
527
+ buf = e.current_buffer
528
+ if buf.text:
529
+ buf.reset()
530
+ return
531
+ now = time.monotonic()
532
+ if now - self._last_ctrl_c < 2.0:
533
+ e.app.exit(exception=EOFError())
534
+ return
535
+ self._last_ctrl_c = now
536
+
537
+ async def clear_hint():
538
+ await asyncio.sleep(2.1)
539
+ self._invalidate()
540
+ asyncio.get_running_loop().create_task(clear_hint())
541
+
542
+ @kb.add("escape", filter=busy & no_dialog)
543
+ def _(e):
544
+ self.interrupt()
545
+
546
+ @kb.add("s-tab", filter=~has_completions & no_dialog)
547
+ def _(e):
548
+ if self.rt is not None:
549
+ self.rt.cycle_mode()
550
+
551
+ @kb.add("escape", "enter", filter=no_dialog | typing)
552
+ def _(e):
553
+ e.current_buffer.insert_text("\n")
554
+
555
+ @kb.add("c-j", filter=no_dialog | typing)
556
+ def _(e):
557
+ e.current_buffer.insert_text("\n")
558
+
559
+ @kb.add("enter", filter=no_dialog & Condition(
560
+ lambda: self.session.default_buffer.document.text_before_cursor.endswith("\\")))
561
+ def _(e):
562
+ e.current_buffer.delete_before_cursor(1)
563
+ e.current_buffer.insert_text("\n")
564
+
565
+ @kb.add("c-o")
566
+ def _(e):
567
+ self.thinking_mode = "full" if self.thinking_mode != "full" else "collapsed"
568
+ self.out_line(f" ⎿ Thinking display: {self.thinking_mode}", "class:dim")
569
+
570
+ @kb.add("c-t")
571
+ def _(e):
572
+ self.show_todos = not self.show_todos
573
+
574
+ return kb
575
+
576
+ # ================================================================== dialogs
577
+ def _choose(self, index: int) -> None:
578
+ d = self.dialog
579
+ if d is None:
580
+ return
581
+ if d.text_option is not None and index == d.text_option:
582
+ d.index = index
583
+ d.typing = True
584
+ return
585
+ self._resolve(index, "")
586
+
587
+ def _resolve(self, index: int | None, text: str) -> None:
588
+ d = self.dialog
589
+ if d is not None and not d.future.done():
590
+ d.future.set_result((index, text))
591
+
592
+ async def dialog_choice(self, title: str, options: list[str], *, text_option: int | None = None,
593
+ text_label: str = "", start_typing: bool = False) -> tuple[int | None, str]:
594
+ while self.dialog is not None: # one question at a time (parallel subagents)
595
+ await asyncio.sleep(0.1)
596
+ fut = asyncio.get_running_loop().create_future()
597
+ buf = self.session.default_buffer
598
+ self._stash = buf.document if buf.text else None
599
+ buf.reset()
600
+ self.dialog = Dialog(title, options, fut, text_option=text_option, typing=start_typing,
601
+ text_label=text_label)
602
+ self._bell()
603
+ self._invalidate()
604
+ try:
605
+ return await fut
606
+ finally:
607
+ self.dialog = None
608
+ if self._stash is not None:
609
+ buf.document = self._stash
610
+ self._stash = None
611
+ self._invalidate()
612
+
613
+ async def choose(self, title: str, options: list[str]) -> int | None:
614
+ idx, _ = await self.dialog_choice(title, options)
615
+ return idx
616
+
617
+ async def ask_text(self, title: str, label: str = "") -> str | None:
618
+ idx, text = await self.dialog_choice(title, [], text_option=0, text_label=label, start_typing=True)
619
+ return None if idx is None else text
620
+
621
+ async def request_permission(self, req, agent):
622
+ titles = {"exec": "Bash command", "edit": "Edit file", "web": "Web access", "mcp": "MCP tool",
623
+ "agent": "Subagent"}
624
+ title = titles.get(req.kind, req.tool_name)
625
+ if req.kind == "edit" and req.preview and req.preview.get("type") == "new_file":
626
+ title = "Create file"
627
+ who = "" if getattr(agent, "is_main", True) else f" (requested by the {agent.name} subagent)"
628
+ frags = [("", "\n"), ("class:dialog.title", f"● {title}"), ("class:dim", who + "\n")]
629
+ target = req.target or req.label
630
+ for line in target.split("\n")[:20]:
631
+ frags.append(("", f" {line}\n"))
632
+ if req.reason:
633
+ frags.append(("class:dim", f" {req.reason}\n"))
634
+ if req.danger:
635
+ frags.append(("class:error", f" ⚠ {req.danger}\n"))
636
+ self.out(frags)
637
+ pv = req.preview
638
+ if pv and pv.get("type") == "diff" and pv.get("diff"):
639
+ self.out_ansi(self.r.ansi(self.r.diff(pv["diff"], max_lines=30, indent=2)))
640
+ elif pv and pv.get("type") == "new_file":
641
+ self.out_ansi(self.r.ansi(self.r.new_file(pv.get("content", ""), max_lines=15, indent=2)))
642
+ options = ["Yes"]
643
+ if req.kind == "edit":
644
+ options.append("Yes, allow all edits during this session (shift+tab)")
645
+ elif req.rule_suggestion:
646
+ options.append(f"Yes, and don't ask again for {req.rule_suggestion} in this project")
647
+ options.append("No, and tell rigcode what to do differently")
648
+ idx, text = await self.dialog_choice(f"Allow this {title.lower()}?", options, text_option=len(options) - 1,
649
+ text_label="What should rigcode do instead? (empty = just stop)")
650
+ if idx is None:
651
+ return Decision(allow=False, stop=True)
652
+ if idx == 0:
653
+ return Decision(allow=True)
654
+ if idx == len(options) - 1:
655
+ fb = text.strip()
656
+ return Decision(allow=False, feedback=fb or None, stop=not fb)
657
+ if req.kind == "edit":
658
+ return Decision(allow=True, session_mode="acceptEdits")
659
+ return Decision(allow=True, remember_rule=req.rule_suggestion)
660
+
661
+ async def ask_user(self, question: str, options: list[str]) -> str | None:
662
+ self.out([("", "\n"), ("class:dialog.title", "? "), ("class:tool.label", question + "\n")])
663
+ if options:
664
+ opts = list(options) + ["Type something else"]
665
+ idx, text = await self.dialog_choice("Your answer:", opts, text_option=len(opts) - 1)
666
+ if idx is None:
667
+ answer = "(the user dismissed the question without answering)"
668
+ else:
669
+ answer = text.strip() if idx == len(opts) - 1 else opts[idx]
670
+ else:
671
+ idx, text = await self.dialog_choice("Your answer:", [], text_option=0, start_typing=True)
672
+ answer = "(the user dismissed the question without answering)" if idx is None else text.strip()
673
+ self.out_line(f" ⎿ {answer}", "class:dim")
674
+ return answer
675
+
676
+ async def review_plan(self, plan: str):
677
+ self.out([("", "\n"), ("class:dialog.title", "● Plan ready for review\n")])
678
+ self.out_markdown(plan)
679
+ opts = ["Yes, and auto-accept edits", "Yes, and manually approve edits", "No, keep planning"]
680
+ idx, text = await self.dialog_choice("Would you like to proceed?", opts, text_option=2,
681
+ text_label="What should change in the plan?")
682
+ if idx is None:
683
+ return (False, None, None)
684
+ if idx == 0:
685
+ return (True, "acceptEdits", None)
686
+ if idx == 1:
687
+ return (True, "default", None)
688
+ return (False, None, text.strip() or None)
689
+
690
+ def take_queued_input(self) -> str | None:
691
+ if not self.queued:
692
+ return None
693
+ text = "\n\n".join(self.queued)
694
+ self.queued.clear()
695
+ self._echo_user(text)
696
+ expanded, notes = expand_mentions(text, self.rt)
697
+ for n in notes:
698
+ self.out_line(f" ⎿ {n}", "class:dim")
699
+ return expanded
700
+
701
+ # ================================================================== engine events
702
+ def _view(self, agent) -> AgentView:
703
+ v = self.views.get(id(agent))
704
+ if v is None:
705
+ v = AgentView(agent, getattr(agent, "name", "agent"))
706
+ self.views[id(agent)] = v
707
+ return v
708
+
709
+ def on_notice(self, level: str, text: str) -> None:
710
+ if level == "info":
711
+ self.out_line(f" ⎿ {text}", "class:dim")
712
+ elif level == "warn":
713
+ self.out([("", "\n"), ("class:warn", f"⚠ {text}\n")])
714
+ else:
715
+ self.out([("", "\n"), ("class:error", f"✗ {text}\n")])
716
+
717
+ def on_model_start(self, agent, info: dict) -> None:
718
+ v = self._view(agent)
719
+ v.phase, v.req_started, v.gen_started, v.progress = "waiting", time.monotonic(), None, None
720
+ v.think_started, v.thought_printed, v.think_tokens, v.out_tokens = None, False, 0, 0
721
+ v.reasoning_tail, v.tool_name, v.tool_args_chars, v.first_block = "", None, 0, True
722
+ if getattr(agent, "is_main", False):
723
+ self.splitter = BlockSplitter()
724
+ self.think_splitter = BlockSplitter()
725
+ self._ensure_ticker()
726
+
727
+ def on_delta(self, agent, d) -> None:
728
+ v = self._view(agent)
729
+ is_main = getattr(agent, "is_main", False)
730
+ k = d.kind
731
+ if k == "progress":
732
+ v.phase, v.progress = "prompt", d.data
733
+ elif k == "reasoning":
734
+ now = time.monotonic()
735
+ if v.think_started is None:
736
+ v.think_started = now
737
+ if v.gen_started is None:
738
+ v.gen_started = now
739
+ v.phase = "thinking"
740
+ v.think_tokens += 1
741
+ v.reasoning_tail = (v.reasoning_tail + d.text)[-800:]
742
+ if is_main and self.thinking_mode == "full":
743
+ for block in self.think_splitter.feed(d.text):
744
+ self.out_markdown(block, style="italic color(244)")
745
+ elif k == "content":
746
+ if v.gen_started is None:
747
+ v.gen_started = time.monotonic()
748
+ if is_main:
749
+ self._end_thinking(v)
750
+ for block in self.splitter.feed(d.text):
751
+ self._print_block(v, block)
752
+ v.phase = "writing"
753
+ v.out_tokens += 1
754
+ elif k == "tool_start":
755
+ if is_main:
756
+ self._end_thinking(v)
757
+ self._flush_text(v)
758
+ v.phase, v.tool_name, v.tool_args_chars = "calling", d.name, 0
759
+ elif k == "tool_args":
760
+ v.tool_args_chars += len(d.text)
761
+ elif k == "reset":
762
+ self.on_notice("warn", d.text)
763
+ v.phase, v.think_started, v.thought_printed, v.gen_started = "waiting", None, False, None
764
+ v.think_tokens = v.out_tokens = 0
765
+ if is_main:
766
+ if self.splitter.pending.strip():
767
+ self.out_line(" ⎿ (partial reply discarded; retrying)", "class:dim")
768
+ self.splitter = BlockSplitter()
769
+ self.think_splitter = BlockSplitter()
770
+
771
+ def _print_block(self, v: AgentView, block: str) -> None:
772
+ self.out_markdown(block, bullet="● " if v.first_block else None)
773
+ v.first_block = False
774
+
775
+ def _flush_text(self, v: AgentView) -> None:
776
+ rest = self.splitter.flush()
777
+ if rest.strip():
778
+ self._print_block(v, rest)
779
+
780
+ def _end_thinking(self, v: AgentView) -> None:
781
+ if v.think_started is None or v.thought_printed:
782
+ return
783
+ v.thought_printed = True
784
+ if self.thinking_mode == "hidden":
785
+ return
786
+ if self.thinking_mode == "full":
787
+ rest = self.think_splitter.flush()
788
+ if rest.strip():
789
+ self.out_markdown(rest, style="italic color(244)")
790
+ secs = time.monotonic() - v.think_started
791
+ self.out([("", "\n"), ("class:thinking", f"✻ Thought for {fmt_duration(secs)} ({v.think_tokens} tokens)"),
792
+ ("class:faint", " ctrl+o to show thinking\n" if self.thinking_mode == "collapsed" else "\n")])
793
+
794
+ def on_model_end(self, agent, turn) -> None:
795
+ v = self._view(agent)
796
+ if getattr(agent, "is_main", False):
797
+ self._end_thinking(v)
798
+ self._flush_text(v)
799
+ v.phase = "tools" if turn is not None and turn.tool_calls else "idle"
800
+
801
+ def on_usage(self, agent, usage) -> None:
802
+ self._ctx_cache = (0.0, self._ctx_cache[1])
803
+
804
+ def on_tool_start(self, agent, prepared, args: dict) -> None:
805
+ self.running[prepared.call.id] = ToolView(agent, prepared.label, time.monotonic())
806
+ v = self._view(agent)
807
+ v.phase = "tools"
808
+ v.tool_calls += 1
809
+ if not getattr(agent, "is_main", False):
810
+ v.recent_tools.append(prepared.label)
811
+ del v.recent_tools[:-3]
812
+ self._ensure_ticker()
813
+
814
+ def on_tool_output(self, agent, call_id: str, text: str) -> None:
815
+ tv = self.running.get(call_id)
816
+ if tv is not None:
817
+ tv.output = (tv.output + text)[-4000:]
818
+
819
+ def on_tool_end(self, agent, prepared, result) -> None:
820
+ self.running.pop(prepared.call.id, None)
821
+ if getattr(agent, "is_main", False):
822
+ self.print_tool(prepared.label, result)
823
+
824
+ def print_tool(self, label: str, res: ToolResult, output_lines: int | None = None) -> None:
825
+ w = term_width() - 1
826
+ bullet = "class:tool.bullet.err" if res.is_error else "class:tool.bullet"
827
+ summary = res.summary or one_line(res.content, 160)
828
+ frags = [("", "\n"), (bullet, "● "), ("class:tool.label", one_line(label, w - 4) + "\n"),
829
+ ("class:dim", " ⎿ "), ("class:error" if res.is_error else "class:dim", one_line(summary, w - 8) + "\n")]
830
+ if res.is_error:
831
+ detail = [l for l in res.content.strip().split("\n") if l.strip()]
832
+ if len(detail) > 1 or (detail and one_line(detail[0], 300) != one_line(summary, 300)):
833
+ for line in detail[:6]:
834
+ frags.append(("class:faint", " " + one_line(line, w - 6) + "\n"))
835
+ if len(detail) > 6:
836
+ frags.append(("class:faint", f" … {len(detail) - 6} more lines\n"))
837
+ self.out(frags)
838
+ disp = res.display
839
+ if not disp or res.is_error:
840
+ return
841
+ t = disp.get("type")
842
+ if t == "diff" and disp.get("diff"):
843
+ self.out_ansi(self.r.ansi(self.r.diff(disp["diff"])))
844
+ elif t == "new_file":
845
+ self.out_ansi(self.r.ansi(self.r.new_file(disp.get("content", ""))))
846
+ elif t == "todos":
847
+ self.out_ansi(self.r.ansi(render_todos(disp.get("items") or [])))
848
+ elif t == "output" and disp.get("text", "").strip():
849
+ n = output_lines or self.tool_output_lines
850
+ lines = [l for l in strip_ansi(disp["text"]).replace("\r", "").split("\n")]
851
+ while lines and not lines[-1].strip():
852
+ lines.pop()
853
+ shown = lines[-n:]
854
+ body = [("class:faint", f" … {len(lines) - n} earlier lines\n")] if len(lines) > n else []
855
+ body += [("class:dim", " " + one_line(l, w - 6) + "\n") for l in shown]
856
+ self.out(body)
857
+ elif t == "markdown" and disp.get("text", "").strip():
858
+ rendered = self.r.markdown(disp["text"], width=w - 6, style="color(246)").strip("\n").split("\n")
859
+ more = len(rendered) - 10
860
+ text = "\n".join(" " + l for l in rendered[:10])
861
+ if more > 0:
862
+ text += f"\n \x1b[38;5;242m… {more} more lines\x1b[0m"
863
+ self.out_ansi(text)
864
+
865
+ def on_compact_start(self, agent, before: int, reason: str) -> None:
866
+ v = self._view(agent)
867
+ v.phase, v.out_tokens, v.req_started = "compacting", 0, time.monotonic()
868
+ if getattr(agent, "is_main", False):
869
+ why = {"auto": "The context is getting large", "overflow": "The prompt overflowed the context window"}
870
+ self.out([("", "\n"), ("class:dim", f"✻ {why.get(reason, 'Compacting')}: summarizing "
871
+ f"{fmt_tokens(before)} tokens of conversation…\n")])
872
+ self._ensure_ticker()
873
+
874
+ def on_compact_delta(self, agent, d) -> None:
875
+ v = self._view(agent)
876
+ if d.kind == "progress":
877
+ v.progress = d.data
878
+ elif d.kind in ("content", "reasoning"):
879
+ v.out_tokens += 1
880
+
881
+ def on_compact_end(self, agent, before: int, after: int, summary: str | None) -> None:
882
+ v = self._view(agent)
883
+ v.phase = "idle"
884
+ if summary and getattr(agent, "is_main", False):
885
+ self.out_line(f" ⎿ Conversation compacted: {fmt_tokens(before)} → {fmt_tokens(after)} tokens", "class:dim")
886
+
887
+ def on_subagent_start(self, agent, description: str) -> None:
888
+ v = self._view(agent)
889
+ v.description = description
890
+ v.started = time.monotonic()
891
+
892
+ def on_subagent_end(self, agent, stats) -> None:
893
+ self.views.pop(id(agent), None)
894
+
895
+ def on_warmup(self, state: str, data: dict | None = None) -> None:
896
+ if state == "progress":
897
+ self.warmup.update(data or {})
898
+ self.warmup["state"] = "running"
899
+ return
900
+ self.warmup = {"state": state, **(data or {})}
901
+ if state == "start":
902
+ self._ensure_ticker()
903
+ elif state == "done":
904
+ secs = (data or {}).get("seconds") or 0
905
+ self.out_line(f" ⎿ Prompt cache ready ({fmt_tokens((data or {}).get('prompt_tokens'))} tokens "
906
+ f"in {fmt_duration(secs)})", "class:faint")
907
+ elif state == "failed":
908
+ self.out_line(f" ⎿ Cache warm-up failed: {(data or {}).get('error', '?')}", "class:faint")
909
+
910
+ # ================================================================== input handling
911
+ def _echo_user(self, text: str) -> None:
912
+ w = term_width() - 1
913
+ lines = wrap_lines(text.rstrip("\n"), w - 3)
914
+ frags: list[tuple[str, str]] = [("", "\n")]
915
+ for i, line in enumerate(lines[:40]):
916
+ pad = " " * max(0, w - 2 - get_cwidth(line))
917
+ frags.append(("class:user.prefix", "> " if i == 0 else " "))
918
+ frags.append(("class:user", line + pad + "\n"))
919
+ if len(lines) > 40:
920
+ frags.append(("class:faint", f" … {len(lines) - 40} more lines\n"))
921
+ self.out(frags)
922
+
923
+ def dispatch(self, text: str) -> None:
924
+ if not text.strip():
925
+ return
926
+ stripped = text.strip()
927
+ if stripped.startswith("/") and not stripped.startswith("//"):
928
+ name, _, args = stripped[1:].partition(" ")
929
+ cmd = self.commands.find(name)
930
+ custom = None if cmd else (self.rt.commands.get(name) if self.rt else None)
931
+ if cmd is None and custom is None:
932
+ if "/" in name or "." in name: # looks like a path: treat as a normal message
933
+ self._send(text)
934
+ else:
935
+ self.out_line(f"Unknown command /{name}. Type /help for the list.", "class:warn")
936
+ return
937
+ if self.busy and (custom is not None or not cmd.busy_ok):
938
+ self.out_line(f"/{name} can't run while the agent is working. Wait, or press Esc to interrupt.",
939
+ "class:warn")
940
+ return
941
+ self._echo_user(stripped)
942
+ if custom is not None:
943
+ self._start_task(self._custom_command(custom, args.strip()), f"/{name}")
944
+ elif cmd.busy_ok and self.busy:
945
+ asyncio.get_running_loop().create_task(self._run_command(cmd, args.strip()))
946
+ else:
947
+ self._start_task(self._run_command(cmd, args.strip()), f"/{name}")
948
+ return
949
+ if stripped.startswith("!"):
950
+ if self.busy:
951
+ self.out_line("Shell commands can't run while the agent is working.", "class:warn")
952
+ return
953
+ self._echo_user(stripped)
954
+ self._start_task(self._bash(stripped[1:].strip()), "shell command")
955
+ return
956
+ if stripped.startswith("#") and not stripped.startswith("##") and len(stripped) > 1 and "\n" not in stripped:
957
+ self._echo_user(stripped)
958
+ self._memory_add(stripped[1:].strip())
959
+ return
960
+ self._send(text)
961
+
962
+ def _send(self, text: str) -> None:
963
+ if self.busy:
964
+ self.queued.append(text.strip("\n"))
965
+ self._invalidate()
966
+ return
967
+ self.start_turn(text)
968
+
969
+ def submit_message(self, text: str) -> None:
970
+ """Send a message as if typed (queued if a task is running, e.g. from inside a command)."""
971
+ self._send(text)
972
+
973
+ def start_turn(self, text: str, echo: bool = True) -> None:
974
+ if echo:
975
+ self._echo_user(text)
976
+ self._start_task(self._turn(text), "turn")
977
+
978
+ async def _turn(self, text: str) -> None:
979
+ await self.run_turn(text)
980
+
981
+ async def run_turn(self, text: str):
982
+ """Run one main-agent turn (inside the current task) and print its footer."""
983
+ expanded, notes = expand_mentions(text, self.rt)
984
+ for n in notes:
985
+ self.out_line(f" ⎿ {n}", "class:dim")
986
+ stats = await self.rt.submit(expanded)
987
+ self._footer(stats)
988
+ return stats
989
+
990
+ def _footer(self, stats) -> None:
991
+ rt = self.rt
992
+ if stats.stopped_reason == "interrupted":
993
+ self.out_line(" ⎿ Interrupted · tell rigcode what to do instead", "class:warn")
994
+ return
995
+ parts = [fmt_duration(stats.elapsed)]
996
+ if stats.tool_calls:
997
+ parts.append(f"{stats.tool_calls} tool call{'s' if stats.tool_calls != 1 else ''}")
998
+ u = stats.usage
999
+ if u.completion_tokens:
1000
+ parts.append(f"{fmt_tokens(u.completion_tokens)} tokens out")
1001
+ if u.gen_tps:
1002
+ parts.append(f"{u.gen_tps:.1f} tok/s")
1003
+ ctx = rt.main_agent.context_tokens()
1004
+ parts.append(f"context {fmt_tokens(ctx)} ({100 * ctx // max(1, rt.context_window)}%)")
1005
+ if u.prompt_tokens:
1006
+ parts.append(f"cache hit {100 * u.cached_tokens // max(1, u.prompt_tokens)}%")
1007
+ if stats.stopped_reason not in ("done", "denied"):
1008
+ parts.append(f"stopped: {stats.stopped_reason}")
1009
+ self.out_line(" " + " · ".join(parts), "class:faint")
1010
+
1011
+ def _start_task(self, coro, label: str) -> None:
1012
+ self.task_label = label
1013
+ self.task_started = time.monotonic()
1014
+ self.task = asyncio.get_running_loop().create_task(self._task_wrapper(coro))
1015
+ self._ensure_ticker()
1016
+
1017
+ async def _task_wrapper(self, coro) -> None:
1018
+ try:
1019
+ await coro
1020
+ except asyncio.CancelledError:
1021
+ self.out_line(" ⎿ Interrupted", "class:warn")
1022
+ except Exception as e: # noqa: BLE001
1023
+ self.on_notice("error", f"{type(e).__name__}: {e}")
1024
+ if self.rt and self.rt.debug:
1025
+ self.out_line(traceback.format_exc(), "class:faint")
1026
+ finally:
1027
+ elapsed = time.monotonic() - self.task_started
1028
+ self.task = None
1029
+ self.running.clear()
1030
+ for key in [k for k, v in self.views.items() if getattr(v.agent, "depth", 0) > 0]:
1031
+ self.views.pop(key, None)
1032
+ if elapsed > 20:
1033
+ self._bell()
1034
+ if self.queued and not self.exit_requested:
1035
+ text = "\n\n".join(self.queued)
1036
+ self.queued.clear()
1037
+ self.start_turn(text)
1038
+ self._invalidate()
1039
+
1040
+ def interrupt(self) -> None:
1041
+ if self.busy:
1042
+ self.task.cancel()
1043
+
1044
+ def begin_activity(self, key: str, label: str) -> None:
1045
+ """Show a long-running non-tool activity (e.g. /review's subagent) in the live area."""
1046
+ self.running[key] = ToolView(self.rt.main_agent, label, time.monotonic())
1047
+ self._ensure_ticker()
1048
+
1049
+ def end_activity(self, key: str) -> None:
1050
+ self.running.pop(key, None)
1051
+
1052
+ async def _run_command(self, cmd, args: str) -> None:
1053
+ await cmd.run(self, self.rt, args)
1054
+
1055
+ async def _custom_command(self, cmd, args: str) -> None:
1056
+ from rigcode.tools.shell import build_invocation
1057
+ rt = self.rt
1058
+ prompt = cmd.render(args, rt.cwd, lambda c: build_invocation(rt.shell, c, rt.cwd, track_cwd=False))
1059
+ await self.run_turn(prompt)
1060
+
1061
+ async def _bash(self, command: str) -> None:
1062
+ if not command:
1063
+ return
1064
+ rt = self.rt
1065
+ tool = rt.tools.get("Bash")
1066
+ if tool is None:
1067
+ self.out_line("The Bash tool is disabled.", "class:warn")
1068
+ return
1069
+ ctx = ToolContext(rt, rt.main_agent, "user-shell")
1070
+ self.running["user-shell"] = ToolView(rt.main_agent, f"! {command}", time.monotonic())
1071
+ try:
1072
+ res = await tool.run({"command": command, "timeout": 600}, ctx)
1073
+ finally:
1074
+ self.running.pop("user-shell", None)
1075
+ self.print_tool(f"! {command}", res, output_lines=40)
1076
+ body = res.content if len(res.content) < 6000 else res.content[:3000] + "\n[...]\n" + res.content[-2000:]
1077
+ rt.main_agent.add_reminder(f"The user ran this shell command themselves (cwd {rt.cwd}):\n$ {command}\n{body}")
1078
+
1079
+ def _memory_add(self, text: str) -> None:
1080
+ root = self.rt.project_root
1081
+ target = next((root / n for n in ("AGENTS.md", "CLAUDE.md", "RIGCODE.md") if (root / n).exists()),
1082
+ root / "AGENTS.md")
1083
+ try:
1084
+ existing = target.read_text(encoding="utf-8") if target.exists() else ""
1085
+ with open(target, "a", encoding="utf-8", newline="\n") as fh:
1086
+ if existing and not existing.endswith("\n"):
1087
+ fh.write("\n")
1088
+ fh.write(f"- {text}\n")
1089
+ except OSError as e:
1090
+ self.out_line(f"Could not write {target}: {e}", "class:error")
1091
+ return
1092
+ self.rt.main_agent.add_reminder(f"The user added this to the project memory file {target.name}: {text}")
1093
+ self.out_line(f" ⎿ Added to {target.name} (the agent sees it from the next message)", "class:dim")
1094
+
1095
+ # ================================================================== main loop
1096
+ def welcome(self) -> None:
1097
+ rt = self.rt
1098
+ s = rt.server
1099
+ where = rt.client.base_url.replace("http://", "").replace("https://", "")
1100
+ server = s.describe() if s.reachable else "server unreachable"
1101
+ lines = [("class:banner", f"✻ rigcode {__version__}"), ("", f" {rt.client.model} @ {where}"),
1102
+ ("class:dim", f" ({server})\n")]
1103
+ info = [f"cwd {rt.cwd}", f"mode {rt.permissions.mode}", f"effort {rt.effort or 'default'}"]
1104
+ if rt.memory:
1105
+ info.append(f"{len(rt.memory)} memory file{'s' if len(rt.memory) != 1 else ''}")
1106
+ n_mcp = sum(1 for x in rt.mcp.servers.values() if x.status == "connected")
1107
+ if n_mcp:
1108
+ info.append(f"{n_mcp} MCP server{'s' if n_mcp != 1 else ''}")
1109
+ lines.append(("class:dim", " " + " · ".join(info) + "\n"))
1110
+ lines.append(("class:faint", " /help for commands · esc to interrupt · shift+tab to change mode\n"))
1111
+ self.out(lines)
1112
+ history = len(rt.main_agent.messages) - rt.main_agent.n_prefix()
1113
+ if history:
1114
+ how = "re-reading them in the background" if rt.warmup_state == "running" else "the first reply re-reads them"
1115
+ self.out_line(f" ⎿ Resumed session {rt.session.id} ({history} messages, "
1116
+ f"~{fmt_tokens(rt.main_agent.context_tokens())} tokens; {how})", "class:dim")
1117
+ reply = rt.main_agent.last_assistant_text()
1118
+ if reply:
1119
+ self.out_markdown(reply[-2000:], bullet="● ")
1120
+
1121
+ async def run(self, rt, initial: str | None = None) -> None:
1122
+ self.rt = rt
1123
+ self.welcome()
1124
+ if initial:
1125
+ self.dispatch(initial)
1126
+ while not self.exit_requested:
1127
+ try:
1128
+ text = await self.session.prompt_async()
1129
+ except EOFError:
1130
+ break
1131
+ except KeyboardInterrupt:
1132
+ continue
1133
+ self.dispatch(text)
1134
+ await self.shutdown()
1135
+
1136
+ def request_exit(self) -> None:
1137
+ self.exit_requested = True
1138
+ app = self.session.app
1139
+ if app.is_running:
1140
+ app.exit(exception=EOFError())
1141
+
1142
+ async def shutdown(self) -> None:
1143
+ self.exit_requested = True
1144
+ if self.busy:
1145
+ self.task.cancel()
1146
+ try:
1147
+ await asyncio.wait_for(asyncio.shield(self.task), 5)
1148
+ except (asyncio.CancelledError, asyncio.TimeoutError, Exception): # noqa: BLE001
1149
+ pass
1150
+ if self._ticker and not self._ticker.done():
1151
+ self._ticker.cancel()
1152
+ rt = self.rt
1153
+ if rt is not None and rt.session.path.exists():
1154
+ self.out_line(f"\nResume this session with: rigcode -r {rt.session.id}", "class:faint")