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,312 @@
1
+ """Structured summaries of the part of a conversation that no longer fits in the window.
2
+
3
+ The summary is a fixed set of fields rather than free text: a model that has to
4
+ remember "what is still open" in a JSON structure keeps it better than in prose.
5
+ """
6
+
7
+ import json
8
+ import re
9
+ from dataclasses import dataclass, field
10
+ from typing import Any
11
+
12
+ from coderagent.core.content import text_of
13
+ from coderagent.core.tokens import estimate_tokens
14
+
15
+ FIELDS = ("goal", "findings", "decisions", "files_touched", "open_questions", "next_steps", "errors_seen")
16
+ CONSERVATIVE_MESSAGES = 5
17
+
18
+ SCHEMA = """{
19
+ "goal": "one sentence: what the user is trying to achieve",
20
+ "findings": ["facts you confirmed, each with file:line when it comes from the code"],
21
+ "decisions": ["technical decisions that were made and why"],
22
+ "files_touched": [{"path": "src/cache.py", "change": "what changed", "state": "modified"}],
23
+ "open_questions": ["questions that are still unanswered"],
24
+ "next_steps": ["the concrete next steps"],
25
+ "errors_seen": ["errors that were hit and how they were resolved"]
26
+ }"""
27
+
28
+ PROMPT = """You are summarizing a coding session so that it can continue after the original messages are dropped.
29
+
30
+ Answer with a single JSON object and nothing else. Use exactly these keys, and use [] for a key you have nothing for:
31
+ {schema}
32
+
33
+ The conversation to summarize:
34
+ """
35
+
36
+ MERGE_PROMPT = """You are merging the partial summaries of a coding session into one summary.
37
+
38
+ Answer with a single JSON object and nothing else. Use exactly these keys, and use [] for a key you have nothing for:
39
+ {schema}
40
+
41
+ Keep every fact that is still true. The partial summaries are in the order of the
42
+ conversation, so the later ones describe the newer state of the work.
43
+
44
+ The partial summaries:
45
+ """
46
+
47
+
48
+ @dataclass
49
+ class Summary:
50
+ goal: str = ""
51
+ findings: list[str] = field(default_factory=list)
52
+ decisions: list[str] = field(default_factory=list)
53
+ files_touched: list[dict] = field(default_factory=list)
54
+ open_questions: list[str] = field(default_factory=list)
55
+ next_steps: list[str] = field(default_factory=list)
56
+ errors_seen: list[str] = field(default_factory=list)
57
+ recent_errors: list[str] = field(default_factory=list)
58
+ """Tool errors from the compacted part. Derived from the messages, not from the model."""
59
+
60
+ @classmethod
61
+ def from_dict(cls, data: dict[str, Any]) -> "Summary":
62
+ def entries(key: str) -> list:
63
+ value = data.get(key)
64
+ return list(value) if isinstance(value, list) else []
65
+
66
+ goal = data.get("goal")
67
+ return cls(
68
+ goal=goal if isinstance(goal, str) else "",
69
+ findings=[str(item) for item in entries("findings")],
70
+ decisions=[str(item) for item in entries("decisions")],
71
+ files_touched=[item for item in entries("files_touched") if isinstance(item, dict)],
72
+ open_questions=[str(item) for item in entries("open_questions")],
73
+ next_steps=[str(item) for item in entries("next_steps")],
74
+ errors_seen=[str(item) for item in entries("errors_seen")],
75
+ )
76
+
77
+ def to_dict(self) -> dict[str, Any]:
78
+ return {
79
+ "goal": self.goal,
80
+ "findings": self.findings,
81
+ "decisions": self.decisions,
82
+ "files_touched": self.files_touched,
83
+ "open_questions": self.open_questions,
84
+ "next_steps": self.next_steps,
85
+ "errors_seen": self.errors_seen,
86
+ }
87
+
88
+ def to_text(self) -> str:
89
+ """The summary as plain text, for the user to read."""
90
+ lines = []
91
+ if self.goal:
92
+ lines.append(f"goal: {self.goal}")
93
+ for label, items in (
94
+ ("findings", self.findings),
95
+ ("decisions", self.decisions),
96
+ ("open_questions", self.open_questions),
97
+ ("next_steps", self.next_steps),
98
+ ("errors_seen", self.errors_seen),
99
+ ):
100
+ if items:
101
+ lines.append(f"{label}:")
102
+ lines += [f"- {item}" for item in items]
103
+ if self.files_touched:
104
+ lines.append("files_touched:")
105
+ lines += [
106
+ f"- {item.get('path', '?')} ({item.get('state', 'modified')}): {item.get('change', '')}"
107
+ for item in self.files_touched
108
+ ]
109
+ if self.recent_errors:
110
+ lines.append("recent_errors:")
111
+ lines += [f"- {item}" for item in self.recent_errors]
112
+ return "\n".join(lines)
113
+
114
+ def render(self) -> str:
115
+ lines = [
116
+ "<session_summary>",
117
+ "The earlier part of this conversation was compacted. Keep these facts and continue the work.",
118
+ "",
119
+ f"goal: {self.goal}",
120
+ "findings:",
121
+ *[f"- {item}" for item in self.findings],
122
+ "decisions:",
123
+ *[f"- {item}" for item in self.decisions],
124
+ "files_touched:",
125
+ *[
126
+ f"- {item.get('path', '?')} ({item.get('state', 'modified')}): {item.get('change', '')}"
127
+ for item in self.files_touched
128
+ ],
129
+ "open_questions:",
130
+ *[f"- {item}" for item in self.open_questions],
131
+ "next_steps:",
132
+ *[f"- {item}" for item in self.next_steps],
133
+ "errors_seen:",
134
+ *[f"- {item}" for item in self.errors_seen],
135
+ ]
136
+ if self.recent_errors:
137
+ lines += ["recent_errors:", *[f"- {item}" for item in self.recent_errors]]
138
+ lines.append("</session_summary>")
139
+ return "\n".join(lines)
140
+
141
+
142
+ def parse_summary(text: str) -> Summary | None:
143
+ """Parse the model's answer. Returns None when it is not usable."""
144
+ if not text:
145
+ return None
146
+ cleaned = re.sub(r"^```(?:json)?|```$", "", text.strip(), flags=re.MULTILINE).strip()
147
+ start, end = cleaned.find("{"), cleaned.rfind("}")
148
+ if start == -1 or end <= start:
149
+ return None
150
+ try:
151
+ data = json.loads(cleaned[start : end + 1])
152
+ except json.JSONDecodeError:
153
+ return None
154
+ if not isinstance(data, dict):
155
+ return None
156
+ return Summary.from_dict(data)
157
+
158
+
159
+ def summarize_prompt(messages: list[dict]) -> str:
160
+ """The prompt that asks the model for the summary."""
161
+ transcript = []
162
+ for message in messages:
163
+ role = message.get("role", "?")
164
+ content = text_of(message.get("content"))
165
+ for call in message.get("tool_calls") or []:
166
+ function = call.get("function") or {}
167
+ content += f"\n[tool call {function.get('name', '?')}: {function.get('arguments', '')}]"
168
+ transcript.append(f"{role}: {content}")
169
+ return PROMPT.format(schema=SCHEMA) + "\n\n".join(transcript)
170
+
171
+
172
+ def merge_prompt(summaries: list["Summary"], previous: str = "") -> str:
173
+ """The prompt that asks the model to merge the partial summaries into one."""
174
+ parts = [summary.to_dict() for summary in summaries]
175
+ text = MERGE_PROMPT.format(schema=SCHEMA)
176
+ if previous:
177
+ text += f"\nThe summary of the part that was compacted before:\n{previous}\n"
178
+ return text + json.dumps(parts, ensure_ascii=False, indent=2)
179
+
180
+
181
+ def chunk_messages(messages: list[dict], max_tokens: int) -> list[list[dict]]:
182
+ """Split the messages into chunks that each fit into one summarizer prompt.
183
+
184
+ A turn is never split in two, so a tool result keeps the assistant message
185
+ that asked for it. A turn that is bigger than the limit on its own is split
186
+ at message boundaries, because there is nothing else to do.
187
+ """
188
+ chunks: list[list[dict]] = []
189
+ current: list[dict] = []
190
+ used = 0
191
+ for turn in _turns(messages):
192
+ for part in _split_oversized(turn, max_tokens):
193
+ size = estimate_tokens(part)
194
+ if current and used + size > max_tokens:
195
+ chunks.append(current)
196
+ current = []
197
+ used = 0
198
+ current.extend(part)
199
+ used += size
200
+ if current:
201
+ chunks.append(current)
202
+ return chunks
203
+
204
+
205
+ def merge_summaries(summaries: list["Summary"]) -> "Summary":
206
+ """Merge the summaries of the parts into one, without losing anything.
207
+
208
+ The fallback of the merging: no model, no loss, but the result grows with
209
+ the number of the parts.
210
+ """
211
+ goal = ""
212
+ findings: list[str] = []
213
+ decisions: list[str] = []
214
+ open_questions: list[str] = []
215
+ next_steps: list[str] = []
216
+ errors_seen: list[str] = []
217
+ files: dict[str, dict] = {}
218
+ for summary in summaries:
219
+ if summary.goal:
220
+ goal = summary.goal
221
+ findings += summary.findings
222
+ decisions += summary.decisions
223
+ open_questions += summary.open_questions
224
+ next_steps += summary.next_steps
225
+ errors_seen += summary.errors_seen
226
+ for index, item in enumerate(summary.files_touched):
227
+ files[str(item.get("path") or f"#{index}")] = item
228
+ return Summary(
229
+ goal=goal,
230
+ findings=_unique(findings),
231
+ decisions=_unique(decisions),
232
+ files_touched=list(files.values()),
233
+ open_questions=_unique(open_questions),
234
+ next_steps=_unique(next_steps),
235
+ errors_seen=_unique(errors_seen),
236
+ )
237
+
238
+
239
+ def _turns(messages: list[dict]) -> list[list[dict]]:
240
+ """The messages of the conversation, one list per turn."""
241
+ turns: list[list[dict]] = []
242
+ current: list[dict] = []
243
+ for message in messages:
244
+ if message.get("role") == "user" and current:
245
+ turns.append(current)
246
+ current = []
247
+ current.append(message)
248
+ if current:
249
+ turns.append(current)
250
+ return turns
251
+
252
+
253
+ def _split_oversized(turn: list[dict], max_tokens: int) -> list[list[dict]]:
254
+ """Split a turn that does not fit into one prompt."""
255
+ if estimate_tokens(turn) <= max_tokens:
256
+ return [turn]
257
+ parts: list[list[dict]] = []
258
+ current: list[dict] = []
259
+ used = 0
260
+ for message in turn:
261
+ size = estimate_tokens([message])
262
+ if current and used + size > max_tokens:
263
+ parts.append(current)
264
+ current = []
265
+ used = 0
266
+ current.append(message)
267
+ used += size
268
+ if current:
269
+ parts.append(current)
270
+ return parts
271
+
272
+
273
+ def _unique(items: list[str]) -> list[str]:
274
+ """The items without the duplicates, in the order they came in."""
275
+ seen = set()
276
+ result = []
277
+ for item in items:
278
+ if item not in seen:
279
+ seen.add(item)
280
+ result.append(item)
281
+ return result
282
+
283
+
284
+ COMPACTED_GOAL = "the earlier part of the conversation was compacted"
285
+ """What a summary says when the messages it replaces are gone."""
286
+
287
+ RECAP_GOAL = "a recap of the conversation so far"
288
+ """What a summary says when the messages are still there."""
289
+
290
+
291
+ def conservative_summary(messages: list[dict], goal: str = COMPACTED_GOAL) -> Summary:
292
+ """Fallback when the model does not return a usable summary."""
293
+ findings = []
294
+ for message in messages[-CONSERVATIVE_MESSAGES:]:
295
+ content = text_of(message.get("content")).strip()
296
+ if content:
297
+ findings.append(f"{message.get('role', '?')}: {content[:400]}")
298
+ return Summary(
299
+ goal=goal,
300
+ findings=findings,
301
+ next_steps=["re-read the files that were mentioned to recover the details"],
302
+ )
303
+
304
+
305
+ def recent_errors(messages: list[dict], limit: int = 3) -> list[str]:
306
+ """The last few tool errors, so they do not get lost in the compaction."""
307
+ errors = []
308
+ for message in messages:
309
+ content = text_of(message.get("content"))
310
+ if message.get("role") == "tool" and content.startswith("Error:"):
311
+ errors.append(content[:300])
312
+ return errors[-limit:]
@@ -0,0 +1,209 @@
1
+ """The trace of a session: what happened, what it cost and where the money went.
2
+
3
+ The event log is the source of truth, so the trace is built from it. The format
4
+ of the trace is `coder-agent-1.0`, next to the `mini-swe-agent-1.1` of
5
+ mini-swe-agent.
6
+ """
7
+
8
+ import json
9
+ from dataclasses import asdict, dataclass, field
10
+ from typing import Any
11
+
12
+ from coderagent.core.events import Event, EventType
13
+
14
+ TRACE_FORMAT = "coder-agent-1.0"
15
+
16
+
17
+ def money(cost: float, priced: bool = True) -> str:
18
+ """The money of a session, as the user sees it.
19
+
20
+ A model without a price has no money: the cost of such a model is unknown,
21
+ not zero. Saying `$0.0000` would be a lie.
22
+ """
23
+ return f"${cost:.4f}" if priced else "$?"
24
+
25
+
26
+ @dataclass
27
+ class Metrics:
28
+ """What a session cost and how it went."""
29
+
30
+ total_cost: float = 0.0
31
+ priced: bool = True
32
+ """False when a model of the session had no price. The money is unknown, not zero."""
33
+ total_tokens_in: int = 0
34
+ total_tokens_out: int = 0
35
+ model_calls: int = 0
36
+ tool_calls: int = 0
37
+ per_tool: dict[str, int] = field(default_factory=dict)
38
+ per_purpose_cost: dict[str, float] = field(default_factory=dict)
39
+ per_model_cost: dict[str, float] = field(default_factory=dict)
40
+ duration_seconds: float = 0.0
41
+ compactions: int = 0
42
+ summary_ratios: list[float] = field(default_factory=list)
43
+ """How much of the compacted history each summary kept. One number per compaction."""
44
+ errors: int = 0
45
+
46
+ def to_dict(self) -> dict[str, Any]:
47
+ return asdict(self)
48
+
49
+ def report(self) -> str:
50
+ """The cost of the session, as a report the user can read."""
51
+ return "\n".join([*self.summary(), *self.attribution()])
52
+
53
+ def summary(self) -> list[str]:
54
+ return [
55
+ f"cost: {money(self.total_cost, self.priced)}",
56
+ f"tokens: {self.total_tokens_in} in, {self.total_tokens_out} out",
57
+ f"model calls: {self.model_calls}",
58
+ f"tool calls: {self.tool_calls}",
59
+ f"duration: {self.duration_seconds:.1f}s",
60
+ ]
61
+
62
+ def attribution(self) -> list[str]:
63
+ """Where the money went."""
64
+ lines = []
65
+ if self.per_purpose_cost:
66
+ lines.append("by purpose:")
67
+ lines += [
68
+ f" {purpose:<12} {money(cost, self.priced)}" for purpose, cost in sorted(self.per_purpose_cost.items())
69
+ ]
70
+ if self.per_model_cost:
71
+ lines.append("by model:")
72
+ lines += [
73
+ f" {model:<24} {money(cost, self.priced)}" for model, cost in sorted(self.per_model_cost.items())
74
+ ]
75
+ if self.per_tool:
76
+ lines.append("by tool:")
77
+ lines += [f" {tool:<12} {count}" for tool, count in sorted(self.per_tool.items())]
78
+ return lines
79
+
80
+
81
+ def collect(events: list[Event]) -> Metrics:
82
+ """The metrics of a session, from its events."""
83
+ metrics = Metrics()
84
+ tools: dict[str, str] = {}
85
+ for event in events:
86
+ payload = event.payload
87
+ if event.type == EventType.ASSISTANT_MESSAGE:
88
+ _model_call(metrics, payload)
89
+ elif event.type == EventType.TOOL_CALL:
90
+ for action in payload.get("actions") or []:
91
+ metrics.tool_calls += 1
92
+ tool = action.get("tool", "")
93
+ metrics.per_tool[tool] = metrics.per_tool.get(tool, 0) + 1
94
+ tools[action.get("tool_call_id", "")] = tool
95
+ elif event.type == EventType.TOOL_RESULT:
96
+ for message in payload.get("messages") or []:
97
+ _sub_agent_cost(metrics, tools.get(message.get("tool_call_id", "")), message.get("content", ""))
98
+ elif event.type == EventType.COMPACTION:
99
+ metrics.compactions += 1
100
+ cost = float(payload.get("cost") or 0.0)
101
+ metrics.total_cost += cost
102
+ metrics.per_purpose_cost["summarize"] = metrics.per_purpose_cost.get("summarize", 0.0) + cost
103
+ if "summary_ratio" in payload:
104
+ metrics.summary_ratios.append(float(payload.get("summary_ratio") or 0.0))
105
+ elif event.type == EventType.RECAP:
106
+ cost = float(payload.get("cost") or 0.0)
107
+ metrics.total_cost += cost
108
+ metrics.per_purpose_cost["recap"] = metrics.per_purpose_cost.get("recap", 0.0) + cost
109
+ elif event.type == EventType.SIDE_CONVERSATION:
110
+ cost = float(payload.get("cost") or 0.0)
111
+ metrics.total_cost += cost
112
+ metrics.per_purpose_cost["side"] = metrics.per_purpose_cost.get("side", 0.0) + cost
113
+ elif event.type == EventType.REFLECTION:
114
+ cost = float(payload.get("cost") or 0.0)
115
+ metrics.total_cost += cost
116
+ if not _is_priced(payload, cost):
117
+ metrics.priced = False
118
+ metrics.per_purpose_cost["reflect"] = metrics.per_purpose_cost.get("reflect", 0.0) + cost
119
+ metrics.total_tokens_in += int(payload.get("tokens_in") or 0)
120
+ metrics.total_tokens_out += int(payload.get("tokens_out") or 0)
121
+ model = str(payload.get("model") or "")
122
+ if model:
123
+ metrics.per_model_cost[model] = metrics.per_model_cost.get(model, 0.0) + cost
124
+ elif event.type == EventType.ERROR:
125
+ metrics.errors += 1
126
+ timestamps = [event.timestamp for event in events if event.timestamp]
127
+ if len(timestamps) > 1:
128
+ metrics.duration_seconds = max(timestamps) - min(timestamps)
129
+ return metrics
130
+
131
+
132
+ def trace(events: list[Event], session=None) -> dict[str, Any]:
133
+ """The whole session, as a trace."""
134
+ return {
135
+ "trajectory_format": TRACE_FORMAT,
136
+ "session": _session(session),
137
+ "events": [event.to_dict() for event in events],
138
+ "metrics": collect(events).to_dict(),
139
+ }
140
+
141
+
142
+ def payload_actions(event: Event) -> list[dict]:
143
+ return event.payload.get("actions") or []
144
+
145
+
146
+ def _model_call(metrics: Metrics, payload: dict) -> None:
147
+ message = payload.get("message") or {}
148
+ extra = message.get("extra") or {}
149
+ cost = float(extra.get("cost") or payload.get("cost") or 0.0)
150
+ if not _is_priced(extra, cost):
151
+ metrics.priced = False
152
+ """A model without a price: the cost of the session is unknown, not zero."""
153
+ metrics.model_calls += 1
154
+ metrics.total_cost += cost
155
+ metrics.total_tokens_in += int(extra.get("tokens_in") or 0)
156
+ metrics.total_tokens_out += int(extra.get("tokens_out") or 0)
157
+ purpose = str(extra.get("purpose") or "main")
158
+ metrics.per_purpose_cost[purpose] = metrics.per_purpose_cost.get(purpose, 0.0) + cost
159
+ model = str(extra.get("model") or "")
160
+ if model:
161
+ metrics.per_model_cost[model] = metrics.per_model_cost.get(model, 0.0) + cost
162
+
163
+
164
+ def _is_priced(extra: dict, cost: float) -> bool:
165
+ """Whether the model of a call had a price.
166
+
167
+ The old logs do not say it: a call that used tokens and cost nothing was a
168
+ model without a price.
169
+ """
170
+ if "priced" in extra:
171
+ return bool(extra["priced"])
172
+ return not (extra.get("tokens_in") and not cost)
173
+
174
+
175
+ def _sub_agent_cost(metrics: Metrics, tool: str, content: str) -> None:
176
+ """The cost of a sub agent is the cost of the purpose it ran for."""
177
+ if tool != "task":
178
+ return
179
+ try:
180
+ result = json.loads(content)
181
+ except (json.JSONDecodeError, TypeError):
182
+ return
183
+ if not isinstance(result, dict):
184
+ return
185
+ cost = float(result.get("cost") or 0.0)
186
+ purpose = str(result.get("purpose") or "subagent")
187
+ metrics.total_cost += cost
188
+ metrics.total_tokens_in += int(result.get("tokens_in") or 0)
189
+ metrics.total_tokens_out += int(result.get("tokens_out") or 0)
190
+ metrics.per_purpose_cost[purpose] = metrics.per_purpose_cost.get(purpose, 0.0) + cost
191
+
192
+
193
+ def _session(session) -> dict[str, Any]:
194
+ if session is None:
195
+ return {}
196
+ return {
197
+ "id": session.id,
198
+ "cwd": str(session.cwd),
199
+ "created_at": session.created_at,
200
+ "updated_at": session.updated_at,
201
+ "state": session.state.value,
202
+ "model_name": session.model_name,
203
+ "permission_mode": session.permission_mode,
204
+ "turn_count": session.turn_count,
205
+ "total_cost": session.total_cost,
206
+ }
207
+
208
+
209
+ __all__ = ["Metrics", "TRACE_FORMAT", "collect", "trace"]
@@ -0,0 +1,132 @@
1
+ """Token estimation.
2
+
3
+ `tiktoken` gives an exact count but downloads its vocabulary on first use, so every
4
+ call is guarded: when it is unavailable or offline the heuristic takes over. The
5
+ estimate only drives decisions (compact or not), the API has the last word.
6
+ """
7
+
8
+ import json
9
+ from functools import lru_cache
10
+
11
+ from coderagent.core.content import image_tokens, text_of
12
+
13
+ CHARS_PER_TOKEN = 3.6
14
+ MESSAGE_OVERHEAD = 4
15
+
16
+ MARKER_ROOM = 160
17
+ """The room the marker of an elision takes, in characters.
18
+
19
+ The marker is part of the budget: what the model reads has to fit in it.
20
+ """
21
+
22
+ MARKER_TOKENS = 16
23
+ """The tokens the marker of an elision takes in a list of lines."""
24
+
25
+ try: # pragma: no cover - depends on the environment
26
+ import tiktoken
27
+ except ImportError: # pragma: no cover
28
+ tiktoken = None
29
+
30
+
31
+ @lru_cache(maxsize=1)
32
+ def _encoding():
33
+ if tiktoken is None:
34
+ return None
35
+ try:
36
+ return tiktoken.get_encoding("cl100k_base")
37
+ except Exception:
38
+ return None
39
+
40
+
41
+ def message_text(message: dict) -> str:
42
+ """The part of a message that costs tokens."""
43
+ parts = [text_of(message.get("content"))]
44
+ for call in message.get("tool_calls") or []:
45
+ function = call.get("function") or {}
46
+ parts.append(str(function.get("name") or ""))
47
+ parts.append(str(function.get("arguments") or ""))
48
+ return "\n".join(part for part in parts if part)
49
+
50
+
51
+ def estimate_tokens(messages: list[dict], tools: list[dict] | None = None) -> int:
52
+ """Rough token count of a conversation, including the tool schemas."""
53
+ encoding = _encoding()
54
+ images = sum(image_tokens(message.get("content")) for message in messages)
55
+ if encoding is not None:
56
+ total = sum(MESSAGE_OVERHEAD + len(encoding.encode(message_text(message))) for message in messages)
57
+ if tools:
58
+ total += len(encoding.encode(json.dumps(tools, ensure_ascii=False)))
59
+ return total + images
60
+ characters = sum(len(message_text(message)) for message in messages)
61
+ if tools:
62
+ characters += len(json.dumps(tools, ensure_ascii=False))
63
+ return int(characters / CHARS_PER_TOKEN) + MESSAGE_OVERHEAD * len(messages) + images
64
+
65
+
66
+ def count_text_tokens(text: str) -> int:
67
+ encoding = _encoding()
68
+ if encoding is not None:
69
+ return len(encoding.encode(text))
70
+ return int(len(text) / CHARS_PER_TOKEN)
71
+
72
+
73
+ def _cheap_tokens(text: str) -> float:
74
+ """Token estimate without touching the tokenizer, for splitting decisions."""
75
+ return len(text) / CHARS_PER_TOKEN
76
+
77
+
78
+ def trim_text(text: str, max_tokens: int) -> tuple[str, dict]:
79
+ """Keep the head and the tail of long text, elide the middle."""
80
+ if count_text_tokens(text) <= max_tokens:
81
+ return text, {}
82
+ budget = int(max_tokens * CHARS_PER_TOKEN)
83
+ room = max(0, budget - min(MARKER_ROOM, budget // 4))
84
+ head = room // 2
85
+ tail = room - head
86
+ head_text, tail_text = text[:head], text[-tail:] if tail else ""
87
+ elided_characters = max(0, len(text) - len(head_text) - len(tail_text))
88
+ elided_lines = max(0, text.count("\n") - head_text.count("\n") - tail_text.count("\n"))
89
+ elided_tokens = max(0, count_text_tokens(text) - count_text_tokens(head_text) - count_text_tokens(tail_text))
90
+ marker = f"\n... [{elided_lines} lines, {elided_tokens} tokens elided, use grep/offset to view that region] ...\n"
91
+ trimmed = f"{head_text}{marker}{tail_text}" if tail else f"{head_text}{marker}"
92
+ return trimmed, {
93
+ "elided_characters": elided_characters,
94
+ "elided_lines": elided_lines,
95
+ "elided_tokens": elided_tokens,
96
+ }
97
+
98
+
99
+ def trim_lines(lines: list[str], max_tokens: int) -> tuple[list[str], dict]:
100
+ """Keep the head and the tail of a list of lines, elide the middle.
101
+
102
+ The marker in the middle is not a line of the file, so the caller needs to know
103
+ how many lines came from the head to keep the line numbers right.
104
+ """
105
+ if count_text_tokens("\n".join(lines)) <= max_tokens:
106
+ return lines, {}
107
+ budget = max(1.0, (max_tokens - MARKER_TOKENS) / 2)
108
+ head_end = 0
109
+ used = 0.0
110
+ while head_end < len(lines):
111
+ cost = _cheap_tokens(lines[head_end]) + 1
112
+ if used + cost > budget and head_end > 0:
113
+ break
114
+ used += cost
115
+ head_end += 1
116
+ tail_start = len(lines)
117
+ used = 0.0
118
+ while tail_start > head_end:
119
+ cost = _cheap_tokens(lines[tail_start - 1]) + 1
120
+ if used + cost > budget and tail_start < len(lines):
121
+ break
122
+ used += cost
123
+ tail_start -= 1
124
+ elided = tail_start - head_end
125
+ marker = [f"... [{elided} lines elided, use offset to view that region] ..."]
126
+ trimmed = lines[:head_end] + marker + lines[tail_start:]
127
+ return trimmed, {
128
+ "elided_lines": elided,
129
+ "start_line": head_end + 1,
130
+ "end_line": tail_start,
131
+ "head_lines": head_end,
132
+ }