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/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """rigcode: a terminal coding agent harness for self-hosted models."""
2
+
3
+ __version__ = "0.1.0"
4
+ APP_NAME = "rigcode"
rigcode/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from rigcode.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
File without changes
rigcode/agent/loop.py ADDED
@@ -0,0 +1,627 @@
1
+ """The agent loop: call the model, run the requested tools, repeat until done."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import json
6
+ import re
7
+ import time
8
+ import traceback
9
+ import uuid
10
+ from dataclasses import dataclass, field
11
+
12
+ from rigcode.agent.prompts import compact_instruction, post_compact_message, reminder
13
+ from rigcode.agent.state import TodoState
14
+ from rigcode.hooks import HookOutcome
15
+ from rigcode.llm.stream import ChunkAssembler
16
+ from rigcode.llm.textmode import has_text_tool_markup, parse_text_tool_calls
17
+ from rigcode.llm.types import AssistantTurn, LLMError, ToolCall, Usage
18
+ from rigcode.llm.wire import to_wire
19
+ from rigcode.tools.base import Tool, ToolContext, ToolResult, validate_args
20
+ from rigcode.utils.jsonrepair import loads_lenient
21
+ from rigcode.utils.paths import display_path
22
+ from rigcode.utils.text import est_tokens, one_line
23
+
24
+ REPEAT_WARN_AT = (3, 5, 8)
25
+ REPEAT_ABORT_AT = 12
26
+ _REMINDER_RE = re.compile(r"<system-reminder>.*?</system-reminder>\s*", re.S)
27
+
28
+
29
+ @dataclass
30
+ class TurnStats:
31
+ steps: int = 0
32
+ tool_calls: int = 0
33
+ usage: Usage = field(default_factory=Usage)
34
+ elapsed: float = 0.0
35
+ stopped_reason: str = "done" # done | interrupted | error | max_steps | denied | hook | loop
36
+
37
+
38
+ @dataclass
39
+ class PreparedCall:
40
+ call: ToolCall
41
+ tool: Tool | None
42
+ args: dict
43
+ error: str | None
44
+ label: str
45
+ repeat_note: str | None = None
46
+ abort: bool = False
47
+
48
+
49
+ class Agent:
50
+ def __init__(self, rt, *, name: str = "main", depth: int = 0, agent_def=None, slot: int | None = None,
51
+ effort: str | None = None, max_steps: int | None = None, messages: list[dict] | None = None,
52
+ client=None):
53
+ self.rt = rt
54
+ self.name = name
55
+ self.depth = depth
56
+ self.agent_def = agent_def
57
+ self.slot = slot
58
+ self.effort = effort
59
+ self.client = client
60
+ self.max_steps = max_steps or int(rt.settings.get("max_steps_per_turn", 150))
61
+ self.messages: list[dict] = messages if messages is not None else [dict(m) for m in rt.prefix_messages]
62
+ self.todos = TodoState()
63
+ self.last_total_tokens = 0
64
+ self._counted_upto = 0
65
+ self.pending_reminders: list[str] = []
66
+ self.env_note: str | None = None # date/git snapshot for the next user message (conversation start)
67
+ self._interrupted = False
68
+ self._repeat_counts: dict[str, int] = {}
69
+ self._stop_hook_active = False
70
+ self.persist = depth == 0
71
+ self.parent_call_id = "" # for subagents: the Task call that started them
72
+ self.forked = False # for subagents: started from a copy of the main conversation
73
+ # Messages before this index were inherited (prompt prefix, or the conversation a fork started from).
74
+ self.own_start = self.n_prefix() if messages is None or depth == 0 else len(self.messages)
75
+
76
+ # ------------------------------------------------------------------ helpers
77
+ @property
78
+ def is_main(self) -> bool:
79
+ return self.depth == 0
80
+
81
+ @property
82
+ def llm(self):
83
+ return self.client or self.rt.client
84
+
85
+ def current_effort(self) -> str | None:
86
+ return self.effort if self.effort is not None else self.rt.effort
87
+
88
+ def _append(self, msg: dict) -> None:
89
+ self.messages.append(msg)
90
+ if self.persist:
91
+ self.rt.session.message(msg)
92
+
93
+ def add_reminder(self, text: str) -> None:
94
+ self.pending_reminders.append(text)
95
+
96
+ def n_prefix(self) -> int:
97
+ """Number of leading messages that form the shared prompt prefix (the system message)."""
98
+ n = 0
99
+ for m in self.messages:
100
+ if m.get("role") != "system":
101
+ break
102
+ n += 1
103
+ return n
104
+
105
+ def fork_messages(self, call_id: str) -> list[dict] | None:
106
+ """This conversation up to and including the assistant message that made `call_id`.
107
+ A forked subagent starts from it, so its prompt begins with this agent's cached state."""
108
+ if not call_id:
109
+ return None
110
+ for i in range(len(self.messages) - 1, -1, -1):
111
+ m = self.messages[i]
112
+ if m.get("role") == "assistant" and any(tc.get("id") == call_id for tc in m.get("tool_calls") or []):
113
+ return [dict(x) for x in self.messages[: i + 1]]
114
+ return None
115
+
116
+ def context_tokens(self) -> int:
117
+ """Best estimate of the current context size (what the next request will send)."""
118
+ if self.last_total_tokens and self._counted_upto <= len(self.messages):
119
+ extra = sum(est_tokens(_msg_text(m)) for m in self.messages[self._counted_upto:])
120
+ return self.last_total_tokens + extra
121
+ tools = est_tokens(json.dumps(self.rt.tool_schemas)) if self.llm.tool_mode == "native" else 0
122
+ return tools + sum(est_tokens(_msg_text(m)) for m in self.messages)
123
+
124
+ def on_tool_output(self, call_id: str, text: str) -> None:
125
+ self.rt.ui.on_tool_output(self, call_id, text)
126
+
127
+ # ------------------------------------------------------------------ turn
128
+ async def run_turn(self, text: str, *, tool_call_id: str | None = None) -> TurnStats:
129
+ """Run one turn. `tool_call_id` starts a forked subagent: `text` (its brief) becomes the
130
+ result of that Task call instead of a user message."""
131
+ rt = self.rt
132
+ stats = TurnStats()
133
+ started = time.monotonic()
134
+ self._repeat_counts = {}
135
+ self._stop_hook_active = False
136
+ try:
137
+ if self.is_main:
138
+ rt.checkpoints.begin_turn(one_line(text, 60))
139
+ if rt.hooks.has("UserPromptSubmit"):
140
+ hook = await rt.hooks.run("UserPromptSubmit", {"prompt": text}, rt.cwd)
141
+ for n in hook.notices:
142
+ rt.ui.on_notice("warn", n)
143
+ if hook.block:
144
+ rt.ui.on_notice("error", f"Prompt blocked by a hook: {hook.reason or '(no reason)'}")
145
+ stats.stopped_reason = "hook"
146
+ return stats
147
+ self.pending_reminders.extend(hook.additional_context)
148
+ if tool_call_id:
149
+ self._append({"role": "tool", "tool_call_id": tool_call_id, "name": "Task", "content": text})
150
+ else:
151
+ self._append({"role": "user", "content": self._compose_user_content(text)})
152
+ length_retries = 0
153
+ while True:
154
+ if stats.steps >= self.max_steps:
155
+ rt.ui.on_notice("warn", f"{self.name}: stopped after {self.max_steps} steps.")
156
+ stats.stopped_reason = "max_steps"
157
+ break
158
+ if not self.is_main and stats.steps and self.context_tokens() > 0.9 * rt.context_limit():
159
+ rt.ui.on_notice("warn", f"{self.name}: stopped - its context is nearly full.")
160
+ stats.stopped_reason = "context"
161
+ break
162
+ stats.steps += 1
163
+ if self.is_main:
164
+ if stats.steps > 1:
165
+ queued = rt.ui.take_queued_input() # typed by the user while we were working
166
+ if queued:
167
+ self._append({"role": "user", "content": self._compose_user_content(queued)})
168
+ await self.maybe_compact()
169
+ turn = await self._call_model(stats)
170
+ if turn is None:
171
+ stats.stopped_reason = "error"
172
+ break
173
+ prepared = self._prepare_calls(turn)
174
+ self._record_assistant(turn)
175
+ if not prepared:
176
+ if turn.finish_reason == "length" and length_retries < 2:
177
+ length_retries += 1
178
+ self._append({"role": "user", "_meta": True, "content": reminder(
179
+ "Your reply hit the output token limit and was cut off. Continue from where you "
180
+ "stopped. Be more concise, and split large file writes or edits into smaller pieces.")})
181
+ continue
182
+ if self.is_main and rt.hooks.has("Stop"):
183
+ out = await rt.hooks.run("Stop", {"stop_hook_active": self._stop_hook_active}, rt.cwd)
184
+ if out.block and out.reason and not out.halt:
185
+ self._stop_hook_active = True
186
+ self._append({"role": "user", "_meta": True,
187
+ "content": reminder(f"A Stop hook asked you to continue: {out.reason}")})
188
+ continue
189
+ break
190
+ stats.tool_calls += len(prepared)
191
+ if any(p.abort for p in prepared):
192
+ for p in prepared:
193
+ self._append(self._tool_message(p, ToolResult.error(
194
+ "Stopped: this exact call has been repeated too many times.")))
195
+ rt.ui.on_notice("error", f"{self.name}: stopped - the model kept repeating the same tool call.")
196
+ stats.stopped_reason = "loop"
197
+ break
198
+ results = await self._execute_calls(prepared)
199
+ stop = False
200
+ for p, res in zip(prepared, results):
201
+ self._append(self._tool_message(p, res))
202
+ stop = stop or res.stop_turn
203
+ if stop:
204
+ stats.stopped_reason = "denied"
205
+ break
206
+ except asyncio.CancelledError:
207
+ stats.stopped_reason = "interrupted"
208
+ self._interrupted = True
209
+ self._close_dangling_calls("[Interrupted by the user before this tool call finished.]")
210
+ if self.depth > 0:
211
+ raise
212
+ except Exception as e: # noqa: BLE001 - never crash the REPL on a bug
213
+ stats.stopped_reason = "error"
214
+ self._close_dangling_calls(f"[Tool call aborted by an internal error: {e}]")
215
+ rt.ui.on_notice("error", f"Internal error: {type(e).__name__}: {e}")
216
+ if rt.debug:
217
+ rt.ui.on_notice("error", traceback.format_exc())
218
+ finally:
219
+ stats.elapsed = time.monotonic() - started
220
+ return stats
221
+
222
+ def _compose_user_content(self, text: str) -> str:
223
+ parts = []
224
+ if self.env_note:
225
+ parts.append(reminder(self.env_note))
226
+ self.env_note = None
227
+ if self._interrupted:
228
+ parts.append(reminder("The user interrupted your previous turn."))
229
+ self._interrupted = False
230
+ for r in self.pending_reminders:
231
+ parts.append(r if r.lstrip().startswith("<system-reminder>") else reminder(r))
232
+ self.pending_reminders = []
233
+ parts.append(text)
234
+ return "\n\n".join(parts)
235
+
236
+ # ------------------------------------------------------------------ model call
237
+ async def _call_model(self, stats: TurnStats, *, tools_allowed: bool = True) -> AssistantTurn | None:
238
+ rt, ui, client = self.rt, self.rt.ui, self.llm
239
+ keep = rt.settings.get("provider.keep_reasoning", "all")
240
+ allow_compact_retry = self.is_main
241
+ while True:
242
+ wire = to_wire(self.messages, tool_mode=client.tool_mode, keep_reasoning=keep)
243
+ tools = rt.tool_schemas if client.tool_mode == "native" else None
244
+ extra = None if tools_allowed or not tools else {"tool_choice": "none"}
245
+ asm = ChunkAssembler()
246
+ ui.on_model_start(self, {"est_prompt_tokens": self.context_tokens(), "step": stats.steps})
247
+ try:
248
+ if self.is_main:
249
+ await rt.wait_warmup()
250
+ turn = await client.stream_chat(
251
+ wire, tools, on_delta=lambda d: ui.on_delta(self, d), assembler=asm,
252
+ effort=self.current_effort(), max_tokens=rt.settings.get("provider.max_output_tokens"),
253
+ slot=self.slot, extra=extra)
254
+ except asyncio.CancelledError:
255
+ partial, _ = asm.finish()
256
+ partial.interrupted = True
257
+ ui.on_model_end(self, partial)
258
+ if partial.content.strip():
259
+ msg = {"role": "assistant", "content": partial.content}
260
+ if partial.reasoning:
261
+ msg["reasoning_content"] = partial.reasoning
262
+ self._append(msg)
263
+ raise
264
+ except LLMError as e:
265
+ ui.on_model_end(self, None)
266
+ if e.kind == "context_overflow" and allow_compact_retry and len(self.messages) > self.n_prefix() + 1:
267
+ allow_compact_retry = False
268
+ ui.on_notice("warn", "The prompt exceeded the context window - compacting and retrying.")
269
+ if await self.compact(reason="overflow"):
270
+ continue
271
+ if e.kind == "tools_unsupported" and client.tool_mode == "native" and \
272
+ rt.settings.get("provider.tool_mode", "auto") == "auto":
273
+ ui.on_notice("warn", "The server rejected native tool calling; switching to text-based tool calls.")
274
+ rt.switch_to_text_tools()
275
+ self._replace_prefix()
276
+ continue
277
+ ui.on_notice("error", f"Model request failed: {e}" + _hint_for(e, rt))
278
+ return None
279
+ ui.on_model_end(self, turn)
280
+ if client.tool_mode == "text" or (not turn.tool_calls and has_text_tool_markup(turn.content)):
281
+ content, calls = parse_text_tool_calls(turn.content)
282
+ if calls:
283
+ turn.content, turn.tool_calls = content, calls
284
+ u = turn.usage
285
+ if not u.prompt_tokens:
286
+ u.prompt_tokens = self.context_tokens()
287
+ if not u.completion_tokens:
288
+ u.completion_tokens = est_tokens(turn.content + turn.reasoning)
289
+ self.last_total_tokens = u.prompt_tokens + u.completion_tokens
290
+ self._counted_upto = len(self.messages) + 1 # +1: the assistant message about to be recorded
291
+ rt.add_usage(u, self)
292
+ stats.usage.add(u)
293
+ return turn
294
+
295
+ def _replace_prefix(self) -> None:
296
+ n = self.n_prefix()
297
+ self.messages = [dict(m) for m in self.rt.prefix_messages] + self.messages[n:]
298
+ self.own_start += len(self.rt.prefix_messages) - n
299
+
300
+ def _record_assistant(self, turn: AssistantTurn) -> None:
301
+ for _i, tc in enumerate(turn.tool_calls):
302
+ if not tc.id:
303
+ tc.id = f"call_{uuid.uuid4().hex[:12]}"
304
+ self._append(turn.to_message())
305
+
306
+ # ------------------------------------------------------------------ tool calls
307
+ def _prepare_calls(self, turn: AssistantTurn) -> list[PreparedCall]:
308
+ out = []
309
+ for tc in turn.tool_calls:
310
+ if not tc.id:
311
+ tc.id = f"call_{uuid.uuid4().hex[:12]}"
312
+ tool = self.rt.tools.get(tc.name)
313
+ if tool is None:
314
+ names = ", ".join(self.rt.tools.names())
315
+ out.append(PreparedCall(tc, None, {}, f"Unknown tool '{tc.name}'. Available tools: {names}.", tc.name))
316
+ continue
317
+ args = tc.args
318
+ error = tc.error
319
+ if args is None and error is None:
320
+ parsed, err = loads_lenient(tc.arguments)
321
+ if err is not None or not isinstance(parsed, dict):
322
+ error = (f"The arguments for {tool.name} are not a valid JSON object ({err or 'not an object'}). "
323
+ "Re-send the call with valid JSON.")
324
+ else:
325
+ args = parsed
326
+ args = dict(args or {})
327
+ if error is None:
328
+ tool.apply_aliases(args)
329
+ args, verr = validate_args(tool, args)
330
+ if verr:
331
+ expected = ", ".join(
332
+ f"{k}{'' if k in (tool.parameters.get('required') or []) else '?'}"
333
+ for k in (tool.parameters.get("properties") or {}))
334
+ error = (f"Invalid arguments for {tool.name}: {verr}. Parameters: {expected}. "
335
+ "Fix the arguments; do not re-send this call unchanged.")
336
+ p = PreparedCall(tc, tool, args, error, tool.label(args) if error is None else tc.name)
337
+ if error is None:
338
+ sig = tool.name + json.dumps(args, sort_keys=True, ensure_ascii=False)[:4000]
339
+ count = self._repeat_counts.get(sig, 0) + 1
340
+ self._repeat_counts[sig] = count
341
+ if count >= REPEAT_ABORT_AT:
342
+ p.abort = True
343
+ elif count in REPEAT_WARN_AT:
344
+ p.repeat_note = (f"You have now made this exact {tool.name} call {count} times in this turn. "
345
+ "Repeating it will not give a different result. Change your approach: "
346
+ "re-read the relevant code, try a different command or search, or ask the user.")
347
+ out.append(p)
348
+ return out
349
+
350
+ def _parallel_ok(self, p: PreparedCall) -> bool:
351
+ if p.error or p.tool is None or not p.tool.is_read_only(p.args):
352
+ return False
353
+ if p.tool.name == "Task":
354
+ return self.rt.parallel_subagents()
355
+ if p.tool.kind in ("interact",):
356
+ return False
357
+ verdict, _ = self.rt.permissions.evaluate(p.tool, p.args, self.rt.cwd)
358
+ return verdict == "allow"
359
+
360
+ async def _execute_calls(self, prepared: list[PreparedCall]) -> list[ToolResult]:
361
+ n = len(prepared)
362
+ results: list[ToolResult | None] = [None] * n
363
+ i = 0
364
+ stopped = False
365
+ while i < n and not stopped:
366
+ batch = []
367
+ while i < n and self._parallel_ok(prepared[i]):
368
+ batch.append(i)
369
+ i += 1
370
+ if len(batch) == 1:
371
+ results[batch[0]] = await self._execute_one(prepared[batch[0]])
372
+ elif batch:
373
+ outs = await asyncio.gather(*(self._execute_one(prepared[j]) for j in batch))
374
+ for j, r in zip(batch, outs):
375
+ results[j] = r
376
+ if any(results[j] and results[j].stop_turn for j in batch):
377
+ break
378
+ if i < n:
379
+ res = await self._execute_one(prepared[i])
380
+ results[i] = res
381
+ i += 1
382
+ stopped = res.stop_turn
383
+ return [r if r is not None else ToolResult(
384
+ content="[Skipped: the user stopped this turn before this tool call ran.]", is_error=True, summary="Skipped")
385
+ for r in results]
386
+
387
+ def _restriction(self, tool: Tool, args: dict) -> str | None:
388
+ a = self.agent_def
389
+ if self.depth > 0 and tool.name == "Task":
390
+ return "Subagents cannot start other subagents. Do the work directly."
391
+ if a is None:
392
+ return None
393
+ if a.tools is not None and tool.name not in a.tools and not (tool.name.startswith("mcp__") and "mcp" in a.tools):
394
+ return (f"The {tool.name} tool is not available to the {a.name} subagent. "
395
+ f"Use only: {', '.join(a.tools)}.")
396
+ if a.read_only and not tool.is_read_only(args):
397
+ return (f"The {a.name} subagent is read-only and this {tool.name} call could modify state. "
398
+ "Use read-only operations only.")
399
+ return None
400
+
401
+ async def _execute_one(self, p: PreparedCall) -> ToolResult:
402
+ rt, ui = self.rt, self.rt.ui
403
+ if p.error or p.tool is None:
404
+ res = ToolResult.error(p.error or "invalid call")
405
+ ui.on_tool_end(self, p, res)
406
+ return res
407
+ tool, args = p.tool, p.args
408
+ ui.on_tool_start(self, p, args)
409
+ restriction = self._restriction(tool, args)
410
+ if restriction:
411
+ res = ToolResult.error(restriction, summary="Not allowed for this agent")
412
+ ui.on_tool_end(self, p, res)
413
+ return res
414
+ hook = HookOutcome()
415
+ if rt.hooks.has("PreToolUse"):
416
+ hook = await rt.hooks.run("PreToolUse", {"tool_name": tool.name, "tool_input": args}, rt.cwd, tool.name)
417
+ for n in hook.notices:
418
+ ui.on_notice("warn", n)
419
+ if hook.block:
420
+ res = ToolResult.error(f"Blocked by a PreToolUse hook: {hook.reason or '(no reason given)'}",
421
+ summary="Blocked by hook")
422
+ res.stop_turn = hook.halt
423
+ ui.on_tool_end(self, p, res)
424
+ return res
425
+ if hook.updated_input:
426
+ args, verr = validate_args(tool, {**args, **hook.updated_input})
427
+ if verr:
428
+ res = ToolResult.error(f"A hook rewrote the input into an invalid call: {verr}")
429
+ ui.on_tool_end(self, p, res)
430
+ return res
431
+ verdict, reason = rt.permissions.evaluate(tool, args, rt.cwd)
432
+ if verdict != "deny" and hook.permission in ("allow", "ask"):
433
+ verdict = hook.permission
434
+ if verdict == "deny":
435
+ res = ToolResult.error(f"Permission denied: {reason}.", summary="Denied")
436
+ ui.on_tool_end(self, p, res)
437
+ return res
438
+ ctx = ToolContext(rt, self, p.call.id)
439
+ if verdict == "ask":
440
+ preview = None
441
+ if hasattr(tool, "preview"):
442
+ pv = await tool.preview(args, ctx)
443
+ if isinstance(pv, ToolResult): # e.g. an edit that would fail anyway - don't bother the user
444
+ ui.on_tool_end(self, p, pv)
445
+ return pv
446
+ preview = pv
447
+ req = rt.permissions.build_request(tool, args, p.label, reason)
448
+ req.preview = preview
449
+ decision = await ui.request_permission(req, self)
450
+ if decision is None:
451
+ res = ToolResult.error(
452
+ "This action needs the user's approval, but nobody is available to approve it, so it was not "
453
+ "run. Continue with what you can do without it, and mention it in your summary.",
454
+ summary="Needs approval (non-interactive)")
455
+ ui.on_tool_end(self, p, res)
456
+ return res
457
+ if decision.remember_rule:
458
+ where = rt.permissions.remember(decision.remember_rule)
459
+ ui.on_notice("info", f"Allowed {decision.remember_rule}" + (f" (saved to {where})" if where else ""))
460
+ if decision.session_mode:
461
+ rt.set_mode(decision.session_mode)
462
+ if not decision.allow:
463
+ msg = "The user rejected this tool call."
464
+ msg += f" Their instructions: {decision.feedback}" if decision.feedback else \
465
+ " Do not retry it. If the way forward is unclear, ask the user."
466
+ res = ToolResult(content=msg, is_error=True, summary="Rejected", stop_turn=decision.stop)
467
+ ui.on_tool_end(self, p, res)
468
+ return res
469
+ try:
470
+ res = await tool.run(args, ctx)
471
+ except asyncio.CancelledError:
472
+ raise
473
+ except Exception as e: # noqa: BLE001
474
+ res = ToolResult.error(f"{tool.name} failed with an internal error: {type(e).__name__}: {e}")
475
+ if rt.debug:
476
+ ui.on_notice("error", traceback.format_exc())
477
+ if p.repeat_note:
478
+ res.content += "\n\n" + reminder(p.repeat_note)
479
+ if rt.hooks.has("PostToolUse"):
480
+ post = await rt.hooks.run("PostToolUse", {"tool_name": tool.name, "tool_input": args,
481
+ "tool_response": {"content": res.content[:20000],
482
+ "is_error": res.is_error}},
483
+ rt.cwd, tool.name)
484
+ for n in post.notices:
485
+ ui.on_notice("warn", n)
486
+ if post.block and post.reason:
487
+ res.content += "\n\n" + reminder(f"PostToolUse hook feedback: {post.reason}")
488
+ for c in post.additional_context:
489
+ res.content += "\n\n" + reminder(c)
490
+ if post.halt:
491
+ res.stop_turn = True
492
+ ui.on_tool_end(self, p, res)
493
+ return res
494
+
495
+ def _tool_message(self, p: PreparedCall, res: ToolResult) -> dict:
496
+ content = res.content if res.content.strip() else "(no output)"
497
+ return {"role": "tool", "tool_call_id": p.call.id, "name": p.call.name, "content": content}
498
+
499
+ def _close_dangling_calls(self, text: str) -> None:
500
+ last = next((m for m in reversed(self.messages[self.own_start:]) if m.get("role") == "assistant"), None)
501
+ if not last or not last.get("tool_calls"):
502
+ return
503
+ idx = max(i for i, m in enumerate(self.messages) if m is last)
504
+ answered = {m.get("tool_call_id") for m in self.messages[idx + 1:] if m.get("role") == "tool"}
505
+ for tc in last["tool_calls"]:
506
+ if tc.get("id") not in answered:
507
+ self._append({"role": "tool", "tool_call_id": tc.get("id"),
508
+ "name": tc.get("function", {}).get("name"), "content": text})
509
+
510
+ # ------------------------------------------------------------------ compaction
511
+ async def maybe_compact(self) -> None:
512
+ if not self.rt.settings.get("context.auto_compact", True):
513
+ return
514
+ if len(self.messages) <= self.n_prefix() + 2:
515
+ return
516
+ if self.context_tokens() >= self.rt.compact_threshold():
517
+ await self.compact(reason="auto")
518
+
519
+ async def compact(self, instructions: str | None = None, reason: str = "manual") -> bool:
520
+ rt, ui, client = self.rt, self.rt.ui, self.llm
521
+ n_sys = self.n_prefix()
522
+ if len(self.messages) <= n_sys + 1:
523
+ ui.on_notice("info", "Nothing to compact yet.")
524
+ return False
525
+ before = self.context_tokens()
526
+ if self.is_main and rt.hooks.has("PreCompact"):
527
+ await rt.hooks.run("PreCompact", {"trigger": reason, "custom_instructions": instructions or ""}, rt.cwd)
528
+ ui.on_compact_start(self, before, reason)
529
+ request = self.messages + [{"role": "user", "content": compact_instruction(instructions)}]
530
+ wire = to_wire(request, tool_mode=client.tool_mode, keep_reasoning=rt.settings.get("provider.keep_reasoning", "all"))
531
+ tools = rt.tool_schemas if client.tool_mode == "native" else None # identical prefix -> cache hit
532
+ asm = ChunkAssembler()
533
+ try:
534
+ turn = await client.stream_chat(wire, tools, on_delta=lambda d: ui.on_compact_delta(self, d), assembler=asm,
535
+ effort=self.current_effort(), max_tokens=12000, slot=self.slot,
536
+ extra={"tool_choice": "none"} if tools else None)
537
+ except LLMError as e:
538
+ ui.on_compact_end(self, before, before, None)
539
+ ui.on_notice("error", f"Compaction failed: {e}")
540
+ return False
541
+ summary = _REMINDER_RE.sub("", turn.content).strip()
542
+ if not summary and turn.tool_calls:
543
+ summary = "\n".join(tc.arguments for tc in turn.tool_calls)[:8000]
544
+ if not summary:
545
+ ui.on_compact_end(self, before, before, None)
546
+ ui.on_notice("error", "Compaction failed: the model returned an empty summary.")
547
+ return False
548
+ rt.add_usage(turn.usage, self)
549
+ recent = self._recent_user_messages(int(rt.settings.get("context.keep_recent_chars", 6000)))
550
+ files = [display_path(p, rt.cwd) for p in rt.file_state.recent(12)]
551
+ todos_text = self.todos.render_text() if self.todos.items else None
552
+ new_user = {"role": "user", "_compact": True,
553
+ "content": post_compact_message(summary, recent, todos_text, files)}
554
+ self.messages = [dict(m) for m in self.messages[:n_sys]] + [new_user]
555
+ self.own_start = n_sys
556
+ self.last_total_tokens = 0
557
+ self._counted_upto = 0
558
+ if self.persist:
559
+ rt.session.compact(self.messages, turn.usage.completion_tokens)
560
+ ui.on_compact_end(self, before, self.context_tokens(), summary)
561
+ return True
562
+
563
+ def _recent_user_messages(self, budget: int) -> list[str]:
564
+ recent: list[str] = []
565
+ for m in reversed(self.messages):
566
+ if m.get("role") != "user" or m.get("_meta") or m.get("_compact"):
567
+ continue
568
+ text = _REMINDER_RE.sub("", _msg_text(m)).strip()
569
+ if not text:
570
+ continue
571
+ if len(text) > budget:
572
+ if recent:
573
+ break
574
+ text = text[:budget] + " [...]"
575
+ recent.insert(0, text)
576
+ budget -= len(text)
577
+ if budget <= 0 or len(recent) >= 4:
578
+ break
579
+ return recent
580
+
581
+ async def final_report(self) -> str:
582
+ """Ask a subagent that ran out of steps for its report (one tool-less call)."""
583
+ self._append({"role": "user", "_meta": True, "content": reminder(
584
+ "You have reached your step limit. Do not call any more tools. Write your final report now with what "
585
+ "you found so far, and note what remains unverified.")})
586
+ turn = await self._call_model(TurnStats(), tools_allowed=False)
587
+ if turn is None:
588
+ return ""
589
+ turn.tool_calls = []
590
+ self._record_assistant(turn)
591
+ return turn.content.strip()
592
+
593
+ def last_assistant_text(self) -> str:
594
+ for m in reversed(self.messages[self.own_start:]):
595
+ if m.get("role") == "assistant":
596
+ return (m.get("content") or "").strip()
597
+ if m.get("role") == "user":
598
+ break
599
+ return ""
600
+
601
+
602
+ def _msg_text(m: dict) -> str:
603
+ c = m.get("content")
604
+ if isinstance(c, str):
605
+ text = c
606
+ elif isinstance(c, list):
607
+ text = " ".join(p.get("text", "") for p in c if isinstance(p, dict))
608
+ else:
609
+ text = ""
610
+ if m.get("reasoning_content"):
611
+ text += m["reasoning_content"]
612
+ for tc in m.get("tool_calls") or []:
613
+ text += tc.get("function", {}).get("arguments", "") + tc.get("function", {}).get("name", "")
614
+ return text
615
+
616
+
617
+ def _hint_for(e: LLMError, rt) -> str:
618
+ if e.kind == "connection":
619
+ return (f"\nCheck that the server is running and reachable at {rt.client.base_url} "
620
+ "(firewall/port), or run `rigcode doctor`.")
621
+ if e.kind == "auth":
622
+ return "\nCheck provider.api_key in your settings."
623
+ if e.kind == "not_found":
624
+ return "\nCheck provider.base_url (should usually end in /v1) and provider.model."
625
+ if e.kind == "context_overflow":
626
+ return "\nTry /compact or /clear."
627
+ return ""