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,368 @@
1
+ """The runner of an eval suite: the working directory, the agent, the verify commands.
2
+
3
+ Every task runs on its own: its own working directory, its own session, its own
4
+ model. The suite only tells whether the tasks passed and what they cost.
5
+ """
6
+
7
+ import shutil
8
+ import time
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from coderagent.compat import recursive_merge
14
+ from coderagent.config.schema import Config
15
+ from coderagent.core.events import EventType
16
+ from coderagent.core.sandbox import build_environment
17
+ from coderagent.core.session import SessionStore
18
+ from coderagent.core.telemetry import collect
19
+ from coderagent.eval.task import Task, script_responses, task_overrides, task_permission_mode
20
+ from coderagent.run import build_loop, build_model
21
+ from coderagent.testing.factory import AllowAllApprover
22
+ from coderagent.testing.scripted_model import ScriptedModel
23
+ from coderagent.tools.permissions import ApprovalDecision
24
+
25
+ SCRIPT_ERROR = "ran out of responses"
26
+ """What the scripted model says when the script is too short."""
27
+
28
+
29
+ @dataclass
30
+ class VerifyResult:
31
+ command: str
32
+ exit_code: int
33
+ output: str
34
+ timed_out: bool = False
35
+
36
+ def to_dict(self) -> dict[str, Any]:
37
+ return {
38
+ "command": self.command,
39
+ "exit_code": self.exit_code,
40
+ "timed_out": self.timed_out,
41
+ "output": self.output,
42
+ }
43
+
44
+
45
+ @dataclass
46
+ class TaskResult:
47
+ id: str
48
+ mode: str
49
+ """`scripted` or `live`."""
50
+ passed: bool
51
+ """The verify commands decided it. A task whose harness broke never passes."""
52
+ expect: str = "pass"
53
+ """What the task was supposed to do: `pass` or `fail`."""
54
+ as_expected: bool = True
55
+ """Whether the task did what it was supposed to do."""
56
+ stop_reason: str = ""
57
+ error: str = ""
58
+ error_kind: str = ""
59
+ """`setup` or `script` when the harness failed, empty when the agent did."""
60
+ cost: float = 0.0
61
+ priced: bool = True
62
+ """False when the model had no price: the cost of the task is unknown, not zero."""
63
+ tokens_in: int = 0
64
+ tokens_out: int = 0
65
+ model_calls: int = 0
66
+ """The calls of the main loop. The calls of the sub agents are not in it."""
67
+ tool_calls: int = 0
68
+ tool_errors: int = 0
69
+ approvals: int = 0
70
+ compactions: int = 0
71
+ summary_ratios: list[float] = field(default_factory=list)
72
+ """How much of the compacted history each summary kept. One number per compaction."""
73
+ duration_seconds: float = 0.0
74
+ session_id: str = ""
75
+ setup: list[VerifyResult] = field(default_factory=list)
76
+ verify: list[VerifyResult] = field(default_factory=list)
77
+
78
+ def to_dict(self) -> dict[str, Any]:
79
+ return {
80
+ "id": self.id,
81
+ "mode": self.mode,
82
+ "passed": self.passed,
83
+ "expect": self.expect,
84
+ "as_expected": self.as_expected,
85
+ "stop_reason": self.stop_reason,
86
+ "error": self.error,
87
+ "error_kind": self.error_kind,
88
+ "cost": self.cost,
89
+ "priced": self.priced,
90
+ "tokens_in": self.tokens_in,
91
+ "tokens_out": self.tokens_out,
92
+ "model_calls": self.model_calls,
93
+ "tool_calls": self.tool_calls,
94
+ "tool_errors": self.tool_errors,
95
+ "approvals": self.approvals,
96
+ "compactions": self.compactions,
97
+ "summary_ratios": list(self.summary_ratios),
98
+ "duration_seconds": self.duration_seconds,
99
+ "session_id": self.session_id,
100
+ "setup": [result.to_dict() for result in self.setup],
101
+ "verify": [result.to_dict() for result in self.verify],
102
+ }
103
+
104
+
105
+ class CountingApprover(AllowAllApprover):
106
+ """Approves everything, but counts how often a human would have been needed."""
107
+
108
+ def __init__(self) -> None:
109
+ self.count = 0
110
+
111
+ def request(self, tool: str, params: dict, reason: str) -> ApprovalDecision:
112
+ self.count += 1
113
+ return super().request(tool, params, reason)
114
+
115
+
116
+ def run_commands(commands: list[str], environment, timeout: int) -> list[VerifyResult]:
117
+ """Run the commands of a task and report what each of them did.
118
+
119
+ The commands run in the environment of the agent, without the permission layer:
120
+ the verify of a task needs the raw exit code and the raw output.
121
+ """
122
+ results = []
123
+ for command in commands:
124
+ outcome = environment.execute({"command": command}, timeout=timeout)
125
+ output = str(outcome.get("output") or "")
126
+ exception = str(outcome.get("exception_info") or "")
127
+ results.append(
128
+ VerifyResult(
129
+ command=command,
130
+ exit_code=int(outcome.get("returncode", 0)),
131
+ output=(output + ("\n" + exception if exception else "")).strip(),
132
+ timed_out="timed out" in exception.lower(),
133
+ )
134
+ )
135
+ return results
136
+
137
+
138
+ def _successful_calls(events: list) -> list[tuple[str, str]]:
139
+ """The tool calls that ran without an error: the tool and the file it touched.
140
+
141
+ The file is empty when the log does not say: a call of a sub agent is
142
+ there, but the way it called the tool is not.
143
+ """
144
+ paths = {}
145
+ for event in events:
146
+ if event.type == EventType.TOOL_CALL:
147
+ for action in event.payload.get("actions") or []:
148
+ paths[str(action.get("tool_call_id") or "")] = str((action.get("args") or {}).get("path") or "")
149
+ calls = []
150
+ for event in events:
151
+ if event.type != EventType.TOOL_RESULT or event.payload.get("is_error"):
152
+ continue
153
+ tool = str(event.payload.get("tool") or "")
154
+ if not tool:
155
+ continue
156
+ path = paths.get(str(event.payload.get("tool_call_id") or "")) or _path_of_diff(event.payload.get("diff"))
157
+ calls.append((tool, path))
158
+ return calls
159
+
160
+
161
+ def _path_of_diff(diff) -> str:
162
+ """The file a diff is about."""
163
+ for line in str(diff or "").splitlines():
164
+ if line.startswith("--- "):
165
+ return line[4:].removeprefix("a/")
166
+ return ""
167
+
168
+
169
+ def _met(requirement, calls: list[tuple[str, str]], workdir: Path) -> bool:
170
+ """Whether a call met a requirement: the right tool, on the right file."""
171
+ for tool, path in calls:
172
+ if tool not in requirement.tools:
173
+ continue
174
+ if not requirement.paths or not path or _is_one_of(path, requirement.paths, workdir):
175
+ return True
176
+ return False
177
+
178
+
179
+ def _is_one_of(path: str, wanted: list[str], workdir: Path) -> bool:
180
+ """Whether a path is one of the files of a requirement."""
181
+ target = _resolve(path, workdir)
182
+ return any(target == _resolve(one, workdir) for one in wanted)
183
+
184
+
185
+ def _resolve(path: str, workdir: Path) -> Path:
186
+ """Where a path is, relative to the working directory of the task."""
187
+ candidate = Path(path)
188
+ return (candidate if candidate.is_absolute() else workdir / candidate).resolve()
189
+
190
+
191
+ def _describe(requirement) -> str:
192
+ """What a requirement asks for, in a sentence."""
193
+ tools = " or ".join(requirement.tools)
194
+ if requirement.paths:
195
+ return f"one of the tools '{tools}' on {' or '.join(requirement.paths)}"
196
+ return f"one of the tools '{tools}'"
197
+
198
+
199
+ def prepare_workdir(task: Task, workdir: Path) -> Path:
200
+ """The working directory of a task: the fixture of the task, and nothing else."""
201
+ if workdir.exists():
202
+ shutil.rmtree(workdir)
203
+ workdir.mkdir(parents=True)
204
+ if task.path is None:
205
+ return workdir
206
+ for source in sorted(task.path.rglob("*")):
207
+ if source.suffix in (".yaml", ".yml"):
208
+ """The yaml files describe the task, they are not part of the fixture."""
209
+ continue
210
+ target = workdir / source.relative_to(task.path)
211
+ if source.is_dir():
212
+ target.mkdir(parents=True, exist_ok=True)
213
+ else:
214
+ target.parent.mkdir(parents=True, exist_ok=True)
215
+ shutil.copy2(source, target)
216
+ return workdir
217
+
218
+
219
+ def task_config(base: Config, task: Task) -> Config:
220
+ """The configuration of a task: the one of the run, plus the overrides of the task."""
221
+ config = base.model_copy(deep=True)
222
+ explicit = "context_window" in base.context.model_fields_set
223
+ for override in task_overrides(task):
224
+ explicit = explicit or "context_window" in (override.get("context") or {})
225
+ config = Config(**recursive_merge(config.model_dump(mode="json"), override))
226
+ if not explicit:
227
+ """The window of the model is used when the configuration does not set one."""
228
+ config.context.model_fields_set.discard("context_window")
229
+ return config
230
+
231
+
232
+ def run_task(
233
+ task: Task,
234
+ config: Config,
235
+ *,
236
+ workdir: Path,
237
+ store: SessionStore,
238
+ permission_mode: str = "bypass",
239
+ approver=None,
240
+ user_home: Path | None = None,
241
+ ) -> TaskResult:
242
+ """Run one task: the fixture, the agent, the verify commands."""
243
+ mode = "scripted" if task.script else "live"
244
+ prepare_workdir(task, workdir)
245
+ environment = build_environment(config.sandbox, workdir)
246
+ setup = run_commands(task.setup, environment, task.verify_timeout)
247
+ if any(result.exit_code != 0 for result in setup):
248
+ failed = next(result for result in setup if result.exit_code != 0)
249
+ return TaskResult(
250
+ id=task.id,
251
+ mode=mode,
252
+ passed=False,
253
+ expect=task.expect,
254
+ as_expected=False,
255
+ stop_reason="setup_failed",
256
+ error=f"the setup failed: {failed.command}",
257
+ error_kind="setup",
258
+ setup=setup,
259
+ )
260
+ config = task_config(config, task)
261
+ permission_mode = task_permission_mode(task) or permission_mode
262
+ if task.script:
263
+ """A scripted model answers every question, so nothing may be routed or compacted."""
264
+ config.model.routing = {}
265
+ config.model.routing_rules = []
266
+ config.context.auto_compact = False
267
+ approver = approver or (CountingApprover() if permission_mode == "default" else None)
268
+ model = ScriptedModel(script_responses(task)) if task.script else build_model(config)
269
+ loop = build_loop(
270
+ config,
271
+ workdir,
272
+ model=model,
273
+ store=store,
274
+ permission_mode=permission_mode,
275
+ approver=approver,
276
+ user_home=user_home,
277
+ enforce_ceilings=True,
278
+ )
279
+ """The harness measures a run: the ceilings of the task hold, whatever the mode is."""
280
+ deadline = time.monotonic() + task.timeout
281
+ loop.cancel = lambda: time.monotonic() > deadline
282
+ started = time.monotonic()
283
+ result = None
284
+ for prompt in task.prompts or [task.prompt]:
285
+ result = loop.run_turn(prompt)
286
+ if result.stop_reason == "error":
287
+ """A broken turn ends the task: the later prompts would run on a broken session."""
288
+ break
289
+ if result is None:
290
+ raise ValueError(f"the task {task.id} has no prompt")
291
+ duration = time.monotonic() - started
292
+ events = store.events(result.session_id)
293
+ metrics = collect(events)
294
+ verify = run_commands(task.verify, loop.sandbox, task.verify_timeout)
295
+ script_error = result.stop_reason == "error" and SCRIPT_ERROR in result.error
296
+ error_kind = "script" if script_error else ""
297
+ used = _successful_calls(events)
298
+ needed = bool(task.require_tools) and not any(
299
+ _met(requirement, used, workdir) for requirement in task.require_tools
300
+ )
301
+ """The task needs a tool, and no call did what it asks for."""
302
+ passed = not error_kind and bool(task.verify) and all(item.exit_code == 0 for item in verify) and not needed
303
+ error = result.error
304
+ if needed:
305
+ error = f"{error}. " if error else ""
306
+ error += (
307
+ f"the task needs {' or '.join(_describe(requirement) for requirement in task.require_tools)}, "
308
+ "and no call did that"
309
+ )
310
+ return TaskResult(
311
+ id=task.id,
312
+ mode=mode,
313
+ passed=passed,
314
+ expect=task.expect,
315
+ as_expected=not error_kind and passed == (task.expect == "pass"),
316
+ stop_reason=result.stop_reason,
317
+ error=error,
318
+ error_kind=error_kind,
319
+ cost=metrics.total_cost,
320
+ priced=metrics.priced,
321
+ tokens_in=metrics.total_tokens_in,
322
+ tokens_out=metrics.total_tokens_out,
323
+ model_calls=metrics.model_calls,
324
+ tool_calls=metrics.tool_calls,
325
+ tool_errors=_tool_errors(events),
326
+ approvals=getattr(approver, "count", 0),
327
+ compactions=metrics.compactions,
328
+ summary_ratios=list(metrics.summary_ratios),
329
+ duration_seconds=duration,
330
+ session_id=result.session_id,
331
+ setup=setup,
332
+ verify=verify,
333
+ )
334
+
335
+
336
+ def run_suite(
337
+ tasks: list[Task],
338
+ config: Config,
339
+ *,
340
+ root: Path,
341
+ store: SessionStore,
342
+ permission_mode: str = "bypass",
343
+ user_home: Path | None = None,
344
+ ) -> list[TaskResult]:
345
+ """Run every task of a suite, each one in its own working directory."""
346
+ return [
347
+ run_task(
348
+ task,
349
+ config,
350
+ workdir=root / task.id,
351
+ store=store,
352
+ permission_mode=permission_mode,
353
+ user_home=user_home,
354
+ )
355
+ for task in tasks
356
+ ]
357
+
358
+
359
+ def _tool_errors(events) -> int:
360
+ """The tool calls that failed, the denied ones included."""
361
+ count = 0
362
+ for event in events:
363
+ if event.type != "tool_result":
364
+ continue
365
+ for message in event.payload.get("messages") or []:
366
+ if str(message.get("content") or "").startswith("Error:"):
367
+ count += 1
368
+ return count
@@ -0,0 +1,194 @@
1
+ """The tasks of an eval suite: the format on disk and the parsing of it.
2
+
3
+ A suite is a directory, every task is a directory inside it. A task has a
4
+ `task.yaml` and, next to it, the files that are the initial state of the working
5
+ directory of the agent.
6
+ """
7
+
8
+ import json
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ import yaml
13
+
14
+ from coderagent.compat import get_config_from_spec
15
+
16
+ TASK_FILE = "task.yaml"
17
+ """The file that describes a task. The other yaml files are part of the fixture."""
18
+
19
+ DEFAULT_TIMEOUT = 300
20
+ DEFAULT_VERIFY_TIMEOUT = 300
21
+
22
+
23
+ @dataclass
24
+ class ToolRequirement:
25
+ tools: list[str]
26
+ """The tools that may do the work. One of them has to have worked."""
27
+ paths: list[str] = field(default_factory=list)
28
+ """The files the work is about. One of them has to have been touched by the tool.
29
+
30
+ Empty means that the file does not matter. A file matters when the model
31
+ could take another route: an edit of another file is not the work of the
32
+ task.
33
+ """
34
+
35
+ def to_dict(self) -> dict:
36
+ return {"tools": list(self.tools), "paths": list(self.paths)}
37
+
38
+
39
+ @dataclass
40
+ class Task:
41
+ id: str
42
+ prompt: str
43
+ """The first prompt of the task."""
44
+ prompts: list[str] = field(default_factory=list)
45
+ """Every prompt of the task. They run one after the other in the same session.
46
+
47
+ A task with one prompt can never compact: the cut of the history has to land
48
+ on a turn boundary, and a turn that never happened cannot be cut. A task that
49
+ wants to see the compaction needs more than one prompt.
50
+ """
51
+ verify: list[str] = field(default_factory=list)
52
+ """The commands that decide whether the task passed. A task without one never passes."""
53
+ setup: list[str] = field(default_factory=list)
54
+ """The commands that prepare the working directory, before the agent starts."""
55
+ expect: str = "pass"
56
+ """What the task is supposed to do: `pass` or `fail`.
57
+
58
+ A task that must fail keeps the suite honest: a check that never fails
59
+ would let every task pass.
60
+ """
61
+ timeout: int = DEFAULT_TIMEOUT
62
+ """Seconds the agent may spend on the task."""
63
+ verify_timeout: int = DEFAULT_VERIFY_TIMEOUT
64
+ """Seconds each verify command may take."""
65
+ tags: list[str] = field(default_factory=list)
66
+ require_tools: list[ToolRequirement] = field(default_factory=list)
67
+ """What the task needs from the tools. One of the requirements has to be met.
68
+
69
+ A task that changes a file with the `edit` tool and says so cannot be
70
+ solved by another route, so a broken tool shows up as a failed task.
71
+ """
72
+ script: list[dict] = field(default_factory=list)
73
+ """The scripted model. Empty means: the real model."""
74
+ config: list[str] = field(default_factory=list)
75
+ """Config overrides: a path to a yaml file or `a.b=c` specs."""
76
+ path: Path | None = None
77
+ """The directory of the task. Its files are the initial state of the working directory."""
78
+
79
+
80
+ def load_task(directory: Path) -> Task:
81
+ """The task of a directory."""
82
+ directory = Path(directory)
83
+ path = directory / TASK_FILE
84
+ if not path.exists():
85
+ raise FileNotFoundError(f"the task {directory} has no {TASK_FILE}")
86
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
87
+ if not data.get("verify"):
88
+ raise ValueError(f"the task {directory} has no verify command: a task without one can never pass")
89
+ expect = str(data.get("expect") or "pass")
90
+ if expect not in ("pass", "fail"):
91
+ raise ValueError(f"the task {directory} expects '{expect}', which is neither 'pass' nor 'fail'")
92
+ prompts = [str(prompt) for prompt in data.get("prompts") or [] if str(prompt).strip()]
93
+ if not prompts and str(data.get("prompt") or "").strip():
94
+ prompts = [str(data["prompt"])]
95
+ if not prompts:
96
+ raise ValueError(f"the task {directory} has no prompt")
97
+ return Task(
98
+ id=str(data.get("id") or directory.name),
99
+ prompt=prompts[0] if prompts else "",
100
+ prompts=prompts,
101
+ verify=[str(command) for command in data["verify"]],
102
+ setup=[str(command) for command in data.get("setup") or []],
103
+ expect=expect,
104
+ timeout=int(data.get("timeout") or DEFAULT_TIMEOUT),
105
+ verify_timeout=int(data.get("verify_timeout") or DEFAULT_VERIFY_TIMEOUT),
106
+ tags=[str(tag) for tag in data.get("tags") or []],
107
+ require_tools=_requirements(data.get("require_tools")),
108
+ script=list(data.get("script") or []),
109
+ config=[str(spec) for spec in data.get("config") or []],
110
+ path=directory,
111
+ )
112
+
113
+
114
+ def _requirements(data) -> list[ToolRequirement]:
115
+ """The requirements of a task: the tools that have to work, and the files they have to touch.
116
+
117
+ A requirement is either the name of a tool or a mapping with the tools and
118
+ the files:
119
+ ```yaml
120
+ require_tools:
121
+ - tools: [edit, multi_edit]
122
+ paths: [calc.py]
123
+ ```
124
+ """
125
+ requirements = []
126
+ for entry in data or []:
127
+ if isinstance(entry, str):
128
+ requirement = ToolRequirement(tools=[entry])
129
+ elif isinstance(entry, dict):
130
+ requirement = ToolRequirement(
131
+ tools=[str(tool) for tool in entry.get("tools") or []],
132
+ paths=[str(path) for path in entry.get("paths") or []],
133
+ )
134
+ else:
135
+ raise ValueError(f"the requirement {entry!r} is neither a tool nor a mapping")
136
+ if not requirement.tools:
137
+ raise ValueError(f"the requirement {entry!r} names no tool")
138
+ requirements.append(requirement)
139
+ return requirements
140
+
141
+
142
+ def load_suite(directory: Path) -> list[Task]:
143
+ """The tasks of a suite, sorted by id."""
144
+ directory = Path(directory)
145
+ if not directory.is_dir():
146
+ raise NotADirectoryError(f"the suite {directory} is not a directory")
147
+ return sorted((load_task(child) for child in directory.iterdir() if child.is_dir()), key=lambda t: t.id)
148
+
149
+
150
+ def task_overrides(task: Task) -> list[dict]:
151
+ """The overrides of a task: a yaml file next to it, or an `a.b=c` spec."""
152
+ overrides = []
153
+ for spec in task.config:
154
+ path = Path(spec)
155
+ if "=" not in spec and not path.is_absolute() and task.path is not None and (task.path / path).exists():
156
+ overrides.append(yaml.safe_load((task.path / path).read_text(encoding="utf-8")) or {})
157
+ else:
158
+ overrides.append(get_config_from_spec(spec))
159
+ return overrides
160
+
161
+
162
+ def task_permission_mode(task: Task) -> str:
163
+ """The permission mode of a task, when the task sets one.
164
+
165
+ The mode of the command is the default; a task may ask for another one, so
166
+ that its rules are the ones that count.
167
+ """
168
+ for override in task_overrides(task):
169
+ mode = (override.get("permissions") or {}).get("mode")
170
+ if mode:
171
+ return str(mode)
172
+ return ""
173
+
174
+
175
+ def script_responses(task: Task) -> list[dict]:
176
+ """The script of a task, in the shape the model gateway expects."""
177
+ responses = []
178
+ counter = 0
179
+ for step in task.script:
180
+ calls = []
181
+ for call in step.get("tool_calls") or []:
182
+ counter += 1
183
+ calls.append(
184
+ {
185
+ "id": f"call_{counter}",
186
+ "type": "function",
187
+ "function": {"name": str(call.get("tool") or ""), "arguments": json.dumps(call.get("args") or {})},
188
+ }
189
+ )
190
+ message = {"role": "assistant", "content": str(step.get("content") or ""), "extra": {"cost": 0.0}}
191
+ if calls:
192
+ message["tool_calls"] = calls
193
+ responses.append(message)
194
+ return responses
@@ -0,0 +1 @@
1
+ """Extensions: the optional parts around the agent, like hooks."""
@@ -0,0 +1,121 @@
1
+ """Hooks: user defined commands that run at the important moments of a session."""
2
+
3
+ import json
4
+ import logging
5
+ import re
6
+ import subprocess
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from coderagent.config.schema import HookConfig
11
+
12
+ logger = logging.getLogger("coderagent.hooks")
13
+
14
+
15
+ @dataclass
16
+ class HookResult:
17
+ decision: str = ""
18
+ """One of allow, deny, block. Empty means the hook has no opinion."""
19
+ reason: str = ""
20
+ additional_context: str = ""
21
+ updated_input: dict | str | None = None
22
+ """The new input of the event: the arguments of the tool, or the prompt."""
23
+
24
+
25
+ @dataclass
26
+ class MergedHookResult:
27
+ """The result of all the hooks of one event, put together."""
28
+
29
+ decision: str = ""
30
+ reason: str = ""
31
+ additional_context: str = ""
32
+ updated_input: dict | str | None = None
33
+
34
+ @property
35
+ def blocked(self) -> bool:
36
+ return self.decision in ("deny", "block")
37
+
38
+
39
+ def merge_results(results: list[HookResult]) -> MergedHookResult:
40
+ """Any deny wins, the contexts are concatenated, the last updated input wins."""
41
+ merged = MergedHookResult()
42
+ for result in results:
43
+ if result.decision in ("deny", "block"):
44
+ merged.decision = result.decision
45
+ merged.reason = result.reason
46
+ elif result.decision == "allow" and not merged.decision:
47
+ merged.decision = "allow"
48
+ if result.additional_context:
49
+ merged.additional_context = (merged.additional_context + "\n" + result.additional_context).strip()
50
+ if result.updated_input is not None:
51
+ merged.updated_input = result.updated_input
52
+ return merged
53
+
54
+
55
+ class HookRunner:
56
+ """Runs the hook commands of the configuration."""
57
+
58
+ def __init__(self, config: HookConfig | None = None, cwd: Path | None = None) -> None:
59
+ self.config = config or HookConfig()
60
+ self.cwd = cwd or Path.cwd()
61
+
62
+ def run(self, hook_name: str, payload: dict) -> list[HookResult]:
63
+ """Run every hook that matches this event."""
64
+ results: list[HookResult] = []
65
+ for matcher in self.config.events.get(hook_name, []):
66
+ if not self._matches(matcher.matcher, payload):
67
+ continue
68
+ for hook in matcher.hooks:
69
+ results.append(self._run_one(hook, payload))
70
+ return results
71
+
72
+ def apply(self, hook_name: str, payload: dict) -> MergedHookResult:
73
+ """Run the hooks of this event and merge their answers."""
74
+ return merge_results(self.run(hook_name, payload))
75
+
76
+ def _matches(self, matcher: str, payload: dict) -> bool:
77
+ if not matcher:
78
+ return True
79
+ tool = payload.get("tool") or ""
80
+ try:
81
+ return re.search(matcher, tool) is not None
82
+ except re.error:
83
+ logger.warning("Hook matcher '%s' is not a valid regex", matcher)
84
+ return False
85
+
86
+ def _run_one(self, hook, payload: dict) -> HookResult:
87
+ try:
88
+ completed = subprocess.run(
89
+ hook.command,
90
+ shell=True,
91
+ cwd=self.cwd,
92
+ input=json.dumps(payload),
93
+ capture_output=True,
94
+ text=True,
95
+ timeout=hook.timeout,
96
+ )
97
+ except subprocess.TimeoutExpired:
98
+ logger.warning("Hook '%s' timed out, ignoring it", hook.command)
99
+ return HookResult()
100
+ if completed.returncode != 0:
101
+ logger.warning("Hook '%s' failed with %s: %s", hook.command, completed.returncode, completed.stderr.strip())
102
+ return HookResult(decision="deny", reason=completed.stderr.strip()) if hook.strict else HookResult()
103
+ return self._parse(completed.stdout)
104
+
105
+ def _parse(self, output: str) -> HookResult:
106
+ if not output.strip():
107
+ return HookResult()
108
+ try:
109
+ data = json.loads(output)
110
+ except json.JSONDecodeError:
111
+ logger.warning("Hook output is not JSON, ignoring it: %s", output[:200])
112
+ return HookResult()
113
+ if not isinstance(data, dict):
114
+ return HookResult()
115
+ updated = data.get("updatedInput", data.get("updated_input"))
116
+ return HookResult(
117
+ decision=str(data.get("decision", "")),
118
+ reason=str(data.get("reason", "")),
119
+ additional_context=str(data.get("additionalContext", data.get("additional_context", ""))),
120
+ updated_input=updated if isinstance(updated, (dict, str)) else None,
121
+ )