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,618 @@
1
+ """The context engine: assembles what the model sees and decides when to compact.
2
+
3
+ The order is fixed: the system prompt, the project instructions and the task list,
4
+ the summary of the compacted part, and then the history. The summary comes before
5
+ the history because it is the older part of the conversation.
6
+
7
+ The history holds everything since the last compaction. Compaction replaces the
8
+ older part of it with a structured summary, so nothing is ever dropped silently.
9
+ """
10
+
11
+ import json
12
+ import time
13
+ from functools import partial
14
+ from pathlib import Path
15
+
16
+ from coderagent.config.schema import ContextConfig, MemoryConfig
17
+ from coderagent.core.budget import BudgetGuard, context_window_for
18
+ from coderagent.core.events import Event, EventBus, EventType
19
+ from coderagent.core.history import History
20
+ from coderagent.core.instructions import InstructionBlock, load_instructions, once_per_file, subdirectory_instructions
21
+ from coderagent.core.memory import load_project_memory, load_user_memory
22
+ from coderagent.core.os_sandbox import sandbox_block
23
+ from coderagent.core.session import Session, SessionStore
24
+ from coderagent.core.summarize import (
25
+ COMPACTED_GOAL,
26
+ RECAP_GOAL,
27
+ Summary,
28
+ chunk_messages,
29
+ conservative_summary,
30
+ merge_prompt,
31
+ merge_summaries,
32
+ parse_summary,
33
+ recent_errors,
34
+ summarize_prompt,
35
+ )
36
+ from coderagent.core.tokens import estimate_tokens
37
+ from coderagent.tools.permissions import PermissionPolicy, mode_block, network_block
38
+
39
+ SUMMARY_OVERHEAD = 2000
40
+ """The tokens the prompt template and the answer of a summary take."""
41
+
42
+ MISSING_RESULT = "Error: the tool call was not finished: the session ended before its result was recorded."
43
+ """What a tool call that never came back says."""
44
+
45
+
46
+ def repair_tool_calls(messages: list[dict]) -> list[dict]:
47
+ """Give every tool call a result, even the ones that never came back.
48
+
49
+ A session that was killed between the answer of the model and the result of
50
+ a tool has a tool call without a result, and a provider refuses such a
51
+ history: the session could not be continued. The missing result is a tool
52
+ message that says the call was not finished.
53
+
54
+ The history itself is left as it is: the event log is the truth, and the
55
+ repair is what the model is shown.
56
+ """
57
+ repaired: list[dict] = []
58
+ index = 0
59
+ while index < len(messages):
60
+ message = messages[index]
61
+ repaired.append(message)
62
+ index += 1
63
+ calls = message.get("tool_calls") or []
64
+ if message.get("role") != "assistant" or not calls:
65
+ continue
66
+ group: list[dict] = []
67
+ while index < len(messages) and messages[index].get("role") == "tool":
68
+ group.append(messages[index])
69
+ index += 1
70
+ answered = {tool.get("tool_call_id"): tool for tool in group}
71
+ for call in calls:
72
+ repaired.append(answered.get(call.get("id")) or _missing_result(call))
73
+ known = {call.get("id") for call in calls}
74
+ repaired.extend(tool for tool in group if tool.get("tool_call_id") not in known)
75
+ return repaired
76
+
77
+
78
+ def _missing_result(call: dict) -> dict:
79
+ """The result of a tool call that was never finished."""
80
+ return {"role": "tool", "tool_call_id": call.get("id", ""), "content": MISSING_RESULT}
81
+
82
+
83
+ class ContextEngine:
84
+ def __init__(
85
+ self,
86
+ session: Session,
87
+ store: SessionStore,
88
+ bus: EventBus,
89
+ config: ContextConfig,
90
+ model,
91
+ *,
92
+ system_prompt: str = "",
93
+ instructions: list[InstructionBlock] | None = None,
94
+ memory_config: MemoryConfig | None = None,
95
+ summary_model=None,
96
+ cwd: Path | None = None,
97
+ user_home: Path | None = None,
98
+ policy: PermissionPolicy | None = None,
99
+ hooks=None,
100
+ ) -> None:
101
+ self.session = session
102
+ self.store = store
103
+ self.bus = bus
104
+ self.config = config
105
+ self.model = model
106
+ self.summary_model = summary_model or model
107
+ self.system_prompt = system_prompt
108
+ self.cwd = Path(cwd) if cwd else session.cwd
109
+ self.user_home = user_home
110
+ self.policy = policy
111
+ """The permission policy. It is shared, so the mode can change under us."""
112
+ self.hooks = hooks
113
+ """The hook runner, when the session has hooks."""
114
+ self.tools: list[dict] = []
115
+ """The schemas of the tools. They are part of every request, so they count."""
116
+ self.history = History()
117
+ self.summaries: list[Summary] = []
118
+ self.instruction_blocks: list[InstructionBlock] = list(instructions or [])
119
+ """The instructions of the subdirectories, and the ones the caller gave."""
120
+ self.reload_instructions = instructions is None
121
+ """Whether the instruction files are read again every round.
122
+
123
+ The project may change its AGENTS.md while the session runs, and then the
124
+ model has to see the new one.
125
+ """
126
+ self.memory_config = memory_config or MemoryConfig()
127
+ self.ephemeral: list[tuple[dict, str]] = []
128
+ """The messages that do not stay in the context, and the note that replaces them."""
129
+ self.guard = BudgetGuard(
130
+ context_window=config.context_window,
131
+ reserved_output=config.reserved_output,
132
+ compact_threshold=config.compact_threshold,
133
+ )
134
+ self.last_compact_turn = 0
135
+
136
+ @property
137
+ def summary(self) -> Summary | None:
138
+ """The most recent summary. Older ones are kept as well."""
139
+ return self.summaries[-1] if self.summaries else None
140
+
141
+ # -- history ---------------------------------------------------------
142
+
143
+ def restore(self) -> None:
144
+ """Rebuild the history and the summaries from the event log."""
145
+ messages: list[dict] = []
146
+ summaries: list[Summary] = []
147
+ for event in self.store.events(self.session.id):
148
+ payload = event.payload
149
+ if event.type == EventType.USER_MESSAGE:
150
+ messages.append({"role": "user", "content": payload.get("content", "")})
151
+ elif event.type == EventType.ASSISTANT_MESSAGE:
152
+ messages.append(payload.get("message", {}))
153
+ elif event.type == EventType.TOOL_RESULT:
154
+ messages.extend(payload.get("messages", []))
155
+ elif event.type == EventType.COMPACTION:
156
+ messages = messages[payload.get("compacted_messages", 0) :]
157
+ summaries = [Summary.from_dict(item) for item in payload.get("summaries", [])]
158
+ self.last_compact_turn = int(payload.get("turn", 0))
159
+ """The turn of the last compaction. Without it a restored session
160
+ compacts again right away, or never at all."""
161
+ elif event.type == EventType.REVERTED:
162
+ messages = messages[: payload.get("messages", len(messages))]
163
+ self.history = History(messages)
164
+ self.summaries = summaries
165
+
166
+ def append(self, message: dict, original: str = "", ephemeral: str = "") -> None:
167
+ """Add a message to the history and record it in the event log.
168
+
169
+ `original` is what the user typed, when a hook rewrote the prompt. The
170
+ log keeps the prompt the model saw, so that a replay says the same
171
+ thing, and the original beside it.
172
+
173
+ `ephemeral` is a note that takes the place of the message when the turn
174
+ is over: a diff that is read once does not have to stay in the context.
175
+ """
176
+ self.history.append(message)
177
+ self._record(message, original, ephemeral)
178
+ if ephemeral:
179
+ self.ephemeral.append((message, ephemeral))
180
+
181
+ def forget_ephemeral(self) -> None:
182
+ """The ephemeral messages are replaced by their note.
183
+
184
+ The message itself stays in the history: the turn that follows it still
185
+ knows that it happened, only its bulk is gone.
186
+ """
187
+ for message, note in self.ephemeral:
188
+ message["content"] = note
189
+ self.ephemeral.clear()
190
+
191
+ def extend(self, messages: list[dict]) -> None:
192
+ """Add tool results to the history and record them in the event log."""
193
+ self.history.extend(messages)
194
+ for message in messages:
195
+ self._record(message)
196
+
197
+ def _record(self, message: dict, original: str = "", ephemeral: str = "") -> None:
198
+ """The event log is the source of truth, so every message goes into it."""
199
+ role = message.get("role")
200
+ if role == "user":
201
+ event_type = EventType.USER_MESSAGE
202
+ payload = {"content": ephemeral or message.get("content", "")}
203
+ if original:
204
+ payload["original"] = original
205
+ elif role == "assistant":
206
+ event_type = EventType.ASSISTANT_MESSAGE
207
+ payload = {"message": message, "cost": message.get("extra", {}).get("cost", 0.0)}
208
+ elif role == "tool":
209
+ event_type = EventType.TOOL_RESULT
210
+ payload = {"messages": [message], "todos": self.session.metadata.get("todos", [])}
211
+ else:
212
+ return
213
+ event = Event(type=event_type, session_id=self.session.id, timestamp=time.time(), payload=payload)
214
+ self.bus.publish(event)
215
+ self.store.append(self.session.id, event)
216
+
217
+ # -- assembly --------------------------------------------------------
218
+
219
+ def build_messages(self, *, tools: list[dict] | None = None) -> list[dict]:
220
+ """The messages to send to the model."""
221
+ return self._prefix_messages() + repair_tool_calls(self.history.messages)
222
+
223
+ def _prefix_messages(self) -> list[dict]:
224
+ """The part of the context that is the same for every request.
225
+
226
+ The system prompt, the mode, the instructions, the memory and the summary.
227
+ The history is not in here: it is the part that grows and that is compacted.
228
+ """
229
+ messages = []
230
+ if self.system_prompt:
231
+ messages.append({"role": "system", "content": self.system_prompt})
232
+ mode = self._policy_text()
233
+ if mode:
234
+ messages.append({"role": "user", "content": mode})
235
+ instructions = self._instruction_text()
236
+ if instructions:
237
+ messages.append({"role": "user", "content": instructions})
238
+ summary = self._summary_text()
239
+ if summary:
240
+ messages.append({"role": "user", "content": summary})
241
+ return messages
242
+
243
+ def _policy_text(self) -> str:
244
+ """What the model is told when the permissions take something away from it.
245
+
246
+ The mode and the network change while the session runs, so this is read
247
+ every time the messages are built and never baked into the system prompt.
248
+ """
249
+ if self.policy is None:
250
+ return ""
251
+ return "\n\n".join(
252
+ text
253
+ for text in (
254
+ mode_block(self.policy.mode),
255
+ network_block(self.policy.network),
256
+ sandbox_block(self.policy.sandbox_mode),
257
+ )
258
+ if text
259
+ )
260
+
261
+ def estimated_tokens(self, tools: list[dict] | None = None) -> int:
262
+ """The size of the whole context. This is what the budget is checked against.
263
+
264
+ The schemas of the tools are part of every request, so they count: without
265
+ them a session with many tools looks smaller than it is.
266
+ """
267
+ schemas = self.tools if tools is None else tools
268
+ return estimate_tokens(self.build_messages(), schemas)
269
+
270
+ def _instruction_text(self) -> str:
271
+ """The instructions and the memory, one block per file.
272
+
273
+ Every file is read once and cut short when it is too long: the file of
274
+ the user is both an instruction and a memory, and the instructions of
275
+ the repository are read before the ones of the directory.
276
+ """
277
+ blocks = list(self.instruction_blocks)
278
+ if self.reload_instructions:
279
+ """The instruction files are read again, so a change of the project counts."""
280
+ blocks = load_instructions(self.cwd, self.user_home, self.config.project_doc_max_bytes) + blocks
281
+ if self.memory_config.enabled:
282
+ blocks += load_project_memory(self.cwd, self.memory_config, self.config.project_doc_max_bytes)
283
+ user_memory = load_user_memory(self.memory_config, self.user_home, self.config.project_doc_max_bytes)
284
+ if user_memory and user_memory.path not in {block.path for block in blocks}:
285
+ blocks.append(user_memory)
286
+ todos = self.session.metadata.get("todos") or []
287
+ parts = [block.render() for block in once_per_file(blocks)]
288
+ if todos:
289
+ lines = [
290
+ f"- [{'x' if todo.get('status') == 'completed' else ' '}] {todo.get('content', '')}" for todo in todos
291
+ ]
292
+ parts.append("<current_todos>\n" + "\n".join(lines) + "\n</current_todos>")
293
+ return "\n\n".join(parts)
294
+
295
+ def _summary_text(self) -> str:
296
+ if not self.summaries:
297
+ return ""
298
+ if len(self.summaries) == 1:
299
+ return self.summaries[0].render()
300
+ parts = [summary.render() for summary in self.summaries]
301
+ return "\n\n".join(parts)
302
+
303
+ # -- compaction ------------------------------------------------------
304
+
305
+ def maybe_compact(self) -> bool:
306
+ """Compact when the context is close to the limit. Returns whether it happened."""
307
+ if not self.config.auto_compact:
308
+ return False
309
+ if self.guard.should_compact(self.estimated_tokens()):
310
+ return self.compact()
311
+ if (
312
+ self.config.compact_every_turns
313
+ and self.session.turn_count - self.last_compact_turn > self.config.compact_every_turns
314
+ ):
315
+ return self.compact()
316
+ return False
317
+
318
+ def force_compact(self) -> bool:
319
+ """Compact regardless of the budget. Used when the provider says the context is too big."""
320
+ return self.compact(force=True)
321
+
322
+ def compact(self, force: bool = False) -> bool:
323
+ """Replace the older part of the history with a summary.
324
+
325
+ `force` says that the provider refused the context: then only the last turn
326
+ is kept, whatever the rules say. A session that forgets is worth more than a
327
+ session that cannot continue.
328
+ """
329
+ cut = self._cut_index(force=force)
330
+ if cut <= 0:
331
+ return False
332
+ compacted = self.history.messages[:cut]
333
+ if self.hooks:
334
+ """The hooks see what is about to be compressed, and then the summary."""
335
+ self.hooks.apply("PreCompact", {"messages": compacted, "turn": self.session.turn_count})
336
+ before = getattr(self.summary_model, "total_cost", 0.0)
337
+ summary = self._summarize(compacted)
338
+ cost = getattr(self.summary_model, "total_cost", 0.0) - before
339
+ if self.summary_model is not self.model:
340
+ """The summary ran on its own model, so its cost is booked on the main one."""
341
+ self.model.total_cost = getattr(self.model, "total_cost", 0.0) + cost
342
+ self.summaries = [summary]
343
+ self.history.messages = self.history.messages[cut:]
344
+ self.last_compact_turn = self.session.turn_count
345
+ source_tokens = estimate_tokens(compacted)
346
+ summary_tokens = estimate_tokens([{"role": "user", "content": summary.render()}])
347
+ if self.hooks:
348
+ self.hooks.apply(
349
+ "PostCompact",
350
+ {
351
+ "summary": summary.render(),
352
+ "messages": cut,
353
+ "tokens": source_tokens,
354
+ "summary_tokens": summary_tokens,
355
+ },
356
+ )
357
+ event = Event(
358
+ type=EventType.COMPACTION,
359
+ session_id=self.session.id,
360
+ timestamp=time.time(),
361
+ payload={
362
+ "compacted_messages": cut,
363
+ "turn": self.session.turn_count,
364
+ "tokens": source_tokens,
365
+ "summary_tokens": summary_tokens,
366
+ "summary_ratio": round(summary_tokens / source_tokens, 4) if source_tokens else 0.0,
367
+ "cost": cost,
368
+ "summary": summary.to_dict(),
369
+ "summaries": [item.to_dict() for item in self.summaries],
370
+ },
371
+ )
372
+ self.bus.publish(event)
373
+ self.store.append(self.session.id, event)
374
+ return True
375
+
376
+ def recap(self) -> Summary | None:
377
+ """Summarize the conversation without changing it.
378
+
379
+ Nothing is dropped and the summary does not go into the context of the
380
+ model: it is a report for the user to read. None when there is nothing
381
+ to summarize.
382
+ """
383
+ messages = self.history.messages
384
+ if not messages:
385
+ return None
386
+ before = getattr(self.summary_model, "total_cost", 0.0)
387
+ summary = self._summarize(messages, compacted=False)
388
+ cost = getattr(self.summary_model, "total_cost", 0.0) - before
389
+ if self.summary_model is not self.model:
390
+ """The summary ran on its own model, so its cost is booked on the main one."""
391
+ self.model.total_cost = getattr(self.model, "total_cost", 0.0) + cost
392
+ self.session.total_cost += cost
393
+ """The recap is not part of a turn, so its cost is added to the session here."""
394
+ event = Event(
395
+ type=EventType.RECAP,
396
+ session_id=self.session.id,
397
+ timestamp=time.time(),
398
+ payload={
399
+ "summary": summary.to_dict(),
400
+ "text": summary.to_text(),
401
+ "tokens": estimate_tokens(messages),
402
+ "cost": cost,
403
+ },
404
+ )
405
+ self.bus.publish(event)
406
+ self.store.append(self.session.id, event)
407
+ return summary
408
+
409
+ def _cut_index(self, force: bool = False) -> int:
410
+ """Where the kept window starts. A turn boundary, unless the last turn does
411
+ not fit on its own.
412
+
413
+ Two rules decide how much is kept: the last `keep_recent_turns` turns, and
414
+ enough tokens to fill `keep_recent_token_ratio` of the context window. The
415
+ larger of the two wins, so a few huge turns are kept as well as many small ones.
416
+
417
+ The kept window also has to fit into the target, so it is cut further when it
418
+ does not: on a turn boundary first, and inside the last turn when even that
419
+ is not enough. `keep_recent_turns` is therefore a target, not a promise: a
420
+ session that is too big is compacted even in its first turns.
421
+
422
+ `force` says that the provider refused the context: then only the last turn
423
+ is kept, and inside it what still does not fit.
424
+ """
425
+ messages = self.history.messages
426
+ starts = self.history.turn_starts()
427
+ if not starts:
428
+ return 0
429
+ candidates = [0, *starts]
430
+ earliest = starts[max(0, len(starts) - self.config.keep_recent_turns)]
431
+ target = self.guard.target() - estimate_tokens(self._prefix_messages()) - estimate_tokens([], self.tools)
432
+ """The fixed part of the request and the schemas of the tools are in every
433
+ request, so the kept window only gets what is left of the budget."""
434
+ if force:
435
+ """The provider refused the context: only the last turn is kept."""
436
+ cut = starts[-1]
437
+ return cut if estimate_tokens(messages[cut:]) <= target else _inside_cut(messages, cut, target)
438
+ budget = int(self.config.context_window * self.config.keep_recent_token_ratio)
439
+ cut = earliest
440
+ for index in candidates:
441
+ if index <= earliest and estimate_tokens(messages[index:]) >= budget:
442
+ cut = index
443
+ while cut < len(messages) and estimate_tokens(messages[cut:]) > target:
444
+ later = [index for index in candidates if index > cut]
445
+ if not later:
446
+ """Even the last turn does not fit: cut inside it."""
447
+ cut = _inside_cut(messages, cut, target)
448
+ break
449
+ cut = later[0]
450
+ return cut
451
+
452
+ def _summarize(self, messages: list[dict], compacted: bool = True) -> Summary:
453
+ """Summarize the compacted part.
454
+
455
+ A history that does not fit into one prompt is summarized in chunks, and
456
+ the partial summaries are merged into one. The previous summary goes in
457
+ as well, so that a second compaction does not lose what the first one found.
458
+
459
+ `compacted` says whether the messages are about to be dropped: a recap
460
+ keeps them, so it must not claim that they are gone.
461
+ """
462
+ previous = self.summaries[-1] if self.summaries else None
463
+ goal = COMPACTED_GOAL if compacted else RECAP_GOAL
464
+ chunks = chunk_messages(messages, self._summary_limit())
465
+ if len(chunks) <= 1:
466
+ payload = list(chunks[0]) if chunks else []
467
+ asked = payload + [{"role": "user", "content": previous.render()}] if previous else payload
468
+ summary = self._ask(summarize_prompt, asked, _written_files(messages)) or _fallback(payload, previous, goal)
469
+ else:
470
+ parts = [
471
+ self._ask(summarize_prompt, chunk, _written_files(chunk)) or conservative_summary(chunk, goal)
472
+ for chunk in chunks
473
+ ]
474
+ summary = self._ask(
475
+ partial(merge_prompt, previous=self._summary_text()), parts, _written_files(messages)
476
+ ) or (merge_summaries([previous, *parts] if previous else parts))
477
+ summary.recent_errors = recent_errors(messages)
478
+ return summary
479
+
480
+ def _ask(self, prompt, payload, files: list[str]) -> Summary | None:
481
+ """Ask the model for a summary. None when it does not deliver a usable one.
482
+
483
+ A summary that does not name the files that were touched is not thrown
484
+ away: the files are added from the messages, which know the truth. A bad
485
+ day of the summarizer must not wipe the memory of the session.
486
+ """
487
+ usable: Summary | None = None
488
+ for _ in range(2):
489
+ try:
490
+ text = self.summary_model.complete([{"role": "user", "content": prompt(payload)}])
491
+ except Exception:
492
+ continue
493
+ summary = parse_summary(text)
494
+ if summary is None:
495
+ continue
496
+ if summary.files_touched or not files:
497
+ return summary
498
+ if summary.goal or summary.findings:
499
+ usable = summary
500
+ if usable is None:
501
+ return None
502
+ usable.files_touched = [
503
+ {"path": path, "change": "the change is not described any more", "state": "modified"} for path in files
504
+ ]
505
+ return usable
506
+
507
+ def _summary_limit(self) -> int:
508
+ """How many tokens the summarizer may take in one prompt."""
509
+ if self.config.summary_chunk_tokens:
510
+ return self.config.summary_chunk_tokens
511
+ window = self.config.context_window
512
+ name = getattr(getattr(self.summary_model, "backend", None), "model_name", "")
513
+ if name:
514
+ window = context_window_for(name, default=window)
515
+ return max(1000, window - self.config.reserved_output - SUMMARY_OVERHEAD)
516
+
517
+ def rewind_to(self, messages: int) -> int:
518
+ """Drop the messages after a checkpoint. Returns how many were dropped."""
519
+ messages = max(0, min(messages, len(self.history.messages)))
520
+ dropped = len(self.history.messages) - messages
521
+ self.history.messages = self.history.messages[:messages]
522
+ event = Event(
523
+ type=EventType.REVERTED,
524
+ session_id=self.session.id,
525
+ timestamp=time.time(),
526
+ payload={"messages": messages},
527
+ )
528
+ self.bus.publish(event)
529
+ self.store.append(self.session.id, event)
530
+ return dropped
531
+
532
+ def note_path(self, path: str) -> None:
533
+ """Remember the instruction files of a directory the agent just touched."""
534
+ if not path:
535
+ return
536
+ target = Path(path)
537
+ if not target.is_absolute():
538
+ target = self.cwd / target
539
+ known = {block.path for block in self.instruction_blocks}
540
+ for block in subdirectory_instructions(target, self.cwd, self.config.project_doc_max_bytes):
541
+ if block.path not in known:
542
+ self.instruction_blocks.append(block)
543
+ known.add(block.path)
544
+
545
+
546
+ def _inside_cut(messages: list[dict], cut: int, limit: int) -> int:
547
+ """A cut inside the last turn, for when even that turn does not fit.
548
+
549
+ The kept window starts with an assistant message: the tool calls whose results
550
+ are cut away are repaired before the model sees them. When no cut inside the
551
+ turn fits, the earliest one is used: the rest is dropped, the window is still
552
+ too big, and the caller says so.
553
+ """
554
+ inside = [index for index in range(cut + 1, len(messages)) if messages[index].get("role") == "assistant"]
555
+ if not inside:
556
+ return cut
557
+ sizes = _suffix_sizes(messages)
558
+ for index in reversed(inside):
559
+ if sizes[index] <= limit:
560
+ return index
561
+ return inside[0]
562
+
563
+
564
+ def _suffix_sizes(messages: list[dict]) -> list[int]:
565
+ """The tokens of every suffix of the history."""
566
+ sizes = [0] * (len(messages) + 1)
567
+ for index in range(len(messages) - 1, -1, -1):
568
+ sizes[index] = sizes[index + 1] + estimate_tokens([messages[index]])
569
+ return sizes
570
+
571
+
572
+ def _fallback(payload: list[dict], previous: Summary | None, goal: str) -> Summary:
573
+ """The summary when the model does not deliver one.
574
+
575
+ The previous summary is kept whole: the summarizer had a bad day, the memory
576
+ of the session does not go with it.
577
+ """
578
+ conservative = conservative_summary(payload, goal)
579
+ return merge_summaries([previous, conservative]) if previous else conservative
580
+
581
+
582
+ def _written_files(messages: list[dict]) -> list[str]:
583
+ """The files the messages changed. The truth about the files, not a guess."""
584
+ paths = []
585
+ for message in messages:
586
+ for call in message.get("tool_calls") or []:
587
+ function = call.get("function") or {}
588
+ name = function.get("name")
589
+ if name not in ("write", "edit", "multi_edit", "apply_patch"):
590
+ continue
591
+ arguments = _arguments(function.get("arguments"))
592
+ if name == "apply_patch":
593
+ paths.extend(_patch_files(str(arguments.get("patch") or "")))
594
+ continue
595
+ path = arguments.get("path")
596
+ if path:
597
+ paths.append(str(path))
598
+ return paths
599
+
600
+
601
+ def _arguments(arguments) -> dict:
602
+ """The arguments of a tool call. Empty when they cannot be read."""
603
+ if isinstance(arguments, str):
604
+ try:
605
+ arguments = json.loads(arguments or "{}")
606
+ except json.JSONDecodeError:
607
+ return {}
608
+ return arguments if isinstance(arguments, dict) else {}
609
+
610
+
611
+ def _patch_files(text: str) -> list[str]:
612
+ """The files a patch touches."""
613
+ from coderagent.tools.builtin.patch import PatchError, parse_patch
614
+
615
+ try:
616
+ return [patch.path for patch in parse_patch(text)]
617
+ except PatchError:
618
+ return []