coder-agent 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 (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. coderagent/web/templates/zh/skills.html +61 -0
@@ -0,0 +1,702 @@
1
+ """The main loop: user input -> model -> tools -> model, until the model stops."""
2
+
3
+ import logging
4
+ import time
5
+ from collections.abc import Callable, Iterator
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ from coderagent.config.schema import ContextConfig
10
+ from coderagent.core import schema
11
+ from coderagent.core.capabilities import TAKES, probe, support
12
+ from coderagent.core.content import describe_message, modalities_of, text_of, with_text
13
+ from coderagent.core.context import ContextEngine
14
+ from coderagent.core.events import Event, EventBus, EventType
15
+ from coderagent.core.mentions import expand as expand_mentions
16
+ from coderagent.core.otel import build_trace
17
+ from coderagent.core.protocols import ToolExecutor
18
+ from coderagent.core.session import Session, SessionState, SessionStore
19
+ from coderagent.core.tokens import trim_text
20
+ from coderagent.environments import is_local
21
+ from coderagent.models.gateway import ModelGateway, is_context_overflow
22
+ from coderagent.models.streaming import ModelEvent, message_from_events
23
+ from coderagent.tools.permissions import PermissionMode
24
+
25
+ logger = logging.getLogger("coderagent.core.loop")
26
+
27
+ VERIFY_OUTPUT_TOKENS = 2000
28
+ """The tokens of the output of a check that go back to the model."""
29
+
30
+ MAX_SCHEMA_ATTEMPTS = 2
31
+ """How many answers the model may give for a schema. Two means: one answer and one try again."""
32
+
33
+ REVIEW_NOTE = "[the changes that were reviewed are not in the context anymore: read the files again]"
34
+ """What takes the place of the diff of a review when the turn is over."""
35
+
36
+ STOP_NOTES = {
37
+ "max_turns": "the turn was cut off: it reached the ceiling of {max_turns} model calls",
38
+ "cost_exceeded": "the turn stopped: the budget of the session is spent",
39
+ "token_limit": "the turn stopped: the token limit of the session is reached",
40
+ }
41
+ """What to say when a turn did not end the way a turn should.
42
+
43
+ A turn that ends like this has not failed, but it has not finished either: the
44
+ user has to know why the agent went quiet.
45
+ """
46
+
47
+
48
+ def stop_note(stop_reason: str, max_turns: int = 0) -> str:
49
+ """The line that tells the user why the turn stopped. Empty when it ended well."""
50
+ note = STOP_NOTES.get(stop_reason, "")
51
+ return note.format(max_turns=max_turns) if note else ""
52
+
53
+
54
+ def _answer_of(messages: list[dict]) -> str:
55
+ """What the agent answered."""
56
+ for message in reversed(messages):
57
+ if message.get("role") == "assistant":
58
+ return text_of(message.get("content"))
59
+ return ""
60
+
61
+
62
+ class Interrupted(Exception):
63
+ """The turn was stopped while the model was answering."""
64
+
65
+
66
+ @dataclass
67
+ class TurnResult:
68
+ session_id: str
69
+ turn_count: int
70
+ """Number of user-initiated turns in this session so far."""
71
+ cost: float
72
+ """What this turn cost."""
73
+ stop_reason: str
74
+ """One of `end_turn`, `max_turns`, `cost_exceeded`, `token_limit`, `schema_invalid`, `error`."""
75
+ messages: list[dict] = field(default_factory=list)
76
+ """Messages added during this turn."""
77
+ error: str = ""
78
+ """Why the turn stopped, if it stopped because of an error."""
79
+ session_cost: float = 0.0
80
+ """What the whole session cost, the turns before this one and the reflection included."""
81
+ output: Any = None
82
+ """The answer of the agent, when a schema was asked for. None otherwise."""
83
+
84
+
85
+ class AgentLoop:
86
+ def __init__(
87
+ self,
88
+ model: ModelGateway,
89
+ executor: ToolExecutor,
90
+ session: Session,
91
+ store: SessionStore,
92
+ bus: EventBus,
93
+ *,
94
+ context: ContextEngine | None = None,
95
+ tools: list[dict] | None = None,
96
+ system_prompt: str = "",
97
+ max_turns: int = 100,
98
+ cost_limit: float = 0.0,
99
+ token_limit: int = 0,
100
+ checkpoints=None,
101
+ hooks=None,
102
+ mcp=None,
103
+ subagents=None,
104
+ router=None,
105
+ plugins=None,
106
+ sandbox=None,
107
+ schema_budget: int | None = None,
108
+ verify=None,
109
+ exporter=None,
110
+ output_schema: dict | None = None,
111
+ enforce_ceilings: bool = False,
112
+ capabilities: dict | None = None,
113
+ remember: Callable[[str, str, bool], None] | None = None,
114
+ ) -> None:
115
+ self.model = model
116
+ self.executor = executor
117
+ self.policy = executor.policy
118
+ """The permission policy of the session. `/mode` changes it under us."""
119
+ self.session = session
120
+ self.store = store
121
+ self.bus = bus
122
+ self.tools = tools
123
+ self.system_prompt = system_prompt
124
+ self.max_turns = max_turns
125
+ self.cost_limit = cost_limit
126
+ self.token_limit = token_limit
127
+ """Stop after this many tokens. The budget of a model that has no price."""
128
+ self.enforce_ceilings = enforce_ceilings
129
+ """Whether the ceilings hold even in bypass. A harness that measures asks for them."""
130
+ self.checkpoints = checkpoints
131
+ self.hooks = hooks
132
+ """The hook runner, when the session has hooks."""
133
+ self.mcp = mcp
134
+ """The MCP manager, when the session has servers."""
135
+ self.subagents = subagents or {}
136
+ """The sub agents that are available, by name."""
137
+ self.router = router
138
+ """The model router, when the session has one."""
139
+ self.plugins = plugins or []
140
+ """The plugins that were loaded, by name."""
141
+ self.sandbox = sandbox
142
+ """The environment the commands run in."""
143
+ self.schema_budget = schema_budget
144
+ """The tokens the schemas of the tools may take. None means no limit."""
145
+ self.verify = verify
146
+ """The commands that check the work of the agent. None means: no verification."""
147
+ self.exporter = exporter
148
+ """Where the trace of the session goes. None means: it stays in the event log."""
149
+ self.output_schema = output_schema
150
+ """The shape the answer of the agent has to have. None means: any shape is fine."""
151
+ self.capabilities = capabilities or {}
152
+ """What the models take, as the user said it."""
153
+ self.remember = remember
154
+ """Where the answer of a probe is written down. None means: it stays in this session."""
155
+ self._asked: set[tuple[str, str]] = set()
156
+ """The models that did not answer a probe. They are not asked again."""
157
+ self._exported = 0
158
+ """How many events of the session the backend has seen."""
159
+ self.cancel = None
160
+ """A callable that says whether the turn should stop. The interface sets it."""
161
+ self.purpose = "main"
162
+ """Why the model is called. The router picks the model of the purpose."""
163
+ self._warned_unpriced = False
164
+ self.context = context or ContextEngine(
165
+ session,
166
+ store,
167
+ bus,
168
+ ContextConfig(),
169
+ model,
170
+ system_prompt=system_prompt,
171
+ cwd=session.cwd,
172
+ policy=self.policy,
173
+ )
174
+ self.context.system_prompt = self._system_prompt(system_prompt or self.context.system_prompt)
175
+ self.context.hooks = self.hooks
176
+ """The context needs the hooks too: it is the one that compresses."""
177
+ self.context.tools = self.tools
178
+ """The schemas of the tools are in every request, so the budget counts them."""
179
+ self.context.restore()
180
+ self._session_start()
181
+
182
+ @property
183
+ def messages(self) -> list[dict]:
184
+ return self.context.history.messages
185
+
186
+ def _system_prompt(self, base: str) -> str:
187
+ """The prompt of the model, with the shape its answer has to have."""
188
+ if not self.output_schema:
189
+ return base
190
+ return f"{base}\n\n{schema.note(self.output_schema)}".strip()
191
+
192
+ def switch_to(self, session: Session, *, start: bool = True) -> None:
193
+ """Continue in another session, with the history that session already has."""
194
+ self.session = session
195
+ self.context = ContextEngine(
196
+ session,
197
+ self.store,
198
+ self.bus,
199
+ self.context.config,
200
+ self.model,
201
+ system_prompt=self.system_prompt,
202
+ memory_config=self.context.memory_config,
203
+ summary_model=self.context.summary_model,
204
+ cwd=session.cwd,
205
+ policy=self.policy,
206
+ instructions=self.context.instruction_blocks,
207
+ user_home=self.context.user_home,
208
+ )
209
+ self.context.reload_instructions = True
210
+ """The instruction files of the new directory are read again."""
211
+ self.context.system_prompt = self._system_prompt(self.context.system_prompt)
212
+ """The shape of the answer is told again: the new context starts from scratch."""
213
+ self.context.hooks = self.hooks
214
+ self.context.tools = self.tools
215
+ self.context.restore()
216
+ self._exported = 0
217
+ """Another session has its own trace."""
218
+ if start:
219
+ self._session_start()
220
+
221
+ def run(self, user_input: str | list[dict]) -> TurnResult:
222
+ """Alias for `run_turn`; the caller drives the conversation."""
223
+ return self.run_turn(user_input)
224
+
225
+ def run_turn(self, user_input: str | list[dict], purpose: str = "", session: Session | None = None) -> TurnResult:
226
+ """Run one turn: query the model, execute its tool calls, repeat until it stops.
227
+
228
+ The input is a string, or the parts of a message that carries images.
229
+ The purpose says which model answers the turn: `main` unless the caller
230
+ says otherwise, like `review`. A session says that the turn happens
231
+ somewhere else: a conversation that goes aside.
232
+ """
233
+ if session is None:
234
+ return self._turn(user_input, purpose)
235
+ return self._aside(user_input, purpose, session)
236
+
237
+ def _aside(self, user_input: str | list[dict], purpose: str, session: Session) -> TurnResult:
238
+ """Run a turn in another session, and come back to this one.
239
+
240
+ The conversation that goes aside has its own log. This one is not
241
+ touched: the question and the answer are recorded in it, and nothing else.
242
+ """
243
+ previous = self.session
244
+ exported = self._exported
245
+ self.switch_to(session)
246
+ try:
247
+ result = self._turn(user_input, purpose or "side")
248
+ finally:
249
+ self.switch_to(previous, start=False)
250
+ self._exported = exported
251
+ self.session.total_cost += result.cost
252
+ """The user paid for the side conversation, so the session pays for it."""
253
+ self._publish(
254
+ EventType.SIDE_CONVERSATION,
255
+ {
256
+ "question": text_of(user_input),
257
+ "answer": _answer_of(result.messages),
258
+ "session_id": session.id,
259
+ "cost": result.cost,
260
+ "stop_reason": result.stop_reason,
261
+ },
262
+ )
263
+ return result
264
+
265
+ def _turn(self, user_input: str | list[dict], purpose: str = "") -> TurnResult:
266
+ self.purpose = purpose or "main"
267
+ turn_messages: list[dict] = []
268
+ prompt = user_input
269
+ original = ""
270
+ if self.hooks:
271
+ hook = self.hooks.apply("UserPromptSubmit", {"prompt": text_of(prompt)})
272
+ if hook.blocked:
273
+ reason = hook.reason or "the prompt was blocked"
274
+ self._publish(EventType.ERROR, {"error": reason})
275
+ self._publish(EventType.TURN_END, {"stop_reason": "error", "error": reason, "calls": 0, "cost": 0.0})
276
+ return TurnResult(
277
+ session_id=self.session.id,
278
+ turn_count=self.session.turn_count,
279
+ cost=0.0,
280
+ stop_reason="error",
281
+ error=reason,
282
+ )
283
+ if isinstance(hook.updated_input, str):
284
+ """The hook rewrote the prompt. What the user typed is kept aside."""
285
+ prompt = with_text(prompt, hook.updated_input)
286
+ original = text_of(user_input)
287
+ if hook.additional_context:
288
+ prompt = with_text(prompt, f"{text_of(prompt)}\n\n[hook] {hook.additional_context}")
289
+ prompt = with_text(prompt, expand_mentions(text_of(prompt), self.session.cwd, self.policy))
290
+ """The files the user mentions go into the message, with their content."""
291
+ self._route()
292
+ """The model of this turn is known before the message goes into the context:
293
+ what the user sent has to fit the model that answers."""
294
+ base = self.session.total_cost
295
+ refusal = self._refuses(prompt)
296
+ if refusal:
297
+ """The model cannot take what the user sent. It would answer anyway, and make it up."""
298
+ self.context.append({"role": "user", "content": describe_message(prompt)}, original=original)
299
+ self.session.turn_count += 1
300
+ self._set_state(SessionState.ERROR)
301
+ cost = self.session.total_cost - base
302
+ self._publish(EventType.ERROR, {"error": refusal})
303
+ self._publish(EventType.TURN_END, {"stop_reason": "error", "error": refusal, "calls": 0, "cost": cost})
304
+ return TurnResult(
305
+ session_id=self.session.id,
306
+ turn_count=self.session.turn_count,
307
+ cost=cost,
308
+ stop_reason="error",
309
+ error=refusal,
310
+ )
311
+ ephemeral = REVIEW_NOTE if self.purpose == "review" else ""
312
+ """The diff of a review is read once. It does not have to stay in the context."""
313
+ self.context.append({"role": "user", "content": prompt}, original=original, ephemeral=ephemeral)
314
+ turn_messages.append({"role": "user", "content": prompt})
315
+ self.session.turn_count += 1
316
+ self._set_state(SessionState.THINKING)
317
+
318
+ stop_reason = "end_turn"
319
+ error = ""
320
+ cost = 0.0
321
+ n_calls = 0
322
+ stop_blocks = 0
323
+ verify_rounds = 0
324
+ schema_attempts = 0
325
+ output = None
326
+ before = (self.model.total_cost, self.model.total_tokens)
327
+ while True:
328
+ # The tools of the last round may have spent money too.
329
+ before = self._bill(before)
330
+ if self.cancel is not None and self.cancel():
331
+ stop_reason = "interrupted"
332
+ break
333
+ if self._ceilings_hold():
334
+ if self.max_turns and n_calls >= self.max_turns:
335
+ stop_reason = "max_turns"
336
+ break
337
+ if self.cost_limit and self.session.total_cost >= self.cost_limit:
338
+ stop_reason = "cost_exceeded"
339
+ break
340
+ if self.token_limit and self.session.total_tokens >= self.token_limit:
341
+ stop_reason = "token_limit"
342
+ break
343
+ self.context.maybe_compact()
344
+ self._route()
345
+ try:
346
+ response, error = self._query()
347
+ except Interrupted:
348
+ """The user stopped the turn while the model was answering."""
349
+ stop_reason = "interrupted"
350
+ break
351
+ before = self._bill(before)
352
+ if response is None:
353
+ self._publish(EventType.ERROR, {"error": error})
354
+ stop_reason = "error"
355
+ break
356
+ n_calls += 1
357
+ response.setdefault("extra", {}).update(
358
+ {
359
+ "purpose": self.purpose,
360
+ "model": getattr(self.model.backend, "model_name", ""),
361
+ "priced": self.model.priced,
362
+ }
363
+ )
364
+ self._warn_unpriced(response)
365
+ self.context.append(response)
366
+ turn_messages.append(response)
367
+ tool_calls = response.get("tool_calls") or []
368
+ if not tool_calls:
369
+ if stop_blocks < 3 and self._stop_blocked(response):
370
+ stop_blocks += 1
371
+ continue
372
+ failure, exhausted = self._verify(verify_rounds)
373
+ if failure:
374
+ """The work does not pass the check: the agent gets to try again."""
375
+ verify_rounds += 1
376
+ self.context.append({"role": "user", "content": failure})
377
+ turn_messages.append({"role": "user", "content": failure})
378
+ if exhausted:
379
+ stop_reason = "verify_failed"
380
+ error = failure
381
+ break
382
+ continue
383
+ if self.output_schema:
384
+ """The answer has to fit the schema. When it does not, the model gets to try again."""
385
+ problems, value = self._check_schema(response)
386
+ if problems:
387
+ schema_attempts += 1
388
+ message = "[schema] The answer does not fit the schema.\n" + "\n".join(
389
+ f"- {problem}" for problem in problems
390
+ )
391
+ self.context.append({"role": "user", "content": message})
392
+ turn_messages.append({"role": "user", "content": message})
393
+ if schema_attempts >= MAX_SCHEMA_ATTEMPTS:
394
+ stop_reason = "schema_invalid"
395
+ error = "; ".join(problems)
396
+ break
397
+ continue
398
+ output = value
399
+ break
400
+ self._set_state(SessionState.EXECUTING)
401
+ actions = self.executor.plan(tool_calls)
402
+ self._publish(EventType.TOOL_CALL, {"actions": actions})
403
+ observations = self.executor.execute(actions)
404
+ self.context.extend(observations)
405
+ turn_messages.extend(observations)
406
+ self._set_state(SessionState.THINKING)
407
+
408
+ self.context.forget_ephemeral()
409
+ """The diff of a review is gone from the context. The rest of the session is not."""
410
+ # What the turn cost: everything the agent spent, the sub agents and the summaries included.
411
+ cost = self.session.total_cost - base
412
+ self._publish(
413
+ EventType.TURN_END,
414
+ {"stop_reason": stop_reason, "error": error, "calls": n_calls, "cost": cost},
415
+ )
416
+ self._set_state(SessionState.ERROR if stop_reason == "error" else SessionState.DONE, stop_reason=stop_reason)
417
+ self._session_end()
418
+ self._export_trace()
419
+ return TurnResult(
420
+ session_id=self.session.id,
421
+ turn_count=self.session.turn_count,
422
+ cost=cost,
423
+ stop_reason=stop_reason,
424
+ messages=turn_messages,
425
+ error=error,
426
+ output=output,
427
+ )
428
+
429
+ def _refuses(self, prompt) -> str:
430
+ """Why the model cannot take what the user sent. Empty when it can.
431
+
432
+ A model that cannot see a picture answers about it anyway, and the answer
433
+ is made up. So the turn does not start: the user is told what is missing.
434
+ A model nobody knows about is asked first, and the answer is remembered.
435
+ """
436
+ wanted = modalities_of(prompt)
437
+ if not wanted:
438
+ return ""
439
+ backend = self.model.backend
440
+ names = [getattr(backend, "alias", ""), getattr(backend, "model_name", "")]
441
+ for modality in sorted(wanted):
442
+ said = support(names, modality, self.capabilities)
443
+ if said is None:
444
+ said = self._measure(modality)
445
+ if said is True:
446
+ continue
447
+ name = next((one for one in names if one), "of this session")
448
+ if said is False:
449
+ return (
450
+ f"The model {name} cannot {TAKES[modality]}, so the turn did not start. "
451
+ f"Use a model that can (/model <name>), or say what is in the file."
452
+ )
453
+ return (
454
+ f"Nobody knows whether the model {name} can {TAKES[modality]}, so the turn did not start. "
455
+ f"Say what it takes in model.capabilities, or use a model that can."
456
+ )
457
+ return ""
458
+
459
+ def _measure(self, modality: str) -> bool | None:
460
+ """Ask the model whether it takes this kind of content, and remember it.
461
+
462
+ The answer is written down, so that the next time the configuration says
463
+ it and the model is not asked again.
464
+ """
465
+ name = getattr(self.model.backend, "model_name", "") or getattr(self.model.backend, "alias", "")
466
+ if (name, modality) in self._asked:
467
+ """The model did not answer the last time. It is not asked again."""
468
+ return None
469
+ self._set_state(SessionState.THINKING)
470
+ before = (self.model.total_cost, self.model.total_tokens)
471
+ said = probe(self._ask, modality)
472
+ self._bill(before)
473
+ """The probe is a call like any other: the session pays for it."""
474
+ if said is None:
475
+ self._asked.add((name, modality))
476
+ return None
477
+ self.capabilities = {**self.capabilities, name: {**self.capabilities.get(name, {}), modality: said}}
478
+ if self.remember:
479
+ self.remember(name, modality, said)
480
+ return said
481
+
482
+ def _ask(self, messages: list[dict]) -> str:
483
+ """What the model answers to a question of the agent itself."""
484
+ return self.model.complete(messages)
485
+
486
+ def _check_schema(self, response: dict) -> tuple[list[str], Any]:
487
+ """The ways the answer does not fit the schema, and the answer when it does."""
488
+ value, reason = schema.parse(text_of(response.get("content")))
489
+ if reason:
490
+ return [reason], None
491
+ errors = schema.validate(value, self.output_schema)
492
+ return errors, None if errors else value
493
+
494
+ def _verify(self, rounds: int) -> tuple[str, bool]:
495
+ """Run the commands that check the work.
496
+
497
+ Returns the message for the agent and whether the rounds are used up.
498
+ The message is empty when the work passes, or when there is nothing to
499
+ check.
500
+ """
501
+ if not self.verify or not self.verify.commands:
502
+ return "", False
503
+ failures = []
504
+ for command in self.verify.commands:
505
+ result = self._run_verify_command(command)
506
+ if result["returncode"] != 0:
507
+ failures.append(result)
508
+ self._publish(
509
+ EventType.VERIFY,
510
+ {
511
+ "commands": list(self.verify.commands),
512
+ "failed": [failure["command"] for failure in failures],
513
+ "round": rounds + 1,
514
+ },
515
+ )
516
+ if not failures:
517
+ return "", False
518
+ message = "\n\n".join(
519
+ [
520
+ "[verify] These commands did not pass. Fix the problem and try again.",
521
+ *[
522
+ f"$ {failure['command']}\n{failure['output']}\n[exit code {failure['returncode']}]"
523
+ for failure in failures
524
+ ],
525
+ ]
526
+ )
527
+ return message, rounds + 1 >= self.verify.max_rounds
528
+
529
+ def _run_verify_command(self, command: str) -> dict:
530
+ """Run one check in the environment of the session."""
531
+ from coderagent.tools.builtin.shell import CodingEnvironment
532
+
533
+ environment = self.sandbox or CodingEnvironment(cwd=str(self.session.cwd))
534
+ cwd = str(self.session.cwd) if is_local(environment) else ""
535
+ result = environment.execute({"command": command}, cwd=cwd, timeout=self.verify.timeout)
536
+ output = str(result.get("output", ""))
537
+ if result.get("exception_info"):
538
+ output = f"{output}\n{result['exception_info']}".strip()
539
+ return {
540
+ "command": command,
541
+ "output": trim_text(output, VERIFY_OUTPUT_TOKENS)[0],
542
+ "returncode": int(result.get("returncode", 0)),
543
+ }
544
+
545
+ def _bill(self, before: tuple[float, int]) -> tuple[float, int]:
546
+ """Put what the gateway spent on the bill of this session.
547
+
548
+ The gateway is shared by all the sessions of the process, the bill is not: a
549
+ session pays for its own calls only.
550
+ """
551
+ self.session.total_cost += self.model.total_cost - before[0]
552
+ self.session.total_tokens += self.model.total_tokens - before[1]
553
+ return (self.model.total_cost, self.model.total_tokens)
554
+
555
+ def _ceilings_hold(self) -> bool:
556
+ """Whether the ceilings of the session apply.
557
+
558
+ Bypass means the session runs until the work is done: the money, the tokens
559
+ and the number of the calls are not what stops it. The user stops it. A
560
+ harness that measures asks for the ceilings anyway.
561
+ """
562
+ return self.enforce_ceilings or self.policy.mode != PermissionMode.BYPASS
563
+
564
+ def _warn_unpriced(self, response: dict) -> None:
565
+ """A model without a price spends no money, so a cost limit cannot be enforced."""
566
+ if not self.cost_limit or self._warned_unpriced:
567
+ return
568
+ extra = response.get("extra") or {}
569
+ if extra.get("tokens_in") and not extra.get("cost"):
570
+ logger.warning(
571
+ "The model %s has no price, so the cost limit cannot be enforced. Use agent.token_limit instead.",
572
+ getattr(self.model.backend, "model_name", ""),
573
+ )
574
+ self._warned_unpriced = True
575
+
576
+ def _route(self) -> None:
577
+ """Pick the model of this turn. A change is announced in the event stream."""
578
+ if self.router is None:
579
+ return
580
+ name = self.router.resolve(self.purpose, self._routing_context())
581
+ if not name:
582
+ return
583
+ backend = self.router.backend_for(name)
584
+ current = getattr(self.model.backend, "model_name", "")
585
+ if backend.model_name == current:
586
+ """The same model behind another name. There is nothing to change."""
587
+ return
588
+ self.model.backend = backend
589
+ self._publish(
590
+ EventType.STATE_CHANGE,
591
+ {
592
+ "state": self.session.state.value,
593
+ "model": name,
594
+ "previous": current,
595
+ "reason": self._route_reason(),
596
+ },
597
+ )
598
+
599
+ def _routing_context(self) -> dict:
600
+ """What the router knows about the session."""
601
+ return {
602
+ "tokens": self.context.estimated_tokens(self.tools),
603
+ "turns": self.session.turn_count,
604
+ "calls": self.model.n_calls,
605
+ "cost": self.session.total_cost,
606
+ "budget": self.cost_limit,
607
+ "tokens_used": self.session.total_tokens,
608
+ "token_budget": self.token_limit,
609
+ }
610
+
611
+ def _route_reason(self) -> str:
612
+ """Why the model changed, in one line."""
613
+ return self.router.explain(self._routing_context())
614
+
615
+ def _stop_blocked(self, response: dict) -> bool:
616
+ """Ask the Stop hook whether the agent may stop. A blocked stop means: keep going."""
617
+ if not self.hooks:
618
+ return False
619
+ hook = self.hooks.apply("Stop", {"last_message": response.get("content", "")})
620
+ if not hook.blocked:
621
+ return False
622
+ self.context.append({"role": "user", "content": f"[hook] {hook.reason}"})
623
+ return True
624
+
625
+ def _session_start(self) -> None:
626
+ if self.hooks:
627
+ self.hooks.apply("SessionStart", {"session_id": self.session.id, "cwd": str(self.session.cwd)})
628
+
629
+ def _session_end(self) -> None:
630
+ if self.hooks:
631
+ self.hooks.apply(
632
+ "SessionEnd",
633
+ {"session_id": self.session.id, "turns": self.session.turn_count, "cost": self.session.total_cost},
634
+ )
635
+
636
+ def _export_trace(self) -> None:
637
+ """Send the spans of this turn to the backend, when there is one.
638
+
639
+ What the backend has seen is not sent again. A backend that is down is
640
+ a warning: the trace stays in the event log either way.
641
+ """
642
+ if self.exporter is None:
643
+ return
644
+ events = self.store.events(self.session.id)
645
+ fresh = events[self._exported :]
646
+ if not fresh:
647
+ return
648
+ payload = build_trace(fresh, self.session)
649
+ if not payload["resourceSpans"][0]["scopeSpans"][0]["spans"]:
650
+ self._exported = len(events)
651
+ return
652
+ if self.exporter.export(payload):
653
+ self._exported = len(events)
654
+
655
+ def _query(self) -> tuple[dict | None, str]:
656
+ """Ask the model. When the provider says the context is too big, compact and try once more."""
657
+ try:
658
+ return self._collect(), ""
659
+ except Interrupted:
660
+ """The turn was stopped: this is not an error of the provider."""
661
+ raise
662
+ except Exception as e:
663
+ if not is_context_overflow(e):
664
+ return None, f"{type(e).__name__}: {e}"
665
+ if not self.context.force_compact():
666
+ return None, f"{type(e).__name__}: {e} (nothing left to compact)"
667
+ try:
668
+ return self._collect(), ""
669
+ except Interrupted:
670
+ raise
671
+ except Exception as retry_error:
672
+ return None, f"{type(retry_error).__name__}: {retry_error}"
673
+
674
+ def _collect(self) -> dict:
675
+ """Read the answer as it arrives and fold it into one message."""
676
+ events = self.model.query_stream(self.context.build_messages(tools=self.tools), tools=self.tools)
677
+ return message_from_events(self._announce(events))
678
+
679
+ def _announce(self, events) -> Iterator[ModelEvent]:
680
+ """Publish the pieces of the answer, so the UI can show them while they arrive."""
681
+ for event in events:
682
+ if self.cancel is not None and self.cancel():
683
+ """The answer is cut short: the user does not wait for the rest of it."""
684
+ raise Interrupted()
685
+ if event.type == "text":
686
+ self._notify(EventType.TEXT_DELTA, {"content": event.content})
687
+ elif event.type == "reasoning":
688
+ self._notify(EventType.REASONING, {"content": event.content})
689
+ yield event
690
+
691
+ def _notify(self, event_type: EventType, payload: dict) -> None:
692
+ """Publish to the UI only. The event log keeps the whole messages."""
693
+ self.bus.publish(Event(type=event_type, session_id=self.session.id, timestamp=time.time(), payload=payload))
694
+
695
+ def _publish(self, event_type: EventType, payload: dict) -> None:
696
+ event = Event(type=event_type, session_id=self.session.id, timestamp=time.time(), payload=payload)
697
+ self.bus.publish(event)
698
+ self.store.append(self.session.id, event)
699
+
700
+ def _set_state(self, state: SessionState, **extra) -> None:
701
+ self.session.state = state
702
+ self._publish(EventType.STATE_CHANGE, {"state": state.value, **extra})