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,218 @@
|
|
|
1
|
+
"""Writing the user level configuration file.
|
|
2
|
+
|
|
3
|
+
The project level file is never written: it is in the repository. The writing
|
|
4
|
+
never calls the model: a configuration that does not work yet is worth writing
|
|
5
|
+
down, to be fixed later.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import yaml
|
|
12
|
+
|
|
13
|
+
from coderagent.config.loader import DEFAULTS_PATH
|
|
14
|
+
from coderagent.config.schema import PURPOSES, ModelConfig, PermissionConfig, check_routing_rule
|
|
15
|
+
from coderagent.models.call import check_reserved
|
|
16
|
+
from coderagent.models.reasoning import EFFORTS
|
|
17
|
+
from coderagent.models.settings import api_base_of
|
|
18
|
+
from coderagent.models.verbosity import VERBOSITIES
|
|
19
|
+
from coderagent.paths import config_home
|
|
20
|
+
from coderagent.tools.permissions import NETWORK_POLICIES, PermissionMode
|
|
21
|
+
|
|
22
|
+
PERMISSION_MODES = [mode.value for mode in PermissionMode]
|
|
23
|
+
"""The permission modes the browser can choose from."""
|
|
24
|
+
|
|
25
|
+
PERMISSION_FIELDS = ("mode", "deny_paths", "include_dirs", "network")
|
|
26
|
+
"""The permission settings that live directly under `permissions:`."""
|
|
27
|
+
|
|
28
|
+
SECRET_FIELDS = ("api_base", "api_key")
|
|
29
|
+
"""The settings of the model that have a field of their own, next to `model_kwargs`."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def user_config_path() -> Path:
|
|
33
|
+
"""The configuration file of the user."""
|
|
34
|
+
return config_home() / "config.yaml"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _default_model() -> dict[str, Any]:
|
|
38
|
+
"""The model settings of a fresh installation: the ones the user never wrote.
|
|
39
|
+
|
|
40
|
+
A setting that is this one is not written to the user file: the shipped
|
|
41
|
+
default may change, and a user who never touched the setting must get the
|
|
42
|
+
new one.
|
|
43
|
+
"""
|
|
44
|
+
defaults = yaml.safe_load(DEFAULTS_PATH.read_text(encoding="utf-8")) or {}
|
|
45
|
+
return {**ModelConfig().model_dump(), **(defaults.get("model") or {})}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _keep(model: dict, key: str, value: Any, default: Any) -> None:
|
|
49
|
+
"""Write a setting, or drop it when it is the default."""
|
|
50
|
+
if value == default:
|
|
51
|
+
model.pop(key, None)
|
|
52
|
+
else:
|
|
53
|
+
model[key] = value
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def write_user_capability(model: str, modality: str, supported: bool) -> Path:
|
|
57
|
+
"""Remember what a model takes, in the user level configuration file.
|
|
58
|
+
|
|
59
|
+
A project does not say what the model of the user takes, so this is written
|
|
60
|
+
to the file of the user: the next session reads it and does not ask again.
|
|
61
|
+
"""
|
|
62
|
+
path = user_config_path()
|
|
63
|
+
data = yaml.safe_load(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
64
|
+
if not isinstance(data, dict):
|
|
65
|
+
data = {}
|
|
66
|
+
section = data.get("model")
|
|
67
|
+
if not isinstance(section, dict):
|
|
68
|
+
section = {}
|
|
69
|
+
capabilities = section.get("capabilities")
|
|
70
|
+
if not isinstance(capabilities, dict):
|
|
71
|
+
capabilities = {}
|
|
72
|
+
takes = capabilities.get(model)
|
|
73
|
+
if not isinstance(takes, dict):
|
|
74
|
+
takes = {}
|
|
75
|
+
capabilities[model] = {**takes, modality: bool(supported)}
|
|
76
|
+
section["capabilities"] = capabilities
|
|
77
|
+
data["model"] = section
|
|
78
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
79
|
+
path.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True), encoding="utf-8")
|
|
80
|
+
return path
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def write_user_permissions(payload: dict) -> Path:
|
|
84
|
+
"""Merge the permission settings into the user level configuration file.
|
|
85
|
+
|
|
86
|
+
The rules are not touched: they are edited by the approvals of the chat
|
|
87
|
+
page, not here. A setting that is the shipped default is not written at
|
|
88
|
+
all, so that a later change of the default reaches the user who never
|
|
89
|
+
touched it.
|
|
90
|
+
"""
|
|
91
|
+
path = user_config_path()
|
|
92
|
+
data = yaml.safe_load(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
93
|
+
if not isinstance(data, dict):
|
|
94
|
+
data = {}
|
|
95
|
+
permissions = data.get("permissions")
|
|
96
|
+
if not isinstance(permissions, dict):
|
|
97
|
+
permissions = {}
|
|
98
|
+
defaults = PermissionConfig().model_dump()
|
|
99
|
+
|
|
100
|
+
mode = payload.get("mode")
|
|
101
|
+
if isinstance(mode, str) and mode.strip():
|
|
102
|
+
if mode.strip() not in PERMISSION_MODES:
|
|
103
|
+
raise ValueError(f"unknown permission mode '{mode}'")
|
|
104
|
+
_keep(permissions, "mode", mode.strip(), defaults["mode"])
|
|
105
|
+
for field in ("deny_paths", "include_dirs"):
|
|
106
|
+
values = payload.get(field)
|
|
107
|
+
if isinstance(values, list):
|
|
108
|
+
_keep(permissions, field, [str(value).strip() for value in values if str(value).strip()], defaults[field])
|
|
109
|
+
network = payload.get("network")
|
|
110
|
+
if isinstance(network, str) and network.strip():
|
|
111
|
+
if network.strip() not in NETWORK_POLICIES:
|
|
112
|
+
raise ValueError(f"unknown network policy '{network}'")
|
|
113
|
+
_keep(permissions, "network", network.strip(), defaults["network"])
|
|
114
|
+
|
|
115
|
+
if permissions:
|
|
116
|
+
data["permissions"] = permissions
|
|
117
|
+
else:
|
|
118
|
+
data.pop("permissions", None)
|
|
119
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
120
|
+
path.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True), encoding="utf-8")
|
|
121
|
+
return path
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def write_user_model(payload: dict) -> Path:
|
|
125
|
+
"""Merge the model settings into the user level configuration file.
|
|
126
|
+
|
|
127
|
+
The project level file is never written: it is in the repository. The
|
|
128
|
+
sections the page does not know about are kept as they are. A setting that
|
|
129
|
+
is the shipped default is not written at all, so that a later change of the
|
|
130
|
+
default reaches the user who never touched it.
|
|
131
|
+
"""
|
|
132
|
+
path = user_config_path()
|
|
133
|
+
data = yaml.safe_load(path.read_text(encoding="utf-8")) if path.exists() else {}
|
|
134
|
+
if not isinstance(data, dict):
|
|
135
|
+
data = {}
|
|
136
|
+
model = data.get("model")
|
|
137
|
+
if not isinstance(model, dict):
|
|
138
|
+
model = {}
|
|
139
|
+
kwargs = model.get("model_kwargs")
|
|
140
|
+
if not isinstance(kwargs, dict):
|
|
141
|
+
kwargs = {}
|
|
142
|
+
defaults = _default_model()
|
|
143
|
+
|
|
144
|
+
for field in SECRET_FIELDS:
|
|
145
|
+
"""The key and the address have a field of their own now: the old place is left."""
|
|
146
|
+
legacy = kwargs.pop(field, None)
|
|
147
|
+
if legacy is not None:
|
|
148
|
+
model.setdefault(field, legacy)
|
|
149
|
+
|
|
150
|
+
name = payload.get("model_name")
|
|
151
|
+
if isinstance(name, str):
|
|
152
|
+
_keep(model, "model_name", name.strip(), defaults["model_name"])
|
|
153
|
+
aliases = payload.get("litellm_config")
|
|
154
|
+
if isinstance(aliases, str):
|
|
155
|
+
_keep(model, "litellm_config", aliases.strip(), defaults["litellm_config"])
|
|
156
|
+
base = payload.get("api_base")
|
|
157
|
+
if isinstance(base, str):
|
|
158
|
+
if base.strip():
|
|
159
|
+
model["api_base"] = api_base_of(base)
|
|
160
|
+
else:
|
|
161
|
+
model.pop("api_base", None)
|
|
162
|
+
key = payload.get("api_key")
|
|
163
|
+
if isinstance(key, str):
|
|
164
|
+
"""An empty key removes it, a missing one keeps it."""
|
|
165
|
+
if key.strip():
|
|
166
|
+
model["api_key"] = key.strip()
|
|
167
|
+
else:
|
|
168
|
+
model.pop("api_key", None)
|
|
169
|
+
if payload.get("max_retries") is not None:
|
|
170
|
+
_keep(model, "max_retries", int(payload["max_retries"]), defaults["max_retries"])
|
|
171
|
+
cache = payload.get("set_cache_control")
|
|
172
|
+
if cache is not None:
|
|
173
|
+
_keep(model, "set_cache_control", cache or None, defaults["set_cache_control"])
|
|
174
|
+
effort = payload.get("reasoning_effort")
|
|
175
|
+
if isinstance(effort, str):
|
|
176
|
+
if effort.strip() and effort.strip() not in EFFORTS:
|
|
177
|
+
raise ValueError(f"unknown reasoning effort '{effort}'")
|
|
178
|
+
_keep(model, "reasoning_effort", effort.strip(), defaults["reasoning_effort"])
|
|
179
|
+
verbosity = payload.get("verbosity")
|
|
180
|
+
if isinstance(verbosity, str):
|
|
181
|
+
if verbosity.strip() and verbosity.strip() not in VERBOSITIES:
|
|
182
|
+
raise ValueError(f"unknown verbosity '{verbosity}'")
|
|
183
|
+
_keep(model, "verbosity", verbosity.strip(), defaults["verbosity"])
|
|
184
|
+
review = payload.get("review_model")
|
|
185
|
+
if isinstance(review, str):
|
|
186
|
+
_keep(model, "review_model", review.strip(), defaults["review_model"])
|
|
187
|
+
routing = payload.get("routing")
|
|
188
|
+
if isinstance(routing, dict):
|
|
189
|
+
for purpose in routing:
|
|
190
|
+
if purpose not in PURPOSES:
|
|
191
|
+
raise ValueError(f"unknown purpose '{purpose}'. Use one of: {', '.join(PURPOSES)}.")
|
|
192
|
+
_keep(model, "routing", {str(key): str(value) for key, value in routing.items()}, defaults["routing"])
|
|
193
|
+
rules = payload.get("routing_rules")
|
|
194
|
+
if isinstance(rules, list):
|
|
195
|
+
for rule in rules:
|
|
196
|
+
if isinstance(rule, dict):
|
|
197
|
+
check_routing_rule(rule)
|
|
198
|
+
_keep(model, "routing_rules", [rule for rule in rules if isinstance(rule, dict)], defaults["routing_rules"])
|
|
199
|
+
extra = payload.get("model_kwargs")
|
|
200
|
+
if isinstance(extra, dict):
|
|
201
|
+
for key, value in extra.items():
|
|
202
|
+
if key in SECRET_FIELDS:
|
|
203
|
+
continue
|
|
204
|
+
kwargs[str(key)] = value
|
|
205
|
+
check_reserved(kwargs)
|
|
206
|
+
"""The page may not write a file that breaks the agent: the agent refuses it at the start."""
|
|
207
|
+
|
|
208
|
+
if kwargs:
|
|
209
|
+
model["model_kwargs"] = kwargs
|
|
210
|
+
else:
|
|
211
|
+
model.pop("model_kwargs", None)
|
|
212
|
+
if model:
|
|
213
|
+
data["model"] = model
|
|
214
|
+
else:
|
|
215
|
+
data.pop("model", None)
|
|
216
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
217
|
+
path.write_text(yaml.safe_dump(data, sort_keys=False, allow_unicode=True), encoding="utf-8")
|
|
218
|
+
return path
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Core abstractions: protocols, events, session, agent loop."""
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""The token budget: how much of the context window is left for the conversation."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from coderagent.models.provider import split
|
|
6
|
+
|
|
7
|
+
MODEL_CONTEXT_WINDOWS = {
|
|
8
|
+
"gpt-": 128000,
|
|
9
|
+
"claude": 200000,
|
|
10
|
+
"deepseek": 64000,
|
|
11
|
+
"qwen": 32768,
|
|
12
|
+
"llama": 8192,
|
|
13
|
+
"gemini": 1000000,
|
|
14
|
+
"mistral": 32768,
|
|
15
|
+
"kimi": 262144,
|
|
16
|
+
"minimax": 204800,
|
|
17
|
+
}
|
|
18
|
+
"""Context windows of the model families we know. Matched as a prefix of the
|
|
19
|
+
model name or of the part after the provider."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def context_window_for(model_name: str, default: int = 200000) -> int:
|
|
23
|
+
"""The context window of a model, looked up by name."""
|
|
24
|
+
name = split(model_name)[1].split("/")[-1].lower()
|
|
25
|
+
for prefix, window in MODEL_CONTEXT_WINDOWS.items():
|
|
26
|
+
if name.startswith(prefix):
|
|
27
|
+
return window
|
|
28
|
+
return default
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class BudgetGuard:
|
|
33
|
+
context_window: int = 200000
|
|
34
|
+
reserved_output: int = 8000
|
|
35
|
+
compact_threshold: float = 0.8
|
|
36
|
+
|
|
37
|
+
def limit(self) -> int:
|
|
38
|
+
"""Tokens available for the context itself."""
|
|
39
|
+
return max(0, self.context_window - self.reserved_output)
|
|
40
|
+
|
|
41
|
+
def target(self) -> int:
|
|
42
|
+
"""The tokens the conversation may take before it has to be compacted."""
|
|
43
|
+
return min(int(self.context_window * self.compact_threshold), self.limit())
|
|
44
|
+
|
|
45
|
+
def should_compact(self, estimated: int) -> bool:
|
|
46
|
+
"""True when the conversation is close enough to the limit to compact."""
|
|
47
|
+
return estimated > self.target()
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""What a model can take: the pictures, the sound, the video.
|
|
2
|
+
|
|
3
|
+
A model that cannot see a picture answers anyway, and the answer is made up.
|
|
4
|
+
So the agent asks before it sends: the user says what a model takes, litellm
|
|
5
|
+
says it for the models it knows, and the agent tries it out for the models
|
|
6
|
+
nobody knows about.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import struct
|
|
11
|
+
import zlib
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from functools import cache
|
|
14
|
+
|
|
15
|
+
from coderagent.core.content import parts
|
|
16
|
+
from coderagent.models import litellm_module
|
|
17
|
+
|
|
18
|
+
MODALITIES = {
|
|
19
|
+
"image": "supports_vision",
|
|
20
|
+
"audio": "supports_audio_input",
|
|
21
|
+
"video": "supports_video_input",
|
|
22
|
+
}
|
|
23
|
+
"""The kinds of content that are not text, and the key litellm knows them by."""
|
|
24
|
+
|
|
25
|
+
TAKES = {
|
|
26
|
+
"image": "take pictures",
|
|
27
|
+
"audio": "take sound",
|
|
28
|
+
"video": "take video",
|
|
29
|
+
}
|
|
30
|
+
"""How to say it in a sentence."""
|
|
31
|
+
|
|
32
|
+
PROBE_QUESTION = "What color is this picture? Answer with one word."
|
|
33
|
+
"""The question the probe asks. The answer of a model that sees is short."""
|
|
34
|
+
|
|
35
|
+
PROBE_PICTURES = {
|
|
36
|
+
"image": ((255, 0, 255), ("magenta", "purple", "pink", "fuchsia", "violet")),
|
|
37
|
+
}
|
|
38
|
+
"""The color of the picture of the probe, and the words that name it.
|
|
39
|
+
|
|
40
|
+
A color nobody guesses by accident: a model that cannot see the picture has
|
|
41
|
+
nothing to say about it.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
PROBE_TRIES = 2
|
|
45
|
+
"""How many times the probe asks. A relay station answers nothing now and then."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@cache
|
|
49
|
+
def _info(model_name: str) -> dict | None:
|
|
50
|
+
"""What litellm knows about a model. None when it does not know it."""
|
|
51
|
+
try:
|
|
52
|
+
return litellm_module().get_model_info(model_name)
|
|
53
|
+
except Exception:
|
|
54
|
+
"""A relay station names its models in its own way: litellm does not know them."""
|
|
55
|
+
return None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def support(names: list[str], modality: str, declared: dict | None = None) -> bool | None:
|
|
59
|
+
"""Whether the model takes this kind of content.
|
|
60
|
+
|
|
61
|
+
`names` are the names of the model: the one the user wrote and the one
|
|
62
|
+
litellm knows. `declared` is what the user said about the models.
|
|
63
|
+
|
|
64
|
+
None means: nobody knows. The agent does not send the content then: the
|
|
65
|
+
model would answer about something it cannot see.
|
|
66
|
+
"""
|
|
67
|
+
for name in names:
|
|
68
|
+
said = (declared or {}).get(name, {}).get(modality)
|
|
69
|
+
if said is not None:
|
|
70
|
+
return bool(said)
|
|
71
|
+
key = MODALITIES.get(modality)
|
|
72
|
+
if not key:
|
|
73
|
+
return None
|
|
74
|
+
for name in names:
|
|
75
|
+
info = _info(name)
|
|
76
|
+
if info is None:
|
|
77
|
+
continue
|
|
78
|
+
value = info.get(key)
|
|
79
|
+
if value is not None:
|
|
80
|
+
return bool(value)
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _png(rgb: tuple[int, int, int], size: int = 32) -> bytes:
|
|
85
|
+
"""A picture of one solid color, as a PNG. It is built here: the probe needs no file."""
|
|
86
|
+
rows = b"".join(b"\x00" + bytes(rgb) * size for _ in range(size))
|
|
87
|
+
|
|
88
|
+
def chunk(tag: bytes, data: bytes) -> bytes:
|
|
89
|
+
body = tag + data
|
|
90
|
+
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
|
|
91
|
+
|
|
92
|
+
return (
|
|
93
|
+
b"\x89PNG\r\n\x1a\n"
|
|
94
|
+
+ chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0))
|
|
95
|
+
+ chunk(b"IDAT", zlib.compress(rows))
|
|
96
|
+
+ chunk(b"IEND", b"")
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def probe_picture(modality: str) -> str:
|
|
101
|
+
"""The picture of the probe, as the data url a provider takes."""
|
|
102
|
+
rgb, _ = PROBE_PICTURES[modality]
|
|
103
|
+
return "data:image/png;base64," + base64.b64encode(_png(rgb)).decode("ascii")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def probe(query: Callable[[list[dict]], str], modality: str) -> bool | None:
|
|
107
|
+
"""Whether the model takes this kind of content: it is asked about a picture.
|
|
108
|
+
|
|
109
|
+
`query` sends the messages and returns the answer of the model. True when the
|
|
110
|
+
answer names the color of the picture, False when the answer says something
|
|
111
|
+
else, None when nobody knows: the model did not answer, or it does not take
|
|
112
|
+
this kind of content at all.
|
|
113
|
+
"""
|
|
114
|
+
if modality not in PROBE_PICTURES:
|
|
115
|
+
"""Only a picture can be asked about. The sound and the video cannot."""
|
|
116
|
+
return None
|
|
117
|
+
_, words = PROBE_PICTURES[modality]
|
|
118
|
+
url = probe_picture(modality)
|
|
119
|
+
for _ in range(PROBE_TRIES):
|
|
120
|
+
try:
|
|
121
|
+
answer = query([{"role": "user", "content": parts(PROBE_QUESTION, [url])}])
|
|
122
|
+
except Exception as error:
|
|
123
|
+
text = str(error).lower()
|
|
124
|
+
if any(word in text for word in ("image", "vision", "picture", "multimodal")):
|
|
125
|
+
"""The provider says it does not take pictures. That is an answer."""
|
|
126
|
+
return False
|
|
127
|
+
return None
|
|
128
|
+
said = str(answer or "").strip().lower()
|
|
129
|
+
if not said:
|
|
130
|
+
"""The relay station answers nothing now and then. It is asked again."""
|
|
131
|
+
continue
|
|
132
|
+
return any(word in said for word in words)
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
__all__ = ["MODALITIES", "PROBE_QUESTION", "TAKES", "probe", "probe_picture", "support"]
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Checkpoints: the file contents as they were before the agent changed them.
|
|
2
|
+
|
|
3
|
+
A checkpoint is taken before every write. Rewinding restores the old contents.
|
|
4
|
+
Only files are rolled back: what a command did to the outside world stays done.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import time
|
|
9
|
+
import uuid
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from coderagent.core.redact import has_secret, redact
|
|
14
|
+
from coderagent.paths import config_home
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class Checkpoint:
|
|
19
|
+
id: str
|
|
20
|
+
timestamp: float
|
|
21
|
+
turn: int
|
|
22
|
+
kind: str
|
|
23
|
+
"""`file_diff` for the file contents, `container_commit` for a container image."""
|
|
24
|
+
payload: dict = field(default_factory=dict)
|
|
25
|
+
"""For `file_diff`: `{path: old_content}`, where `None` means the file did not exist."""
|
|
26
|
+
messages: int = 0
|
|
27
|
+
"""How many messages the conversation had when the checkpoint was taken."""
|
|
28
|
+
redacted: list[str] = field(default_factory=list)
|
|
29
|
+
"""The paths whose content held a secret, so it cannot be put back exactly."""
|
|
30
|
+
|
|
31
|
+
def to_dict(self) -> dict:
|
|
32
|
+
return {
|
|
33
|
+
"id": self.id,
|
|
34
|
+
"timestamp": self.timestamp,
|
|
35
|
+
"turn": self.turn,
|
|
36
|
+
"kind": self.kind,
|
|
37
|
+
"payload": self.payload,
|
|
38
|
+
"messages": self.messages,
|
|
39
|
+
"redacted": self.redacted,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def from_dict(cls, data: dict) -> "Checkpoint":
|
|
44
|
+
return cls(
|
|
45
|
+
id=data["id"],
|
|
46
|
+
timestamp=data.get("timestamp", 0.0),
|
|
47
|
+
turn=data.get("turn", 0),
|
|
48
|
+
kind=data.get("kind", "file_diff"),
|
|
49
|
+
payload=data.get("payload", {}),
|
|
50
|
+
messages=data.get("messages", 0),
|
|
51
|
+
redacted=data.get("redacted", []),
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def paths(self) -> list[str]:
|
|
56
|
+
return list(self.payload)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class CheckpointStore:
|
|
60
|
+
"""The checkpoints of a session, on disk."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, root: Path | None = None, keep: int = 50) -> None:
|
|
63
|
+
self.root = Path(root) if root else config_home() / "checkpoints"
|
|
64
|
+
self.keep = keep
|
|
65
|
+
|
|
66
|
+
def path(self, session_id: str) -> Path:
|
|
67
|
+
return self.root / f"{session_id}.json"
|
|
68
|
+
|
|
69
|
+
def create(
|
|
70
|
+
self, session_id: str, turn: int, kind: str, payload: dict, messages: int = 0, redacted: list[str] | None = None
|
|
71
|
+
) -> Checkpoint:
|
|
72
|
+
checkpoint = Checkpoint(
|
|
73
|
+
id=f"{time.strftime('%Y%m%d')}-{uuid.uuid4().hex[:6]}",
|
|
74
|
+
timestamp=time.time(),
|
|
75
|
+
turn=turn,
|
|
76
|
+
kind=kind,
|
|
77
|
+
payload=payload,
|
|
78
|
+
messages=messages,
|
|
79
|
+
redacted=redacted or [],
|
|
80
|
+
)
|
|
81
|
+
checkpoints = self.all(session_id)
|
|
82
|
+
checkpoints.append(checkpoint)
|
|
83
|
+
self._write(session_id, checkpoints[-self.keep :])
|
|
84
|
+
return checkpoint
|
|
85
|
+
|
|
86
|
+
def all(self, session_id: str) -> list[Checkpoint]:
|
|
87
|
+
path = self.path(session_id)
|
|
88
|
+
if not path.exists():
|
|
89
|
+
return []
|
|
90
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
91
|
+
return [Checkpoint.from_dict(item) for item in data]
|
|
92
|
+
|
|
93
|
+
def get(self, session_id: str, checkpoint_id: str) -> Checkpoint | None:
|
|
94
|
+
for checkpoint in self.all(session_id):
|
|
95
|
+
if checkpoint.id == checkpoint_id:
|
|
96
|
+
return checkpoint
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
def _write(self, session_id: str, checkpoints: list[Checkpoint]) -> None:
|
|
100
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
path = self.path(session_id)
|
|
102
|
+
path.write_text(
|
|
103
|
+
json.dumps([checkpoint.to_dict() for checkpoint in checkpoints], ensure_ascii=False, indent=2),
|
|
104
|
+
encoding="utf-8",
|
|
105
|
+
)
|
|
106
|
+
path.chmod(0o600)
|
|
107
|
+
"""The checkpoints hold the content of the files of the project."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def snapshot_file(path: Path) -> str | None:
|
|
111
|
+
"""The content of a file before it is changed. `None` when it does not exist."""
|
|
112
|
+
if not path.exists():
|
|
113
|
+
return None
|
|
114
|
+
return path.read_text(encoding="utf-8", errors="replace")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def create_file_checkpoint(
|
|
118
|
+
store: CheckpointStore,
|
|
119
|
+
session_id: str,
|
|
120
|
+
turn: int,
|
|
121
|
+
cwd: Path,
|
|
122
|
+
path: str,
|
|
123
|
+
messages: int = 0,
|
|
124
|
+
) -> Checkpoint | None:
|
|
125
|
+
"""Snapshot a file before a write tool changes it.
|
|
126
|
+
|
|
127
|
+
A file that holds a secret is stored without it, so it cannot be put back
|
|
128
|
+
exactly. The path is remembered, so the user can be told about it.
|
|
129
|
+
"""
|
|
130
|
+
target = Path(path)
|
|
131
|
+
if not target.is_absolute():
|
|
132
|
+
target = Path(cwd) / target
|
|
133
|
+
try:
|
|
134
|
+
name = str(target.relative_to(Path(cwd)))
|
|
135
|
+
except ValueError:
|
|
136
|
+
name = str(target)
|
|
137
|
+
content = snapshot_file(target)
|
|
138
|
+
secret = content is not None and has_secret(content)
|
|
139
|
+
payload = {name: redact(content) if secret else content}
|
|
140
|
+
return store.create(session_id, turn, "file_diff", payload, messages, [name] if secret else [])
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def restore_files(checkpoint: Checkpoint, cwd: Path) -> list[str]:
|
|
144
|
+
"""Put the files back the way they were. Returns the paths that changed.
|
|
145
|
+
|
|
146
|
+
A file whose content was redacted is left alone: writing it back would put
|
|
147
|
+
a placeholder where the secret was.
|
|
148
|
+
"""
|
|
149
|
+
changed = []
|
|
150
|
+
redacted = set(getattr(checkpoint, "redacted", []))
|
|
151
|
+
for name, content in checkpoint.payload.items():
|
|
152
|
+
if name in redacted:
|
|
153
|
+
continue
|
|
154
|
+
path = Path(cwd) / name
|
|
155
|
+
if content is None:
|
|
156
|
+
if path.exists():
|
|
157
|
+
path.unlink()
|
|
158
|
+
changed.append(name)
|
|
159
|
+
continue
|
|
160
|
+
if not path.exists() or path.read_text(encoding="utf-8", errors="replace") != content:
|
|
161
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
162
|
+
path.write_text(content, encoding="utf-8")
|
|
163
|
+
changed.append(name)
|
|
164
|
+
return changed
|