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.
- coder_agent-0.1.0.dist-info/METADATA +262 -0
- coder_agent-0.1.0.dist-info/RECORD +163 -0
- coder_agent-0.1.0.dist-info/WHEEL +5 -0
- coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
- coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
- coder_agent-0.1.0.dist-info/top_level.txt +1 -0
- coderagent/__init__.py +20 -0
- coderagent/compat/__init__.py +27 -0
- coderagent/compat/cache_control.py +69 -0
- coderagent/compat/config_spec.py +60 -0
- coderagent/compat/exceptions.py +20 -0
- coderagent/compat/retry.py +27 -0
- coderagent/compat/serialize.py +31 -0
- coderagent/config/__init__.py +1 -0
- coderagent/config/defaults.yaml +103 -0
- coderagent/config/loader.py +264 -0
- coderagent/config/schema.py +548 -0
- coderagent/config/writer.py +218 -0
- coderagent/core/__init__.py +1 -0
- coderagent/core/budget.py +47 -0
- coderagent/core/capabilities.py +136 -0
- coderagent/core/checkpoint.py +164 -0
- coderagent/core/content.py +156 -0
- coderagent/core/context.py +618 -0
- coderagent/core/events.py +83 -0
- coderagent/core/history.py +56 -0
- coderagent/core/instructions.py +99 -0
- coderagent/core/loop.py +702 -0
- coderagent/core/memory.py +56 -0
- coderagent/core/mentions.py +81 -0
- coderagent/core/os_sandbox.py +191 -0
- coderagent/core/otel.py +214 -0
- coderagent/core/protocols.py +38 -0
- coderagent/core/redact.py +49 -0
- coderagent/core/sandbox.py +82 -0
- coderagent/core/schema.py +107 -0
- coderagent/core/session.py +344 -0
- coderagent/core/shell_env.py +74 -0
- coderagent/core/subagent.py +474 -0
- coderagent/core/summarize.py +312 -0
- coderagent/core/telemetry.py +209 -0
- coderagent/core/tokens.py +132 -0
- coderagent/core/trust.py +301 -0
- coderagent/environments/__init__.py +11 -0
- coderagent/environments/bubblewrap.py +150 -0
- coderagent/environments/contree.py +146 -0
- coderagent/environments/docker.py +160 -0
- coderagent/environments/local.py +110 -0
- coderagent/environments/singularity.py +138 -0
- coderagent/environments/swerex_docker.py +79 -0
- coderagent/environments/swerex_modal.py +123 -0
- coderagent/eval/__init__.py +1 -0
- coderagent/eval/compare.py +190 -0
- coderagent/eval/report.py +141 -0
- coderagent/eval/runner.py +368 -0
- coderagent/eval/task.py +194 -0
- coderagent/extensions/__init__.py +1 -0
- coderagent/extensions/hooks.py +121 -0
- coderagent/extensions/plugins.py +217 -0
- coderagent/extensions/reflect.py +342 -0
- coderagent/models/__init__.py +33 -0
- coderagent/models/backends.py +218 -0
- coderagent/models/call.py +18 -0
- coderagent/models/check.py +139 -0
- coderagent/models/gateway.py +60 -0
- coderagent/models/litellm_config.py +70 -0
- coderagent/models/provider.py +98 -0
- coderagent/models/reasoning.py +28 -0
- coderagent/models/router.py +136 -0
- coderagent/models/settings.py +172 -0
- coderagent/models/streaming.py +122 -0
- coderagent/models/verbosity.py +14 -0
- coderagent/paths.py +31 -0
- coderagent/run.py +454 -0
- coderagent/skills/__init__.py +119 -0
- coderagent/skills/errors.py +11 -0
- coderagent/skills/install.py +340 -0
- coderagent/skills/presets/code-review/SKILL.md +35 -0
- coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
- coderagent/skills/presets/data-analysis/SKILL.md +35 -0
- coderagent/skills/presets/deep-research/SKILL.md +38 -0
- coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
- coderagent/skills/presets/long-document/SKILL.md +37 -0
- coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
- coderagent/skills/presets/office-docx/SKILL.md +36 -0
- coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
- coderagent/skills/presets/office-pptx/SKILL.md +32 -0
- coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
- coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
- coderagent/skills/presets/writing/SKILL.md +31 -0
- coderagent/skills/sandbox.py +269 -0
- coderagent/skills/sites.py +177 -0
- coderagent/skills/source.py +404 -0
- coderagent/testing/__init__.py +5 -0
- coderagent/testing/factory.py +59 -0
- coderagent/testing/scripted_model.py +54 -0
- coderagent/tools/__init__.py +1 -0
- coderagent/tools/base.py +54 -0
- coderagent/tools/bash_policy.py +486 -0
- coderagent/tools/builtin/__init__.py +35 -0
- coderagent/tools/builtin/fs.py +283 -0
- coderagent/tools/builtin/patch.py +279 -0
- coderagent/tools/builtin/search.py +242 -0
- coderagent/tools/builtin/shell.py +336 -0
- coderagent/tools/builtin/skill.py +41 -0
- coderagent/tools/builtin/task.py +53 -0
- coderagent/tools/builtin/todo.py +63 -0
- coderagent/tools/executor.py +243 -0
- coderagent/tools/mcp.py +317 -0
- coderagent/tools/permissions.py +472 -0
- coderagent/tools/registry.py +83 -0
- coderagent/tools/rules.py +138 -0
- coderagent/ui/__init__.py +1 -0
- coderagent/ui/cli.py +498 -0
- coderagent/ui/commands/__init__.py +109 -0
- coderagent/ui/commands/builtin.py +778 -0
- coderagent/ui/commands/compact.py +12 -0
- coderagent/ui/commands/resume.py +26 -0
- coderagent/ui/commands/review.py +73 -0
- coderagent/ui/commands/rewind.py +28 -0
- coderagent/ui/custom_commands.py +179 -0
- coderagent/ui/notify.py +46 -0
- coderagent/ui/open_file.py +48 -0
- coderagent/ui/render.py +62 -0
- coderagent/ui/spinner.py +68 -0
- coderagent/ui/tui.py +610 -0
- coderagent/ui/widgets/__init__.py +29 -0
- coderagent/ui/widgets/approval_prompt.py +129 -0
- coderagent/ui/widgets/diff_view.py +97 -0
- coderagent/ui/widgets/file_tree.py +105 -0
- coderagent/ui/widgets/markdown_message.py +44 -0
- coderagent/ui/widgets/markup.py +10 -0
- coderagent/ui/widgets/message_block.py +61 -0
- coderagent/ui/widgets/path_suggester.py +66 -0
- coderagent/ui/widgets/session_picker.py +49 -0
- coderagent/ui/widgets/status_bar.py +44 -0
- coderagent/ui/widgets/todo_panel.py +40 -0
- coderagent/ui/widgets/tool_card.py +104 -0
- coderagent/ui/widgets/working_dots.py +26 -0
- coderagent/version.py +7 -0
- coderagent/web/__init__.py +5 -0
- coderagent/web/api.py +449 -0
- coderagent/web/app.py +113 -0
- coderagent/web/approver.py +73 -0
- coderagent/web/config_api.py +53 -0
- coderagent/web/events.py +159 -0
- coderagent/web/files.py +115 -0
- coderagent/web/i18n.py +346 -0
- coderagent/web/server.py +100 -0
- coderagent/web/sessions.py +404 -0
- coderagent/web/skills_api.py +376 -0
- coderagent/web/static/app.css +283 -0
- coderagent/web/static/app.js +1466 -0
- coderagent/web/templates/en/base.html +31 -0
- coderagent/web/templates/en/chat.html +60 -0
- coderagent/web/templates/en/macros.html +9 -0
- coderagent/web/templates/en/settings.html +80 -0
- coderagent/web/templates/en/skills.html +64 -0
- coderagent/web/templates/zh/base.html +31 -0
- coderagent/web/templates/zh/chat.html +60 -0
- coderagent/web/templates/zh/macros.html +9 -0
- coderagent/web/templates/zh/settings.html +77 -0
- coderagent/web/templates/zh/skills.html +61 -0
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
"""Sub agents: a task that runs in its own context and returns a conclusion.
|
|
2
|
+
|
|
3
|
+
A sub agent is defined by a markdown file in `.coderagent/agents`:
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
name: code-explorer
|
|
7
|
+
description: Locate a symbol and explain the code around it.
|
|
8
|
+
tools: [read, grep, glob, ls]
|
|
9
|
+
model_purpose: cheap
|
|
10
|
+
max_turns: 15
|
|
11
|
+
---
|
|
12
|
+
You are a code base explorer. ...
|
|
13
|
+
|
|
14
|
+
The body is the system prompt of the sub agent. The tools are a white list: the
|
|
15
|
+
sub agent cannot reach anything else. The messages live only in the sub agent, so
|
|
16
|
+
the context of the main agent stays clean.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
import threading
|
|
22
|
+
from collections.abc import Callable
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
import yaml
|
|
27
|
+
|
|
28
|
+
from coderagent.config.schema import PURPOSES, ContextConfig, MemoryConfig
|
|
29
|
+
from coderagent.core.budget import context_window_for
|
|
30
|
+
from coderagent.core.context import repair_tool_calls
|
|
31
|
+
from coderagent.core.events import EventBus
|
|
32
|
+
from coderagent.core.memory import project_text
|
|
33
|
+
from coderagent.core.os_sandbox import sandbox_block
|
|
34
|
+
from coderagent.core.tokens import estimate_tokens
|
|
35
|
+
from coderagent.models.gateway import is_context_overflow
|
|
36
|
+
from coderagent.paths import config_home
|
|
37
|
+
from coderagent.tools.executor import ToolExecutor
|
|
38
|
+
from coderagent.tools.permissions import mode_block, network_block
|
|
39
|
+
from coderagent.tools.registry import ToolRegistry
|
|
40
|
+
|
|
41
|
+
AGENTS_DIR = "agents"
|
|
42
|
+
"""The directory of the sub agents. In the project it is under `.coderagent`."""
|
|
43
|
+
|
|
44
|
+
logger = logging.getLogger("coderagent.subagent")
|
|
45
|
+
|
|
46
|
+
DEFAULT_TOOLS = ["read", "grep", "glob", "bash"]
|
|
47
|
+
|
|
48
|
+
BUILTIN_SUBAGENTS: dict[str, "SubagentSpec"] = {}
|
|
49
|
+
"""The sub agents that are always there. Filled at the end of this module."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class SubagentSpec:
|
|
54
|
+
"""What a sub agent is and what it may do."""
|
|
55
|
+
|
|
56
|
+
name: str
|
|
57
|
+
description: str = ""
|
|
58
|
+
system_prompt: str = ""
|
|
59
|
+
tools: list[str] = field(default_factory=lambda: list(DEFAULT_TOOLS))
|
|
60
|
+
model_purpose: str = "cheap"
|
|
61
|
+
max_turns: int = 20
|
|
62
|
+
path: Path | None = None
|
|
63
|
+
|
|
64
|
+
def render(self) -> str:
|
|
65
|
+
"""The description, as the main agent sees it."""
|
|
66
|
+
return f"{self.name}: {self.description}" if self.description else self.name
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def effective_turns(spec: SubagentSpec, ceiling: int = 0) -> int:
|
|
70
|
+
"""How many model calls the sub agent may make. 0 means no limit.
|
|
71
|
+
|
|
72
|
+
The ceiling of the configuration wins over the one of the sub agent.
|
|
73
|
+
"""
|
|
74
|
+
if not ceiling:
|
|
75
|
+
return spec.max_turns
|
|
76
|
+
return min(spec.max_turns, ceiling) if spec.max_turns else ceiling
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def parse_subagent(path: Path) -> SubagentSpec | None:
|
|
80
|
+
"""Read one sub agent file. Returns None when the file cannot be used."""
|
|
81
|
+
text = path.read_text(encoding="utf-8")
|
|
82
|
+
if not text.startswith("---"):
|
|
83
|
+
return None
|
|
84
|
+
_, _, rest = text.partition("---")
|
|
85
|
+
front_matter, _, body = rest.partition("---")
|
|
86
|
+
try:
|
|
87
|
+
data = yaml.safe_load(front_matter) or {}
|
|
88
|
+
except yaml.YAMLError:
|
|
89
|
+
return None
|
|
90
|
+
if not isinstance(data, dict):
|
|
91
|
+
return None
|
|
92
|
+
purpose = str(data.get("model_purpose", "cheap"))
|
|
93
|
+
if purpose not in PURPOSES:
|
|
94
|
+
logger.warning("The sub agent '%s' has an unknown model_purpose '%s'. It is not used.", path.name, purpose)
|
|
95
|
+
return None
|
|
96
|
+
return SubagentSpec(
|
|
97
|
+
name=str(data.get("name") or path.stem),
|
|
98
|
+
description=str(data.get("description", "")),
|
|
99
|
+
system_prompt=body.strip(),
|
|
100
|
+
tools=_tool_list(data.get("tools")),
|
|
101
|
+
model_purpose=purpose,
|
|
102
|
+
max_turns=int(data.get("max_turns", 20)),
|
|
103
|
+
path=path,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _tool_list(value) -> list[str]:
|
|
108
|
+
"""The white list of the tools. Empty means the default set."""
|
|
109
|
+
if value is None:
|
|
110
|
+
return list(DEFAULT_TOOLS)
|
|
111
|
+
if isinstance(value, list):
|
|
112
|
+
return [str(item).strip() for item in value if str(item).strip()]
|
|
113
|
+
return [item.strip() for item in str(value).split(",") if item.strip()]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def load_subagents(cwd: Path, user_home: Path | None = None) -> dict[str, SubagentSpec]:
|
|
117
|
+
"""The sub agents of the project and of the user. The project wins on a name clash."""
|
|
118
|
+
specs: dict[str, SubagentSpec] = dict(BUILTIN_SUBAGENTS)
|
|
119
|
+
for directory in _directories(cwd, user_home):
|
|
120
|
+
for path in sorted(directory.glob("*.md")):
|
|
121
|
+
spec = parse_subagent(path)
|
|
122
|
+
if spec is not None:
|
|
123
|
+
specs[spec.name] = spec
|
|
124
|
+
return specs
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _directories(cwd: Path, user_home: Path | None) -> list[Path]:
|
|
128
|
+
home = Path(user_home) if user_home else config_home()
|
|
129
|
+
directories = [home / AGENTS_DIR, Path(cwd) / ".coderagent" / AGENTS_DIR]
|
|
130
|
+
return [directory for directory in directories if directory.is_dir()]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class SubAgentRunner:
|
|
134
|
+
"""Runs a sub agent: its own messages, its own tools, its own turn budget."""
|
|
135
|
+
|
|
136
|
+
def __init__(
|
|
137
|
+
self,
|
|
138
|
+
gateway,
|
|
139
|
+
registry: ToolRegistry,
|
|
140
|
+
policy,
|
|
141
|
+
ctx_factory,
|
|
142
|
+
*,
|
|
143
|
+
approver=None,
|
|
144
|
+
gateway_for=None,
|
|
145
|
+
bus: EventBus | None = None,
|
|
146
|
+
session_id: str | Callable[[], str] = "",
|
|
147
|
+
hooks=None,
|
|
148
|
+
before_write=None,
|
|
149
|
+
store=None,
|
|
150
|
+
on_path=None,
|
|
151
|
+
schema_budget: int | None = None,
|
|
152
|
+
max_turns: int = 0,
|
|
153
|
+
max_parallel: int = 0,
|
|
154
|
+
context_config: ContextConfig | None = None,
|
|
155
|
+
memory_config: MemoryConfig | None = None,
|
|
156
|
+
user_home: Path | None = None,
|
|
157
|
+
) -> None:
|
|
158
|
+
self.gateway = gateway
|
|
159
|
+
self.registry = registry
|
|
160
|
+
self.policy = policy
|
|
161
|
+
self.ctx_factory = ctx_factory
|
|
162
|
+
self.approver = approver
|
|
163
|
+
self.gateway_for = gateway_for
|
|
164
|
+
"""Returns the gateway of a purpose. The main gateway when it is not set."""
|
|
165
|
+
self.bus = bus
|
|
166
|
+
self.session_id = session_id
|
|
167
|
+
"""The session the events of the sub agent belong to. A callable follows the session of the loop."""
|
|
168
|
+
self.hooks = hooks
|
|
169
|
+
"""The hook runner of the session. The sub agent goes through the same hooks."""
|
|
170
|
+
self.before_write = before_write
|
|
171
|
+
"""Called before a write tool changes a file, e.g. to take a checkpoint."""
|
|
172
|
+
self.store = store
|
|
173
|
+
"""The event log. The result of a tool of the sub agent lands in it."""
|
|
174
|
+
self.on_path = on_path
|
|
175
|
+
"""Called with the path of every path based tool."""
|
|
176
|
+
self.schema_budget = schema_budget
|
|
177
|
+
"""The tokens the schemas of the tools may take. None means no limit."""
|
|
178
|
+
self.max_turns = max_turns
|
|
179
|
+
"""The ceiling of the turns of every sub agent. 0 means no ceiling."""
|
|
180
|
+
self.max_parallel = max_parallel
|
|
181
|
+
"""How many sub agents may run at the same time. 0 means no limit."""
|
|
182
|
+
self.context_config = context_config or ContextConfig()
|
|
183
|
+
"""The window of the context of the sub agent. It follows the model it runs on."""
|
|
184
|
+
self.memory_config = memory_config or MemoryConfig()
|
|
185
|
+
self.user_home = user_home
|
|
186
|
+
"""The root of the user level data. The sub agent reads the instructions of the user too."""
|
|
187
|
+
self._slots = threading.Semaphore(max_parallel) if max_parallel > 0 else None
|
|
188
|
+
|
|
189
|
+
def run(self, spec: SubagentSpec, description: str, prompt: str) -> dict:
|
|
190
|
+
"""Run the sub agent and return the structured result."""
|
|
191
|
+
if self._slots is None:
|
|
192
|
+
result = self._run(spec, description, prompt)
|
|
193
|
+
else:
|
|
194
|
+
with self._slots:
|
|
195
|
+
"""Only a few sub agents at a time, so the provider is not flooded."""
|
|
196
|
+
result = self._run(spec, description, prompt)
|
|
197
|
+
self._stop(spec, result)
|
|
198
|
+
return result
|
|
199
|
+
|
|
200
|
+
def _stop(self, spec: SubagentSpec, result: dict) -> None:
|
|
201
|
+
"""Tell the hooks that the sub agent is done."""
|
|
202
|
+
if not self.hooks:
|
|
203
|
+
return
|
|
204
|
+
self.hooks.apply(
|
|
205
|
+
"SubagentStop",
|
|
206
|
+
{
|
|
207
|
+
"agent": spec.name,
|
|
208
|
+
"status": result["status"],
|
|
209
|
+
"summary": result["summary"],
|
|
210
|
+
"files_touched": result["files_touched"],
|
|
211
|
+
},
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def _run(self, spec: SubagentSpec, description: str, prompt: str) -> dict:
|
|
215
|
+
registry = self._restricted(spec)
|
|
216
|
+
executor = ToolExecutor(
|
|
217
|
+
registry,
|
|
218
|
+
self.policy,
|
|
219
|
+
self.ctx_factory,
|
|
220
|
+
self.approver,
|
|
221
|
+
hooks=self.hooks,
|
|
222
|
+
before_write=self.before_write,
|
|
223
|
+
store=self.store,
|
|
224
|
+
on_path=self.on_path,
|
|
225
|
+
)
|
|
226
|
+
gateway = self._gateway(spec)
|
|
227
|
+
before = (gateway.total_cost, gateway.total_tokens_in, gateway.total_tokens_out)
|
|
228
|
+
system = spec.system_prompt or spec.description
|
|
229
|
+
block = "\n\n".join(
|
|
230
|
+
text
|
|
231
|
+
for text in (
|
|
232
|
+
mode_block(self.policy.mode),
|
|
233
|
+
network_block(self.policy.network),
|
|
234
|
+
sandbox_block(self.policy.sandbox_mode),
|
|
235
|
+
)
|
|
236
|
+
if text
|
|
237
|
+
)
|
|
238
|
+
if block:
|
|
239
|
+
"""The sub agent shares the permission mode, so it has to know about it too."""
|
|
240
|
+
system = f"{system}\n\n{block}"
|
|
241
|
+
rules = self._project_rules()
|
|
242
|
+
if rules:
|
|
243
|
+
"""The sub agent works in the same project: it has to know the rules of it."""
|
|
244
|
+
system = f"{system}\n\n{rules}"
|
|
245
|
+
messages = [
|
|
246
|
+
{"role": "system", "content": system},
|
|
247
|
+
{"role": "user", "content": f"{description}\n\n{prompt}".strip()},
|
|
248
|
+
]
|
|
249
|
+
schemas = registry.schemas(self.schema_budget)
|
|
250
|
+
budget = self._budget(gateway)
|
|
251
|
+
turns = 0
|
|
252
|
+
touched: list[str] = []
|
|
253
|
+
summary = ""
|
|
254
|
+
status = "completed"
|
|
255
|
+
limit = effective_turns(spec, self.max_turns)
|
|
256
|
+
while not limit or turns < limit:
|
|
257
|
+
_trim(messages, schemas, budget)
|
|
258
|
+
try:
|
|
259
|
+
response = gateway.query(repair_tool_calls(messages), tools=schemas)
|
|
260
|
+
except Exception as e:
|
|
261
|
+
if is_context_overflow(e) and _shrink(messages):
|
|
262
|
+
"""The provider says the context is too big: the oldest turns go,
|
|
263
|
+
and the call is made again."""
|
|
264
|
+
continue
|
|
265
|
+
return self._result("error", f"{type(e).__name__}: {e}", [], [], gateway, before, turns)
|
|
266
|
+
turns += 1
|
|
267
|
+
messages.append(response)
|
|
268
|
+
summary = response.get("content", "") or summary
|
|
269
|
+
calls = response.get("tool_calls") or []
|
|
270
|
+
touched += _paths_of(calls)
|
|
271
|
+
if not calls:
|
|
272
|
+
break
|
|
273
|
+
actions = executor.plan(calls)
|
|
274
|
+
self._publish(actions)
|
|
275
|
+
messages.extend(executor.execute(actions))
|
|
276
|
+
else:
|
|
277
|
+
status = "max_turns"
|
|
278
|
+
return self._result(status, summary, _findings(summary), touched, gateway, before, turns)
|
|
279
|
+
|
|
280
|
+
def _project_rules(self) -> str:
|
|
281
|
+
"""The instructions and the memory of the project, for the sub agent too."""
|
|
282
|
+
return project_text(
|
|
283
|
+
self.ctx_factory().cwd,
|
|
284
|
+
self.user_home,
|
|
285
|
+
self.memory_config,
|
|
286
|
+
self.context_config.project_doc_max_bytes,
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
def _budget(self, gateway) -> int:
|
|
290
|
+
"""The tokens the messages of the sub agent may take.
|
|
291
|
+
|
|
292
|
+
The window belongs to the model the sub agent runs on: it may be a
|
|
293
|
+
different one than the main agent.
|
|
294
|
+
"""
|
|
295
|
+
name = getattr(getattr(gateway, "backend", None), "model_name", "")
|
|
296
|
+
window = context_window_for(name, default=self.context_config.context_window)
|
|
297
|
+
return max(1000, window - self.context_config.reserved_output)
|
|
298
|
+
|
|
299
|
+
def _restricted(self, spec: SubagentSpec) -> ToolRegistry:
|
|
300
|
+
"""The registry with only the tools of the white list."""
|
|
301
|
+
tools = [self.registry.get(name) for name in spec.tools]
|
|
302
|
+
return ToolRegistry([tool for tool in tools if tool is not None])
|
|
303
|
+
|
|
304
|
+
def _gateway(self, spec: SubagentSpec):
|
|
305
|
+
if self.gateway_for is None:
|
|
306
|
+
return self.gateway
|
|
307
|
+
return self.gateway_for(spec.model_purpose) or self.gateway
|
|
308
|
+
|
|
309
|
+
def _publish(self, actions: list[dict]) -> None:
|
|
310
|
+
"""Let the interface know what the sub agent does."""
|
|
311
|
+
if self.bus is None:
|
|
312
|
+
return
|
|
313
|
+
from coderagent.core.events import Event, EventType
|
|
314
|
+
|
|
315
|
+
self.bus.publish(
|
|
316
|
+
Event(
|
|
317
|
+
type=EventType.TOOL_CALL,
|
|
318
|
+
session_id=self.session_id() if callable(self.session_id) else self.session_id,
|
|
319
|
+
timestamp=0.0,
|
|
320
|
+
payload={"actions": actions},
|
|
321
|
+
)
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
def _result(
|
|
325
|
+
self, status: str, summary: str, findings: list[str], touched: list[str], gateway, before, turns: int
|
|
326
|
+
) -> dict:
|
|
327
|
+
"""What the sub agent spent. When it ran on its own model, the cost is booked on the main one."""
|
|
328
|
+
cost = gateway.total_cost - before[0]
|
|
329
|
+
tokens_in = gateway.total_tokens_in - before[1]
|
|
330
|
+
tokens_out = gateway.total_tokens_out - before[2]
|
|
331
|
+
if gateway is not self.gateway:
|
|
332
|
+
self.gateway.total_cost += cost
|
|
333
|
+
self.gateway.total_tokens_in += tokens_in
|
|
334
|
+
self.gateway.total_tokens_out += tokens_out
|
|
335
|
+
return {
|
|
336
|
+
"status": status,
|
|
337
|
+
"summary": summary,
|
|
338
|
+
"findings": findings,
|
|
339
|
+
"files_touched": sorted(set(touched)),
|
|
340
|
+
"cost": cost,
|
|
341
|
+
"tokens_in": tokens_in,
|
|
342
|
+
"tokens_out": tokens_out,
|
|
343
|
+
"turns": turns,
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _trim(messages: list[dict], schemas: list[dict], budget: int) -> None:
|
|
348
|
+
"""Make room: the oldest turns go until the request fits into the window.
|
|
349
|
+
|
|
350
|
+
A sub agent has no summary, so it forgets instead of summarizing.
|
|
351
|
+
"""
|
|
352
|
+
while estimate_tokens(messages, schemas) > budget and _shrink(messages):
|
|
353
|
+
pass
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _shrink(messages: list[dict]) -> bool:
|
|
357
|
+
"""Drop the oldest turn of a sub agent. True when something was dropped.
|
|
358
|
+
|
|
359
|
+
The tool results go with the message that asked for them: a result without its
|
|
360
|
+
call is a history that the provider refuses. When only the last turn is left,
|
|
361
|
+
its results go and the calls are repaired into results that say they did not
|
|
362
|
+
finish.
|
|
363
|
+
"""
|
|
364
|
+
starts = [index for index, message in enumerate(messages) if message.get("role") == "assistant"]
|
|
365
|
+
if len(starts) > 1:
|
|
366
|
+
del messages[starts[0] : starts[1]]
|
|
367
|
+
return True
|
|
368
|
+
if starts and len(messages) > starts[0] + 1:
|
|
369
|
+
del messages[starts[0] + 1 :]
|
|
370
|
+
return True
|
|
371
|
+
return False
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _paths_of(calls: list[dict]) -> list[str]:
|
|
375
|
+
"""The files the tool calls touch."""
|
|
376
|
+
paths = []
|
|
377
|
+
for call in calls:
|
|
378
|
+
function = call.get("function") or {}
|
|
379
|
+
name = function.get("name", "")
|
|
380
|
+
arguments = function.get("arguments")
|
|
381
|
+
if isinstance(arguments, str):
|
|
382
|
+
try:
|
|
383
|
+
arguments = json.loads(arguments or "{}")
|
|
384
|
+
except json.JSONDecodeError:
|
|
385
|
+
continue
|
|
386
|
+
if not isinstance(arguments, dict):
|
|
387
|
+
continue
|
|
388
|
+
path = arguments.get("path")
|
|
389
|
+
if path and name in ("write", "edit", "multi_edit"):
|
|
390
|
+
paths.append(str(path))
|
|
391
|
+
return paths
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _findings(summary: str) -> list[str]:
|
|
395
|
+
"""The bullet points of the conclusion."""
|
|
396
|
+
return [line.lstrip("-* ").strip() for line in summary.splitlines() if line.strip().startswith(("-", "*"))]
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def render_result(result: dict) -> str:
|
|
400
|
+
"""The result of a sub agent, as the main agent reads it."""
|
|
401
|
+
return json.dumps(result, ensure_ascii=False, indent=2)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def subagent_index(specs: dict[str, SubagentSpec]) -> str:
|
|
405
|
+
"""The index of the sub agents, as it goes into the system prompt."""
|
|
406
|
+
if not specs:
|
|
407
|
+
return ""
|
|
408
|
+
lines = [
|
|
409
|
+
"<subagents>",
|
|
410
|
+
"These sub agents are available. Hand a job to one with the `task` tool.",
|
|
411
|
+
*[f"- {spec.render()}" for spec in specs.values()],
|
|
412
|
+
"</subagents>",
|
|
413
|
+
]
|
|
414
|
+
return "\n".join(lines)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
__all__ = [
|
|
418
|
+
"BUILTIN_SUBAGENTS",
|
|
419
|
+
"SubAgentRunner",
|
|
420
|
+
"SubagentSpec",
|
|
421
|
+
"load_subagents",
|
|
422
|
+
"parse_subagent",
|
|
423
|
+
"render_result",
|
|
424
|
+
"subagent_index",
|
|
425
|
+
]
|
|
426
|
+
|
|
427
|
+
BUILTIN_SUBAGENTS.update(
|
|
428
|
+
{
|
|
429
|
+
"code-explorer": SubagentSpec(
|
|
430
|
+
name="code-explorer",
|
|
431
|
+
description="Find code: locate a symbol, follow a call chain, explain how a part works.",
|
|
432
|
+
system_prompt=(
|
|
433
|
+
"You are a code base explorer. Given a target (a symbol, a behaviour or a question), "
|
|
434
|
+
"find the code that matters:\n"
|
|
435
|
+
"1. Narrow the search down with grep and glob.\n"
|
|
436
|
+
"2. Read the files that matter.\n"
|
|
437
|
+
"3. Answer with the files and the line numbers, the relations between them and your judgement.\n\n"
|
|
438
|
+
"Never change a file. Answer with a short summary and a bullet point per finding."
|
|
439
|
+
),
|
|
440
|
+
tools=["read", "grep", "glob", "ls"],
|
|
441
|
+
model_purpose="cheap",
|
|
442
|
+
max_turns=15,
|
|
443
|
+
),
|
|
444
|
+
"verifier": SubagentSpec(
|
|
445
|
+
name="verifier",
|
|
446
|
+
description="Check a result on its own: run the tests, reproduce the bug.",
|
|
447
|
+
system_prompt=(
|
|
448
|
+
"You are a verifier. You do not trust the claims of others, you check them.\n"
|
|
449
|
+
"1. Reproduce the situation: run the tests, the build or the command that fails.\n"
|
|
450
|
+
"2. Read the code that is involved.\n"
|
|
451
|
+
"3. Say what is true: does it work, and what exactly is broken when it does not.\n\n"
|
|
452
|
+
"Never change a file unless the job asks for it. Answer with a short summary and a "
|
|
453
|
+
"bullet point per finding."
|
|
454
|
+
),
|
|
455
|
+
tools=["read", "grep", "glob", "bash"],
|
|
456
|
+
model_purpose="main",
|
|
457
|
+
max_turns=20,
|
|
458
|
+
),
|
|
459
|
+
"refactorer": SubagentSpec(
|
|
460
|
+
name="refactorer",
|
|
461
|
+
description="Change the same pattern everywhere: a rename, a moved helper, a new signature.",
|
|
462
|
+
system_prompt=(
|
|
463
|
+
"You are a refactorer. You make the same change everywhere it is needed and nowhere else.\n"
|
|
464
|
+
"1. Find every place the pattern occurs.\n"
|
|
465
|
+
"2. Change them one by one.\n"
|
|
466
|
+
"3. Run the tests when there are any.\n\n"
|
|
467
|
+
"Answer with a short summary, a bullet point per place you changed and the tests you ran."
|
|
468
|
+
),
|
|
469
|
+
tools=["read", "edit", "grep", "glob"],
|
|
470
|
+
model_purpose="main",
|
|
471
|
+
max_turns=30,
|
|
472
|
+
),
|
|
473
|
+
}
|
|
474
|
+
)
|