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
coderagent/run.py
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
"""Assembly of the coding agent: config -> model -> environment -> session -> loop."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from dataclasses import replace
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from coderagent.config.schema import Config, ContextConfig
|
|
12
|
+
from coderagent.config.writer import write_user_capability
|
|
13
|
+
from coderagent.core import os_sandbox, shell_env
|
|
14
|
+
from coderagent.core.budget import context_window_for
|
|
15
|
+
from coderagent.core.checkpoint import CheckpointStore, create_file_checkpoint
|
|
16
|
+
from coderagent.core.context import ContextEngine
|
|
17
|
+
from coderagent.core.events import Event, EventBus, EventType
|
|
18
|
+
from coderagent.core.loop import AgentLoop, TurnResult
|
|
19
|
+
from coderagent.core.os_sandbox import Confinement
|
|
20
|
+
from coderagent.core.otel import OtlpExporter
|
|
21
|
+
from coderagent.core.protocols import ModelBackend
|
|
22
|
+
from coderagent.core.sandbox import build_environment
|
|
23
|
+
from coderagent.core.session import SessionStore
|
|
24
|
+
from coderagent.core.subagent import SubAgentRunner, load_subagents, subagent_index
|
|
25
|
+
from coderagent.core.telemetry import collect
|
|
26
|
+
from coderagent.environments import is_local
|
|
27
|
+
from coderagent.extensions.hooks import HookRunner
|
|
28
|
+
from coderagent.extensions.plugins import load as load_plugins
|
|
29
|
+
from coderagent.extensions.reflect import (
|
|
30
|
+
PENDING_HEADER,
|
|
31
|
+
MemoryWrite,
|
|
32
|
+
Reflection,
|
|
33
|
+
append_facts,
|
|
34
|
+
append_user_preferences,
|
|
35
|
+
known_memory,
|
|
36
|
+
parse_reflection,
|
|
37
|
+
pending_path,
|
|
38
|
+
project_memory_path,
|
|
39
|
+
reflect_prompt,
|
|
40
|
+
user_memory_path,
|
|
41
|
+
)
|
|
42
|
+
from coderagent.models import verbosity
|
|
43
|
+
from coderagent.models.backends import LiteLLMBackend
|
|
44
|
+
from coderagent.models.gateway import ModelGateway
|
|
45
|
+
from coderagent.models.router import ModelRouter
|
|
46
|
+
from coderagent.paths import config_home
|
|
47
|
+
from coderagent.skills import load_skills, skill_index
|
|
48
|
+
from coderagent.tools.base import ToolContext
|
|
49
|
+
from coderagent.tools.builtin import build_registry
|
|
50
|
+
from coderagent.tools.builtin.skill import SkillTool
|
|
51
|
+
from coderagent.tools.builtin.task import TaskTool
|
|
52
|
+
from coderagent.tools.executor import ToolExecutor
|
|
53
|
+
from coderagent.tools.mcp import MCPManager
|
|
54
|
+
from coderagent.tools.permissions import HeadlessApprover, PermissionPolicy, Rule
|
|
55
|
+
from coderagent.tools.registry import estimate_tokens
|
|
56
|
+
from coderagent.tools.rules import load_rules
|
|
57
|
+
from coderagent.ui.commands import register as register_command
|
|
58
|
+
|
|
59
|
+
logger = logging.getLogger("coderagent.run")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def remember_capability(model: str, modality: str, supported: bool) -> None:
|
|
63
|
+
"""Write what a model takes into the user level configuration file.
|
|
64
|
+
|
|
65
|
+
The file of the user is the only place where it is kept: a project does not
|
|
66
|
+
say what the model of the user takes. A file that cannot be written is not
|
|
67
|
+
a failure of the turn: the answer is in the session anyway.
|
|
68
|
+
"""
|
|
69
|
+
try:
|
|
70
|
+
write_user_capability(model, modality, supported)
|
|
71
|
+
except OSError:
|
|
72
|
+
logger.warning("The capability of the model was not written", exc_info=True)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def build_model(config: Config, model_name: str = "") -> ModelBackend:
|
|
76
|
+
return LiteLLMBackend(
|
|
77
|
+
model_name or config.model.model_name,
|
|
78
|
+
model_kwargs=config.model.model_kwargs,
|
|
79
|
+
set_cache_control=config.model.set_cache_control,
|
|
80
|
+
litellm_config=config.model.litellm_config,
|
|
81
|
+
reasoning_effort=config.model.reasoning_effort,
|
|
82
|
+
max_retries=config.model.max_retries,
|
|
83
|
+
api_key=config.model.api_key,
|
|
84
|
+
api_base=config.model.api_base,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def build_policy(config: Config, cwd: Path, permission_mode: str | None = None) -> PermissionPolicy:
|
|
89
|
+
"""Built-in rules, then the project and user rule files."""
|
|
90
|
+
fields = ("tool", "pattern", "decision", "reason")
|
|
91
|
+
rules = [Rule(**{k: v for k, v in rule.items() if k in fields}) for rule in config.permissions.rules]
|
|
92
|
+
rules += load_rules(cwd)
|
|
93
|
+
return PermissionPolicy(
|
|
94
|
+
permission_mode or config.permissions.mode,
|
|
95
|
+
rules,
|
|
96
|
+
cwd=cwd,
|
|
97
|
+
include_dirs=config.permissions.include_dirs,
|
|
98
|
+
bounded=config.sandbox.type == "local",
|
|
99
|
+
network=config.permissions.network,
|
|
100
|
+
sandbox_mode=config.sandbox.mode,
|
|
101
|
+
deny_paths=config.permissions.deny_paths,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _context_config(config: Config, model_name: str) -> ContextConfig:
|
|
106
|
+
"""The context window follows the model, unless the configuration sets it."""
|
|
107
|
+
if "context_window" in config.context.model_fields_set:
|
|
108
|
+
return config.context
|
|
109
|
+
return config.context.model_copy(update={"context_window": context_window_for(model_name)})
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def purpose_gateway(config: Config, gateway: ModelGateway, purpose: str) -> ModelGateway:
|
|
113
|
+
"""The gateway of a purpose. The main one when the purpose is not routed."""
|
|
114
|
+
name = ModelRouter(config.model, gateway).resolve(purpose)
|
|
115
|
+
if not name or name == config.model.model_name:
|
|
116
|
+
return gateway
|
|
117
|
+
return ModelGateway(build_model(config, name))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def schema_budget(config: Config, context_window: int) -> int:
|
|
121
|
+
"""The tokens the schemas of the tools may take.
|
|
122
|
+
|
|
123
|
+
A tenth of the context window, and never less than the built-in tools need,
|
|
124
|
+
so that a small window does not take a tool away from the agent. The tools
|
|
125
|
+
that go over the budget are dropped, the last useful ones first.
|
|
126
|
+
"""
|
|
127
|
+
if config.tools.schema_budget_tokens:
|
|
128
|
+
return config.tools.schema_budget_tokens
|
|
129
|
+
return max(context_window // 10, estimate_tokens(build_registry().schemas()))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _exporter(config: Config) -> OtlpExporter | None:
|
|
133
|
+
"""Where the trace of the session goes. Nothing when the user did not say."""
|
|
134
|
+
if not config.telemetry.otel_endpoint:
|
|
135
|
+
return None
|
|
136
|
+
return OtlpExporter(
|
|
137
|
+
config.telemetry.otel_endpoint,
|
|
138
|
+
config.telemetry.otel_headers,
|
|
139
|
+
config.telemetry.otel_timeout,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _confinement(config: Config, environment: Any, cwd: Path) -> Confinement | None:
|
|
144
|
+
"""The boundary of the operating system around the commands of the agent.
|
|
145
|
+
|
|
146
|
+
A container is its own boundary, so the mode only reaches the commands
|
|
147
|
+
that run on the machine of the user.
|
|
148
|
+
"""
|
|
149
|
+
if not is_local(environment):
|
|
150
|
+
return None
|
|
151
|
+
return os_sandbox.build(config.sandbox.mode, cwd, config.permissions.include_dirs, config.permissions.network)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def build_store(config: Config) -> SessionStore:
|
|
155
|
+
"""The store of the sessions, with the history policy of the configuration."""
|
|
156
|
+
return SessionStore(
|
|
157
|
+
persist=config.history.persistence != "save-none",
|
|
158
|
+
max_bytes=config.history.max_bytes,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def build_loop(
|
|
163
|
+
config: Config,
|
|
164
|
+
cwd: Path,
|
|
165
|
+
*,
|
|
166
|
+
model: ModelBackend | None = None,
|
|
167
|
+
store: SessionStore | None = None,
|
|
168
|
+
session=None,
|
|
169
|
+
permission_mode: str | None = None,
|
|
170
|
+
bus: EventBus | None = None,
|
|
171
|
+
approver=None,
|
|
172
|
+
user_home: Path | None = None,
|
|
173
|
+
output_schema: dict | None = None,
|
|
174
|
+
enforce_ceilings: bool = False,
|
|
175
|
+
remember: Callable[[str, str, bool], None] | None = None,
|
|
176
|
+
) -> AgentLoop:
|
|
177
|
+
store = store or build_store(config)
|
|
178
|
+
session = session or store.create(cwd)
|
|
179
|
+
user_home = user_home or config_home()
|
|
180
|
+
"""The root of the user level data: the agents, the skills, the plugins, the memory."""
|
|
181
|
+
policy = build_policy(config, cwd, permission_mode)
|
|
182
|
+
session.permission_mode = policy.mode.value
|
|
183
|
+
bus = bus or EventBus()
|
|
184
|
+
registry = build_registry(config.tools.enabled, config.tools.disabled)
|
|
185
|
+
mcp = MCPManager(config.mcp, bus)
|
|
186
|
+
for tool in mcp.start():
|
|
187
|
+
registry.register(tool)
|
|
188
|
+
extensions, plugins = load_plugins(cwd, user_home)
|
|
189
|
+
for tool in extensions.tools.all():
|
|
190
|
+
registry.register(tool)
|
|
191
|
+
for command in extensions.commands:
|
|
192
|
+
register_command(command)
|
|
193
|
+
for event, matchers in extensions.hooks.events.items():
|
|
194
|
+
config.hooks.events.setdefault(event, []).extend(matchers)
|
|
195
|
+
backend = model if model is not None else build_model(config)
|
|
196
|
+
gateway = ModelGateway(backend)
|
|
197
|
+
router = ModelRouter(config.model, gateway)
|
|
198
|
+
if model is not None:
|
|
199
|
+
"""An injected model is the main model, whatever the configuration says."""
|
|
200
|
+
router.main_model = model.get_template_vars().get("model_name", config.model.model_name)
|
|
201
|
+
specs = load_subagents(cwd, user_home)
|
|
202
|
+
skills = load_skills(cwd, user_home)
|
|
203
|
+
environment = build_environment(config.sandbox, cwd)
|
|
204
|
+
if is_local(environment):
|
|
205
|
+
"""The commands of the agent do not see the keys of the user, unless he says so."""
|
|
206
|
+
environment.env_override = shell_env.build(
|
|
207
|
+
config.shell_environment.inherit,
|
|
208
|
+
config.shell_environment.exclude,
|
|
209
|
+
config.shell_environment.include,
|
|
210
|
+
config.shell_environment.set,
|
|
211
|
+
os.environ,
|
|
212
|
+
)
|
|
213
|
+
system_prompt = config.agent.system_prompt
|
|
214
|
+
if config.model.verbosity:
|
|
215
|
+
"""How much the model says. It is an instruction, not a parameter of the provider."""
|
|
216
|
+
system_prompt = f"{system_prompt}\n\n{verbosity.note(config.model.verbosity)}"
|
|
217
|
+
if skill_index(skills):
|
|
218
|
+
system_prompt = f"{system_prompt}\n\n{skill_index(skills)}"
|
|
219
|
+
if subagent_index(specs):
|
|
220
|
+
system_prompt = f"{system_prompt}\n\n{subagent_index(specs)}"
|
|
221
|
+
context_config = _context_config(config, config.model.model_name)
|
|
222
|
+
budget = schema_budget(config, context_config.context_window)
|
|
223
|
+
context = ContextEngine(
|
|
224
|
+
session,
|
|
225
|
+
store,
|
|
226
|
+
bus,
|
|
227
|
+
context_config,
|
|
228
|
+
gateway,
|
|
229
|
+
system_prompt=system_prompt,
|
|
230
|
+
memory_config=config.memory,
|
|
231
|
+
cwd=cwd,
|
|
232
|
+
user_home=user_home,
|
|
233
|
+
summary_model=ModelGateway(build_model(config, config.context.summarize_model))
|
|
234
|
+
if config.context.summarize_model
|
|
235
|
+
else purpose_gateway(config, gateway, "summarize"),
|
|
236
|
+
policy=policy,
|
|
237
|
+
)
|
|
238
|
+
ctx = ToolContext(
|
|
239
|
+
cwd=cwd,
|
|
240
|
+
session=session,
|
|
241
|
+
bus=bus,
|
|
242
|
+
policy=policy,
|
|
243
|
+
config=config.tools,
|
|
244
|
+
env=environment,
|
|
245
|
+
sandbox=_confinement(config, environment, cwd),
|
|
246
|
+
)
|
|
247
|
+
holder: dict[str, AgentLoop] = {}
|
|
248
|
+
"""The loop of this session. The tools have to follow it."""
|
|
249
|
+
|
|
250
|
+
def tool_context() -> ToolContext:
|
|
251
|
+
"""The tool context of the session the loop is in.
|
|
252
|
+
|
|
253
|
+
The loop may go to another session (`/resume`, `/fork`, a conversation
|
|
254
|
+
that goes aside), and then the tools have to follow it: their results
|
|
255
|
+
belong to the log of the session that is running.
|
|
256
|
+
"""
|
|
257
|
+
return replace(ctx, session=holder["loop"].session)
|
|
258
|
+
|
|
259
|
+
checkpoints = CheckpointStore(keep=config.checkpoint.keep)
|
|
260
|
+
hooks = HookRunner(config.hooks, cwd) if config.hooks.events else None
|
|
261
|
+
|
|
262
|
+
def before_write(tool: str, params: dict) -> None:
|
|
263
|
+
"""Snapshot the file before a write tool changes it."""
|
|
264
|
+
path = params.get("path")
|
|
265
|
+
if path and config.checkpoint.enabled:
|
|
266
|
+
loop = holder["loop"]
|
|
267
|
+
create_file_checkpoint(
|
|
268
|
+
checkpoints,
|
|
269
|
+
loop.session.id,
|
|
270
|
+
loop.session.turn_count,
|
|
271
|
+
cwd,
|
|
272
|
+
str(path),
|
|
273
|
+
len(loop.context.history.messages),
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
runner = SubAgentRunner(
|
|
277
|
+
gateway,
|
|
278
|
+
registry,
|
|
279
|
+
policy,
|
|
280
|
+
tool_context,
|
|
281
|
+
approver=approver or HeadlessApprover(allow=False),
|
|
282
|
+
gateway_for=lambda purpose: purpose_gateway(config, gateway, purpose),
|
|
283
|
+
bus=bus,
|
|
284
|
+
session_id=lambda: holder["loop"].session.id,
|
|
285
|
+
hooks=hooks,
|
|
286
|
+
before_write=before_write,
|
|
287
|
+
store=store,
|
|
288
|
+
on_path=lambda path: holder["loop"].context.note_path(path),
|
|
289
|
+
schema_budget=budget,
|
|
290
|
+
max_turns=config.agent.subagent_max_turns,
|
|
291
|
+
max_parallel=config.agent.subagent_max_parallel,
|
|
292
|
+
context_config=context_config,
|
|
293
|
+
memory_config=config.memory,
|
|
294
|
+
user_home=user_home,
|
|
295
|
+
)
|
|
296
|
+
if "task" in config.tools.enabled and "task" not in config.tools.disabled:
|
|
297
|
+
registry.register(TaskTool(runner, specs))
|
|
298
|
+
if "skill" in config.tools.enabled and "skill" not in config.tools.disabled:
|
|
299
|
+
registry.register(SkillTool(skills))
|
|
300
|
+
|
|
301
|
+
executor = ToolExecutor(
|
|
302
|
+
registry,
|
|
303
|
+
policy,
|
|
304
|
+
tool_context,
|
|
305
|
+
approver or HeadlessApprover(allow=False),
|
|
306
|
+
on_path=lambda path: holder["loop"].context.note_path(path),
|
|
307
|
+
before_write=before_write,
|
|
308
|
+
hooks=hooks,
|
|
309
|
+
store=store,
|
|
310
|
+
)
|
|
311
|
+
loop = AgentLoop(
|
|
312
|
+
gateway,
|
|
313
|
+
executor,
|
|
314
|
+
session,
|
|
315
|
+
store,
|
|
316
|
+
bus,
|
|
317
|
+
context=context,
|
|
318
|
+
tools=registry.schemas(budget),
|
|
319
|
+
schema_budget=budget,
|
|
320
|
+
system_prompt=system_prompt,
|
|
321
|
+
max_turns=config.agent.max_turns,
|
|
322
|
+
cost_limit=config.agent.cost_limit,
|
|
323
|
+
token_limit=config.agent.token_limit,
|
|
324
|
+
checkpoints=checkpoints,
|
|
325
|
+
hooks=hooks,
|
|
326
|
+
mcp=mcp,
|
|
327
|
+
subagents=specs,
|
|
328
|
+
router=router,
|
|
329
|
+
plugins=plugins,
|
|
330
|
+
sandbox=environment,
|
|
331
|
+
verify=config.verify,
|
|
332
|
+
exporter=_exporter(config),
|
|
333
|
+
output_schema=output_schema,
|
|
334
|
+
enforce_ceilings=enforce_ceilings,
|
|
335
|
+
capabilities=config.model.capabilities,
|
|
336
|
+
remember=remember,
|
|
337
|
+
)
|
|
338
|
+
holder["loop"] = loop
|
|
339
|
+
ctx.cancel = lambda: bool(loop.cancel and loop.cancel())
|
|
340
|
+
"""A tool that runs long asks the loop whether the turn is still going on."""
|
|
341
|
+
return loop
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def settle_session(
|
|
345
|
+
loop: AgentLoop, config: Config, cwd: Path, confirm=None, user_home: Path | None = None, gateway=None
|
|
346
|
+
) -> Reflection:
|
|
347
|
+
"""Ask the model what is worth remembering and write it down.
|
|
348
|
+
|
|
349
|
+
The facts about the project are written right away. The preferences of the
|
|
350
|
+
user are only written when `confirm` says so, otherwise they wait.
|
|
351
|
+
|
|
352
|
+
The call of the model is a call like any other: it lands in the event log and
|
|
353
|
+
its cost is part of the cost of the session.
|
|
354
|
+
"""
|
|
355
|
+
messages = loop.context.history.messages
|
|
356
|
+
if not messages:
|
|
357
|
+
return Reflection()
|
|
358
|
+
gateway = gateway or purpose_gateway(config, loop.model, "reflect")
|
|
359
|
+
before = gateway.total_cost
|
|
360
|
+
message: dict = {}
|
|
361
|
+
try:
|
|
362
|
+
message = gateway.query(
|
|
363
|
+
[{"role": "user", "content": reflect_prompt(messages, known=known_memory(cwd, config.memory))}]
|
|
364
|
+
)
|
|
365
|
+
except Exception:
|
|
366
|
+
logger.warning("The reflection of the session failed", exc_info=True)
|
|
367
|
+
cost = gateway.total_cost - before
|
|
368
|
+
if gateway is not loop.model:
|
|
369
|
+
"""The reflection ran on its own model, so its cost is booked on the main one."""
|
|
370
|
+
loop.model.total_cost += cost
|
|
371
|
+
reflection = parse_reflection(message.get("content", ""))
|
|
372
|
+
_warn(append_facts(project_memory_path(cwd, config.memory), reflection.project_facts, "# Project memory"))
|
|
373
|
+
if reflection.user_preferences:
|
|
374
|
+
if confirm is not None and confirm(reflection.user_preferences):
|
|
375
|
+
_warn(append_user_preferences(user_memory_path(config.memory, user_home), reflection.user_preferences))
|
|
376
|
+
else:
|
|
377
|
+
_warn(append_facts(pending_path(cwd), reflection.user_preferences, PENDING_HEADER))
|
|
378
|
+
_record_reflection(loop, gateway, cost, message, reflection)
|
|
379
|
+
return reflection
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _warn(write: MemoryWrite) -> None:
|
|
383
|
+
"""Say it when nothing was written, so that a full file is not a silent loss."""
|
|
384
|
+
if write.warning:
|
|
385
|
+
logger.warning("The memory was not written: %s", write.warning)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _record_reflection(
|
|
389
|
+
loop: AgentLoop, gateway: ModelGateway, cost: float, message: dict, reflection: Reflection
|
|
390
|
+
) -> None:
|
|
391
|
+
"""Put the reflection in the event log, so that the money it cost is in the trace."""
|
|
392
|
+
extra = message.get("extra") or {}
|
|
393
|
+
event = Event(
|
|
394
|
+
type=EventType.REFLECTION,
|
|
395
|
+
session_id=loop.session.id,
|
|
396
|
+
timestamp=time.time(),
|
|
397
|
+
payload={
|
|
398
|
+
"cost": cost,
|
|
399
|
+
"priced": gateway.priced,
|
|
400
|
+
"purpose": "reflect",
|
|
401
|
+
"model": getattr(gateway.backend, "model_name", ""),
|
|
402
|
+
"tokens_in": int(extra.get("tokens_in") or 0),
|
|
403
|
+
"tokens_out": int(extra.get("tokens_out") or 0),
|
|
404
|
+
"project_facts": reflection.project_facts,
|
|
405
|
+
"user_preferences": reflection.user_preferences,
|
|
406
|
+
},
|
|
407
|
+
)
|
|
408
|
+
loop.bus.publish(event)
|
|
409
|
+
loop.store.append(loop.session.id, event)
|
|
410
|
+
loop.session.total_cost += cost
|
|
411
|
+
"""The reflection is not part of a turn, so its cost is added to the session directly."""
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def settle(loop: AgentLoop, config: Config, cwd: Path) -> Reflection:
|
|
415
|
+
"""Settle the session in the memory. A failure here must not break the run."""
|
|
416
|
+
if not config.memory.enabled:
|
|
417
|
+
return Reflection()
|
|
418
|
+
try:
|
|
419
|
+
return settle_session(loop, config, cwd)
|
|
420
|
+
except Exception:
|
|
421
|
+
logger.warning("The reflection of the session failed", exc_info=True)
|
|
422
|
+
return Reflection()
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def run_turn(
|
|
426
|
+
task: str,
|
|
427
|
+
config: Config,
|
|
428
|
+
*,
|
|
429
|
+
cwd: Path,
|
|
430
|
+
model: ModelBackend | None = None,
|
|
431
|
+
store: SessionStore | None = None,
|
|
432
|
+
session=None,
|
|
433
|
+
permission_mode: str | None = None,
|
|
434
|
+
output_schema: dict | None = None,
|
|
435
|
+
remember: Callable[[str, str, bool], None] | None = None,
|
|
436
|
+
) -> TurnResult:
|
|
437
|
+
loop = build_loop(
|
|
438
|
+
config,
|
|
439
|
+
cwd,
|
|
440
|
+
model=model,
|
|
441
|
+
store=store,
|
|
442
|
+
session=session,
|
|
443
|
+
permission_mode=permission_mode,
|
|
444
|
+
output_schema=output_schema,
|
|
445
|
+
remember=remember,
|
|
446
|
+
)
|
|
447
|
+
result = loop.run_turn(task)
|
|
448
|
+
"""A session that ends is settled in the memory, the same way as in the interface."""
|
|
449
|
+
if result.stop_reason not in ("error", "cost_exceeded"):
|
|
450
|
+
"""A turn that failed or ran out of budget has nothing to remember, and no money to do it."""
|
|
451
|
+
settle(loop, config, cwd)
|
|
452
|
+
result.session_cost = collect(loop.store.events(loop.session.id)).total_cost
|
|
453
|
+
"""What the whole session cost, read from the event log."""
|
|
454
|
+
return result
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Skills: a reusable package of instructions, scripts and resources.
|
|
2
|
+
|
|
3
|
+
A skill is a directory with a `SKILL.md` in it:
|
|
4
|
+
|
|
5
|
+
.coderagent/skills/pdf-report/
|
|
6
|
+
├── SKILL.md
|
|
7
|
+
├── scripts/
|
|
8
|
+
│ └── make_report.py
|
|
9
|
+
└── assets/
|
|
10
|
+
└── template.docx
|
|
11
|
+
|
|
12
|
+
The front matter of `SKILL.md` says what the skill is for:
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
name: pdf-report
|
|
16
|
+
description: Make a PDF report out of a folder of notes.
|
|
17
|
+
---
|
|
18
|
+
Use `scripts/make_report.py` to build the report...
|
|
19
|
+
|
|
20
|
+
The index of the skills goes into the system prompt. The model decides to load one
|
|
21
|
+
when the description fits the task, and gets the whole instruction then.
|
|
22
|
+
|
|
23
|
+
This module only reads the skills that are on the disk. Downloading them is in
|
|
24
|
+
`coderagent.skills.source` and putting them there is in `coderagent.skills.install`.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
import yaml
|
|
31
|
+
|
|
32
|
+
from coderagent.paths import config_home
|
|
33
|
+
|
|
34
|
+
SKILLS_DIR = "skills"
|
|
35
|
+
"""The directory of the skills. In the project it is under `.coderagent`."""
|
|
36
|
+
SKILL_FILE = "SKILL.md"
|
|
37
|
+
|
|
38
|
+
PRESETS = Path(__file__).parent / "presets"
|
|
39
|
+
"""The skills that come with the agent. The user and the project may shadow them."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Skill:
|
|
44
|
+
"""A skill the agent may use."""
|
|
45
|
+
|
|
46
|
+
name: str
|
|
47
|
+
description: str = ""
|
|
48
|
+
body: str = ""
|
|
49
|
+
"""The instructions of the skill."""
|
|
50
|
+
path: Path | None = None
|
|
51
|
+
directory: Path | None = None
|
|
52
|
+
|
|
53
|
+
def render(self) -> str:
|
|
54
|
+
"""The whole skill, as the model reads it when it loads it."""
|
|
55
|
+
return f'<skill name="{self.name}">\n{self.body.strip()}\n</skill>'
|
|
56
|
+
|
|
57
|
+
def index_line(self) -> str:
|
|
58
|
+
"""The one line of the index."""
|
|
59
|
+
return f"- {self.name}: {self.description}" if self.description else f"- {self.name}"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def parse_skill(path: Path) -> Skill | None:
|
|
63
|
+
"""Read one `SKILL.md`. Returns None when the file cannot be used."""
|
|
64
|
+
text = path.read_text(encoding="utf-8")
|
|
65
|
+
if not text.startswith("---"):
|
|
66
|
+
return None
|
|
67
|
+
_, _, rest = text.partition("---")
|
|
68
|
+
front_matter, _, body = rest.partition("---")
|
|
69
|
+
try:
|
|
70
|
+
data = yaml.safe_load(front_matter) or {}
|
|
71
|
+
except yaml.YAMLError:
|
|
72
|
+
return None
|
|
73
|
+
if not isinstance(data, dict):
|
|
74
|
+
return None
|
|
75
|
+
return Skill(
|
|
76
|
+
name=str(data.get("name") or path.parent.name),
|
|
77
|
+
description=str(data.get("description", "")),
|
|
78
|
+
body=body.strip(),
|
|
79
|
+
path=path,
|
|
80
|
+
directory=path.parent,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def load_skills(cwd: Path, user_home: Path | None = None) -> dict[str, Skill]:
|
|
85
|
+
"""The skills of the presets, of the user and of the project.
|
|
86
|
+
|
|
87
|
+
The later ones win on a name clash: a skill of the project beats a skill
|
|
88
|
+
of the user, and a skill of the user beats a skill that comes with the
|
|
89
|
+
agent.
|
|
90
|
+
"""
|
|
91
|
+
skills: dict[str, Skill] = {}
|
|
92
|
+
for directory in _directories(cwd, user_home):
|
|
93
|
+
for path in sorted(directory.glob(f"*/{SKILL_FILE}")):
|
|
94
|
+
skill = parse_skill(path)
|
|
95
|
+
if skill is not None:
|
|
96
|
+
skills[skill.name] = skill
|
|
97
|
+
return skills
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _directories(cwd: Path, user_home: Path | None) -> list[Path]:
|
|
101
|
+
home = Path(user_home) if user_home else config_home()
|
|
102
|
+
directories = [PRESETS, home / SKILLS_DIR, Path(cwd) / ".coderagent" / SKILLS_DIR]
|
|
103
|
+
return [directory for directory in directories if directory.is_dir()]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def skill_index(skills: dict[str, Skill]) -> str:
|
|
107
|
+
"""The index of the skills, as it goes into the system prompt."""
|
|
108
|
+
if not skills:
|
|
109
|
+
return ""
|
|
110
|
+
lines = [
|
|
111
|
+
"<skills>",
|
|
112
|
+
"These skills are available. Load one with the `skill` tool when its description fits the task.",
|
|
113
|
+
*[skill.index_line() for skill in skills.values()],
|
|
114
|
+
"</skills>",
|
|
115
|
+
]
|
|
116
|
+
return "\n".join(lines)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
__all__ = ["PRESETS", "SKILL_FILE", "SKILLS_DIR", "Skill", "load_skills", "parse_skill", "skill_index"]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""The errors of the skill hub: something did not work, and the reason is for a person."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class SkillError(Exception):
|
|
5
|
+
"""A skill could not be fetched, checked or installed.
|
|
6
|
+
|
|
7
|
+
The message is written for the user of the page, not for a log file.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
__all__ = ["SkillError"]
|