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,217 @@
|
|
|
1
|
+
"""Plugins: third party extensions of the agent.
|
|
2
|
+
|
|
3
|
+
A plugin is a directory with a `plugin.py` in it:
|
|
4
|
+
|
|
5
|
+
.coderagent/plugins/hello/
|
|
6
|
+
└── plugin.py
|
|
7
|
+
|
|
8
|
+
def register(registry):
|
|
9
|
+
registry.tools.register(HelloTool())
|
|
10
|
+
registry.commands.append(Command(name="hello", description="Say hi", handler=hello))
|
|
11
|
+
|
|
12
|
+
A plugin runs in the process of the agent, without a sandbox, so it is only
|
|
13
|
+
loaded when the user has trusted it. The trust list lives in
|
|
14
|
+
`~/.coderagent/trusted-plugins.json` and is changed with `/plugins trust`.
|
|
15
|
+
|
|
16
|
+
The code of a plugin is not run before that decision: finding the plugins only
|
|
17
|
+
reads their source, and the module is imported when a trusted plugin is
|
|
18
|
+
resolved.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import ast
|
|
22
|
+
import json
|
|
23
|
+
from collections.abc import Callable
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from coderagent.config.schema import HookConfig
|
|
29
|
+
from coderagent.paths import config_home
|
|
30
|
+
from coderagent.tools.registry import ToolRegistry
|
|
31
|
+
from coderagent.ui.commands import Command
|
|
32
|
+
|
|
33
|
+
PLUGINS_DIR = "plugins"
|
|
34
|
+
"""The directory of the plugins. In the project it is under `.coderagent`."""
|
|
35
|
+
PLUGIN_FILE = "plugin.py"
|
|
36
|
+
ENTRY_POINT_GROUP = "coderagent.plugins"
|
|
37
|
+
TRUST_FILE = "trusted-plugins.json"
|
|
38
|
+
TRUSTED = "trusted"
|
|
39
|
+
DENIED = "denied"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class ExtensionRegistry:
|
|
44
|
+
"""What a plugin may add to the agent."""
|
|
45
|
+
|
|
46
|
+
tools: ToolRegistry = field(default_factory=ToolRegistry)
|
|
47
|
+
commands: list[Command] = field(default_factory=list)
|
|
48
|
+
hooks: HookConfig = field(default_factory=HookConfig)
|
|
49
|
+
model_backends: dict[str, Any] = field(default_factory=dict)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Plugin:
|
|
54
|
+
"""A plugin that was found on the disk.
|
|
55
|
+
|
|
56
|
+
The code of the plugin is not loaded until `resolve()` is called: listing the
|
|
57
|
+
plugins must not run the code of a plugin the user has not trusted yet.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
name: str
|
|
61
|
+
resolve: Callable[[], Callable[[ExtensionRegistry], None] | None]
|
|
62
|
+
path: Path | None = None
|
|
63
|
+
source: str = "directory"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def discover(cwd: Path, user_home: Path | None = None) -> list[Plugin]:
|
|
67
|
+
"""The plugins of the project and of the user, plus the installed ones."""
|
|
68
|
+
plugins = []
|
|
69
|
+
for directory in _directories(cwd, user_home):
|
|
70
|
+
for path in sorted(directory.glob(f"*/{PLUGIN_FILE}")):
|
|
71
|
+
plugin = _from_file(path)
|
|
72
|
+
if plugin is not None:
|
|
73
|
+
plugins.append(plugin)
|
|
74
|
+
plugins += _from_entry_points()
|
|
75
|
+
return plugins
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def load(
|
|
79
|
+
cwd: Path, user_home: Path | None = None, registry: ExtensionRegistry | None = None, confirm=None
|
|
80
|
+
) -> tuple[ExtensionRegistry, list[Plugin]]:
|
|
81
|
+
"""Load the trusted plugins.
|
|
82
|
+
|
|
83
|
+
A plugin that the user has not answered for yet is only loaded when the
|
|
84
|
+
confirmation says yes, and the answer is remembered. Without a confirmation
|
|
85
|
+
the untrusted plugins are left alone.
|
|
86
|
+
"""
|
|
87
|
+
registry = registry if registry is not None else ExtensionRegistry()
|
|
88
|
+
loaded = []
|
|
89
|
+
for plugin in discover(cwd, user_home):
|
|
90
|
+
decision = trust_decision(plugin.name, user_home)
|
|
91
|
+
if decision == DENIED:
|
|
92
|
+
continue
|
|
93
|
+
if decision != TRUSTED:
|
|
94
|
+
if confirm is None or not confirm(plugin):
|
|
95
|
+
if confirm is not None:
|
|
96
|
+
remember(plugin.name, DENIED, user_home)
|
|
97
|
+
continue
|
|
98
|
+
remember(plugin.name, TRUSTED, user_home)
|
|
99
|
+
register = plugin.resolve()
|
|
100
|
+
if register is None:
|
|
101
|
+
continue
|
|
102
|
+
register(registry)
|
|
103
|
+
loaded.append(plugin)
|
|
104
|
+
return registry, loaded
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def trust_path(user_home: Path | None = None) -> Path:
|
|
108
|
+
home = Path(user_home) if user_home else config_home()
|
|
109
|
+
return home / TRUST_FILE
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def trust_decisions(user_home: Path | None = None) -> dict[str, str]:
|
|
113
|
+
"""The plugins the user has already answered for."""
|
|
114
|
+
path = trust_path(user_home)
|
|
115
|
+
if not path.exists():
|
|
116
|
+
return {}
|
|
117
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def trust_decision(name: str, user_home: Path | None = None) -> str:
|
|
121
|
+
return trust_decisions(user_home).get(name, "")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def remember(name: str, decision: str, user_home: Path | None = None) -> Path:
|
|
125
|
+
"""Write the answer of the user into the trust list."""
|
|
126
|
+
path = trust_path(user_home)
|
|
127
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
128
|
+
decisions = trust_decisions(user_home)
|
|
129
|
+
decisions[name] = decision
|
|
130
|
+
path.write_text(json.dumps(decisions, indent=2, sort_keys=True), encoding="utf-8")
|
|
131
|
+
return path
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _directories(cwd: Path, user_home: Path | None) -> list[Path]:
|
|
135
|
+
home = Path(user_home) if user_home else config_home()
|
|
136
|
+
directories = [home / PLUGINS_DIR, Path(cwd) / ".coderagent" / PLUGINS_DIR]
|
|
137
|
+
return [directory for directory in directories if directory.is_dir()]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _from_file(path: Path) -> Plugin | None:
|
|
141
|
+
"""Find one `plugin.py`. Returns None when it has nothing to register.
|
|
142
|
+
|
|
143
|
+
The file is only read here: whether it has a `register` is decided by
|
|
144
|
+
looking at the source, the code itself runs when the plugin is resolved.
|
|
145
|
+
"""
|
|
146
|
+
try:
|
|
147
|
+
source = path.read_text(encoding="utf-8")
|
|
148
|
+
except OSError:
|
|
149
|
+
return None
|
|
150
|
+
if not _has_register(source):
|
|
151
|
+
return None
|
|
152
|
+
return Plugin(name=path.parent.name, resolve=lambda: _register_of(path), path=path)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _has_register(source: str) -> bool:
|
|
156
|
+
"""Whether the source has a `register` function or a class with one."""
|
|
157
|
+
try:
|
|
158
|
+
tree = ast.parse(source)
|
|
159
|
+
except SyntaxError:
|
|
160
|
+
return False
|
|
161
|
+
for node in tree.body:
|
|
162
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == "register":
|
|
163
|
+
return True
|
|
164
|
+
if isinstance(node, ast.ClassDef) and any(
|
|
165
|
+
isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)) and item.name == "register" for item in node.body
|
|
166
|
+
):
|
|
167
|
+
return True
|
|
168
|
+
return False
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _register_of(path: Path) -> Callable[[ExtensionRegistry], None] | None:
|
|
172
|
+
"""Run the plugin file and return the function that registers it."""
|
|
173
|
+
import importlib.util
|
|
174
|
+
|
|
175
|
+
spec = importlib.util.spec_from_file_location(f"coderagent_plugin_{path.parent.name}", path)
|
|
176
|
+
if spec is None or spec.loader is None:
|
|
177
|
+
return None
|
|
178
|
+
module = importlib.util.module_from_spec(spec)
|
|
179
|
+
spec.loader.exec_module(module)
|
|
180
|
+
register = getattr(module, "register", None)
|
|
181
|
+
if register is None:
|
|
182
|
+
plugin = getattr(module, "plugin", None)
|
|
183
|
+
register = getattr(plugin, "register", None)
|
|
184
|
+
return register if callable(register) else None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _from_entry_points() -> list[Plugin]:
|
|
188
|
+
from importlib.metadata import entry_points
|
|
189
|
+
|
|
190
|
+
plugins = []
|
|
191
|
+
for entry in entry_points(group=ENTRY_POINT_GROUP):
|
|
192
|
+
plugins.append(
|
|
193
|
+
Plugin(name=entry.name, resolve=lambda entry=entry: _entry_register(entry), source="entry-point")
|
|
194
|
+
)
|
|
195
|
+
return plugins
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _entry_register(entry) -> Callable[[ExtensionRegistry], None] | None:
|
|
199
|
+
"""Load the installed distribution and return the function that registers it."""
|
|
200
|
+
loaded = entry.load()
|
|
201
|
+
register = getattr(loaded, "register", loaded)
|
|
202
|
+
return register if callable(register) else None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
__all__ = [
|
|
206
|
+
"ENTRY_POINT_GROUP",
|
|
207
|
+
"PLUGINS_DIR",
|
|
208
|
+
"PLUGIN_FILE",
|
|
209
|
+
"ExtensionRegistry",
|
|
210
|
+
"Plugin",
|
|
211
|
+
"discover",
|
|
212
|
+
"load",
|
|
213
|
+
"remember",
|
|
214
|
+
"trust_decision",
|
|
215
|
+
"trust_decisions",
|
|
216
|
+
"trust_path",
|
|
217
|
+
]
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
"""Settling the experience of a session in the memory.
|
|
2
|
+
|
|
3
|
+
At the end of a session the model is asked what is worth remembering. Two kinds
|
|
4
|
+
of things come out:
|
|
5
|
+
|
|
6
|
+
- project facts: objective things about this project that are not in the code.
|
|
7
|
+
- user preferences: how the user likes to work.
|
|
8
|
+
|
|
9
|
+
The project facts are written right away. The user preferences are only written
|
|
10
|
+
when the user says so: they end up in the instructions of every session, so a
|
|
11
|
+
wrong one is expensive.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from coderagent.config.schema import MemoryConfig
|
|
21
|
+
from coderagent.paths import config_home
|
|
22
|
+
|
|
23
|
+
MAX_LINES = 200
|
|
24
|
+
"""The project memory does not grow past this. Then it has to be tidied up."""
|
|
25
|
+
|
|
26
|
+
MIN_LENGTH = 40
|
|
27
|
+
"""A fact shorter than this is only compared exactly: short sentences collide by
|
|
28
|
+
accident (`the model is gpt-4` and `the model is gpt-5` are alike, not the same)."""
|
|
29
|
+
|
|
30
|
+
STOP_WORDS = frozenset(
|
|
31
|
+
"""a an the and or but if then than that this these those it its they them their there here is are
|
|
32
|
+
was were be been being of to in on at for with without within from by as not no nor only just also
|
|
33
|
+
more most other some such any all can could may might must shall will would should do does did has
|
|
34
|
+
have had into onto upon about after before over under again further once own same too very""".split()
|
|
35
|
+
)
|
|
36
|
+
"""The words that say nothing about what a fact is about. Two facts that differ
|
|
37
|
+
only in these are the same fact."""
|
|
38
|
+
|
|
39
|
+
PROJECT_FILE = "projects.md"
|
|
40
|
+
PENDING_FILE = "pending-memory.md"
|
|
41
|
+
PENDING_HEADER = "# Preferences waiting for a confirmation"
|
|
42
|
+
USER_HEADER = "## Preferences"
|
|
43
|
+
|
|
44
|
+
REFLECT_PROMPT = """You are looking at a finished session of a coding agent.
|
|
45
|
+
|
|
46
|
+
Decide what is worth remembering for the sessions that come after it:
|
|
47
|
+
|
|
48
|
+
- project_facts: objective facts about this project that are not already in the code
|
|
49
|
+
or in the instructions (the build command, the quirks of the tests, where the
|
|
50
|
+
generated files live, ...).
|
|
51
|
+
- user_preferences: what the user said about how they like to work (the language
|
|
52
|
+
of the comments, the style of the commits, ...).
|
|
53
|
+
|
|
54
|
+
Leave a list empty when there is nothing worth remembering. Never repeat what the
|
|
55
|
+
instructions already say.
|
|
56
|
+
|
|
57
|
+
What is already remembered (do not say it again):
|
|
58
|
+
{known}
|
|
59
|
+
|
|
60
|
+
Answer with JSON only, nothing else:
|
|
61
|
+
{"project_facts": ["..."], "user_preferences": ["..."]}
|
|
62
|
+
|
|
63
|
+
The session:
|
|
64
|
+
{conversation}
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class Reflection:
|
|
70
|
+
"""What the model thinks is worth remembering."""
|
|
71
|
+
|
|
72
|
+
project_facts: list[str] = field(default_factory=list)
|
|
73
|
+
user_preferences: list[str] = field(default_factory=list)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class MemoryWrite:
|
|
78
|
+
"""The outcome of a write to a memory file."""
|
|
79
|
+
|
|
80
|
+
written: list[str] = field(default_factory=list)
|
|
81
|
+
warning: str = ""
|
|
82
|
+
"""Why nothing was written, when nothing was written."""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def reflect_prompt(messages: list[dict], limit: int = 40, known: str = "") -> str:
|
|
86
|
+
"""The prompt that asks the model about the session."""
|
|
87
|
+
return REFLECT_PROMPT.replace("{known}", known).replace("{conversation}", _conversation(messages[-limit:]))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def known_memory(cwd: Path, config: MemoryConfig) -> str:
|
|
91
|
+
"""What is already remembered, so that the model does not say it again."""
|
|
92
|
+
parts = []
|
|
93
|
+
for path in (project_memory_path(cwd, config), pending_path(cwd)):
|
|
94
|
+
if path.exists():
|
|
95
|
+
text = path.read_text(encoding="utf-8").strip()
|
|
96
|
+
if text:
|
|
97
|
+
parts.append(text)
|
|
98
|
+
return "\n\n".join(parts)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _conversation(messages: list[dict]) -> str:
|
|
102
|
+
"""The messages as text the model can read.
|
|
103
|
+
|
|
104
|
+
An answer that only calls a tool says nothing, so the name of the tool is
|
|
105
|
+
what is left of it.
|
|
106
|
+
"""
|
|
107
|
+
lines = []
|
|
108
|
+
for message in messages:
|
|
109
|
+
role = message.get("role", "")
|
|
110
|
+
content = message.get("content")
|
|
111
|
+
if not isinstance(content, str):
|
|
112
|
+
content = ""
|
|
113
|
+
calls = message.get("tool_calls") or []
|
|
114
|
+
if not content.strip() and calls:
|
|
115
|
+
content = ", ".join((call.get("function") or {}).get("name", "") for call in calls)
|
|
116
|
+
if content:
|
|
117
|
+
lines.append(f"{role}: {content}")
|
|
118
|
+
return "\n\n".join(lines)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def parse_reflection(text: str) -> Reflection:
|
|
122
|
+
"""Read the answer of the model. A broken answer gives an empty reflection."""
|
|
123
|
+
payload = _json_of(text)
|
|
124
|
+
if not isinstance(payload, dict):
|
|
125
|
+
return Reflection()
|
|
126
|
+
return Reflection(
|
|
127
|
+
project_facts=_strings(payload.get("project_facts")),
|
|
128
|
+
user_preferences=_strings(payload.get("user_preferences")),
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _json_of(text: str) -> dict | None:
|
|
133
|
+
"""The JSON object in the text, with or without the fences around it."""
|
|
134
|
+
stripped = text.strip()
|
|
135
|
+
if stripped.startswith("```"):
|
|
136
|
+
stripped = re.sub(r"^```[a-zA-Z]*\n?", "", stripped)
|
|
137
|
+
stripped = re.sub(r"```$", "", stripped.strip())
|
|
138
|
+
try:
|
|
139
|
+
payload = json.loads(stripped)
|
|
140
|
+
except json.JSONDecodeError:
|
|
141
|
+
match = re.search(r"\{.*\}", stripped, re.DOTALL)
|
|
142
|
+
if match is None:
|
|
143
|
+
return None
|
|
144
|
+
try:
|
|
145
|
+
payload = json.loads(match.group(0))
|
|
146
|
+
except json.JSONDecodeError:
|
|
147
|
+
return None
|
|
148
|
+
return payload if isinstance(payload, dict) else None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _strings(value) -> list[str]:
|
|
152
|
+
"""A list of non empty strings, whatever the model sent."""
|
|
153
|
+
if isinstance(value, str):
|
|
154
|
+
value = [value]
|
|
155
|
+
if not isinstance(value, list):
|
|
156
|
+
return []
|
|
157
|
+
return [str(item).strip() for item in value if str(item).strip()]
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def project_memory_path(cwd: Path, config: MemoryConfig) -> Path:
|
|
161
|
+
"""The file with the facts about this project."""
|
|
162
|
+
return Path(cwd) / config.project_path / PROJECT_FILE
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def pending_path(cwd: Path) -> Path:
|
|
166
|
+
"""The file with the preferences that wait for a confirmation."""
|
|
167
|
+
return Path(cwd) / ".coderagent" / PENDING_FILE
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def user_memory_path(config: MemoryConfig, user_home: Path | None = None) -> Path:
|
|
171
|
+
"""The file with the preferences of the user."""
|
|
172
|
+
home = Path(user_home) if user_home else config_home()
|
|
173
|
+
return home / Path(config.user_path).name
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def append_facts(path: Path, facts: list[str], header: str) -> MemoryWrite:
|
|
177
|
+
"""Append the facts that are not in the file yet. The rest is left alone."""
|
|
178
|
+
existing = path.read_text(encoding="utf-8").splitlines() if path.exists() else []
|
|
179
|
+
new = []
|
|
180
|
+
for fact in facts:
|
|
181
|
+
fact = fact.strip()
|
|
182
|
+
if fact and _is_new(fact, existing + new):
|
|
183
|
+
new.append(fact)
|
|
184
|
+
if not new:
|
|
185
|
+
return MemoryWrite()
|
|
186
|
+
if len(existing) + len(new) + 1 > MAX_LINES:
|
|
187
|
+
return MemoryWrite(warning=f"{path} would grow past {MAX_LINES} lines; tidy it up first.")
|
|
188
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
189
|
+
lines = existing
|
|
190
|
+
if not lines:
|
|
191
|
+
lines = [header, ""]
|
|
192
|
+
elif lines[-1].strip():
|
|
193
|
+
lines.append("")
|
|
194
|
+
lines += [f"- {fact}" for fact in new]
|
|
195
|
+
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
196
|
+
return MemoryWrite(written=new)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _normalize(text: str) -> str:
|
|
200
|
+
"""The text as it is compared, so that a fact is not written twice."""
|
|
201
|
+
return re.sub(r"\W+", " ", text.lower()).strip()
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _names(text: str) -> set[str]:
|
|
205
|
+
"""The things a fact names: a path, a file, a version, a flag.
|
|
206
|
+
|
|
207
|
+
Two facts that name the same things are about the same thing. Two facts that
|
|
208
|
+
name different things are not, however alike they read.
|
|
209
|
+
"""
|
|
210
|
+
names = set()
|
|
211
|
+
for token in re.sub(r"`", " ", text).split():
|
|
212
|
+
token = token.strip("`.,;:(),。;:()\"'")
|
|
213
|
+
if token and any(char.isdigit() or char in "./_-" for char in token):
|
|
214
|
+
names.add(token)
|
|
215
|
+
return names
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _words(text: str) -> set[str]:
|
|
219
|
+
"""The words of a text that carry something. The rest says nothing."""
|
|
220
|
+
return {word for word in re.findall(r"\w+", text.lower()) if word not in STOP_WORDS and len(word) > 2}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _alike(one: str, other: str) -> bool:
|
|
224
|
+
"""Whether two words are the same word, written differently (`build`, `built`)."""
|
|
225
|
+
if one == other:
|
|
226
|
+
return True
|
|
227
|
+
return len(one) > 3 and len(other) > 3 and len(os.path.commonprefix([one, other])) >= 4
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _covered(words: set[str], other: set[str]) -> bool:
|
|
231
|
+
"""Whether every word of the first set is in the second one."""
|
|
232
|
+
return all(any(_alike(word, one) for one in other) for word in words)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _line_text(line: str) -> str:
|
|
236
|
+
"""The text of a line of the file, without the bullet in front of it."""
|
|
237
|
+
return line[2:].strip() if line.startswith("- ") else line.strip()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _is_said(fact: str, line: str) -> bool:
|
|
241
|
+
"""Whether the line of the file already says what the fact says.
|
|
242
|
+
|
|
243
|
+
Three things have to hold, so that a fact is only dropped when it really is
|
|
244
|
+
a new wording of an old one: it is long enough to be more than a sentence
|
|
245
|
+
about nothing, it names nothing that the line does not name, and it holds
|
|
246
|
+
the same words.
|
|
247
|
+
"""
|
|
248
|
+
if len(_normalize(fact)) < MIN_LENGTH:
|
|
249
|
+
"""Short facts collide by accident: `the model is gpt-4` and `the model is gpt-5`."""
|
|
250
|
+
return False
|
|
251
|
+
text = _line_text(line)
|
|
252
|
+
if not _names(fact) <= _names(text):
|
|
253
|
+
return False
|
|
254
|
+
words, other = _words(fact), _words(text)
|
|
255
|
+
if not words or not other:
|
|
256
|
+
return False
|
|
257
|
+
return _covered(words, other) and _covered(other, words)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _is_new(fact: str, lines: list[str]) -> bool:
|
|
261
|
+
"""Whether the fact says something that the file does not say yet."""
|
|
262
|
+
normalized = _normalize(fact)
|
|
263
|
+
if any(_normalize(_line_text(line)) == normalized for line in lines):
|
|
264
|
+
return False
|
|
265
|
+
return not any(_is_said(fact, line) for line in lines)
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def append_user_preferences(path: Path, preferences: list[str]) -> MemoryWrite:
|
|
269
|
+
"""Add the preferences to the instructions of the user, under their own heading."""
|
|
270
|
+
lines = path.read_text(encoding="utf-8").splitlines() if path.exists() else []
|
|
271
|
+
new = []
|
|
272
|
+
for item in preferences:
|
|
273
|
+
item = item.strip()
|
|
274
|
+
if item and _is_new(item, lines + new):
|
|
275
|
+
new.append(item)
|
|
276
|
+
if not new:
|
|
277
|
+
return MemoryWrite()
|
|
278
|
+
if USER_HEADER not in lines:
|
|
279
|
+
if lines and lines[-1].strip():
|
|
280
|
+
lines.append("")
|
|
281
|
+
lines += [USER_HEADER, ""]
|
|
282
|
+
lines += [f"- {item}" for item in new]
|
|
283
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
284
|
+
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
285
|
+
return MemoryWrite(written=new)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def read_pending(cwd: Path) -> list[str]:
|
|
289
|
+
"""The preferences that wait for a confirmation."""
|
|
290
|
+
path = pending_path(cwd)
|
|
291
|
+
if not path.exists():
|
|
292
|
+
return []
|
|
293
|
+
return [line[2:].strip() for line in path.read_text(encoding="utf-8").splitlines() if line.startswith("- ")]
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def clear_pending(cwd: Path) -> list[str]:
|
|
297
|
+
"""Take the pending preferences out of the way and return them."""
|
|
298
|
+
preferences = read_pending(cwd)
|
|
299
|
+
path = pending_path(cwd)
|
|
300
|
+
if path.exists():
|
|
301
|
+
path.unlink()
|
|
302
|
+
return preferences
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def forget(path: Path, text: str) -> bool:
|
|
306
|
+
"""Remove the line that holds this text. True when something was removed."""
|
|
307
|
+
if not path.exists():
|
|
308
|
+
return False
|
|
309
|
+
lines = path.read_text(encoding="utf-8").splitlines()
|
|
310
|
+
wanted = _normalize(text)
|
|
311
|
+
kept = [line for line in lines if _normalize(line) != wanted and not _contains(line, wanted)]
|
|
312
|
+
if len(kept) == len(lines):
|
|
313
|
+
return False
|
|
314
|
+
path.write_text("\n".join(kept) + "\n", encoding="utf-8")
|
|
315
|
+
return True
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _contains(line: str, wanted: str) -> bool:
|
|
319
|
+
"""True when the line holds the text, with the bullet in front."""
|
|
320
|
+
if not wanted:
|
|
321
|
+
return False
|
|
322
|
+
return wanted in _normalize(line[2:] if line.startswith("- ") else line)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
__all__ = [
|
|
326
|
+
"MAX_LINES",
|
|
327
|
+
"MIN_LENGTH",
|
|
328
|
+
"STOP_WORDS",
|
|
329
|
+
"MemoryWrite",
|
|
330
|
+
"Reflection",
|
|
331
|
+
"append_facts",
|
|
332
|
+
"append_user_preferences",
|
|
333
|
+
"clear_pending",
|
|
334
|
+
"forget",
|
|
335
|
+
"known_memory",
|
|
336
|
+
"parse_reflection",
|
|
337
|
+
"pending_path",
|
|
338
|
+
"project_memory_path",
|
|
339
|
+
"read_pending",
|
|
340
|
+
"reflect_prompt",
|
|
341
|
+
"user_memory_path",
|
|
342
|
+
]
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Model backends and the gateway that fronts them."""
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
from functools import cache
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@cache
|
|
8
|
+
def litellm_module():
|
|
9
|
+
"""litellm, imported on demand.
|
|
10
|
+
|
|
11
|
+
Importing litellm takes about two seconds, and most commands never call a model.
|
|
12
|
+
"""
|
|
13
|
+
import litellm
|
|
14
|
+
|
|
15
|
+
litellm.suppress_debug_info = True
|
|
16
|
+
"""litellm prints banners to stdout, which would break the machine-readable output."""
|
|
17
|
+
return litellm
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def warm_up_litellm() -> None:
|
|
21
|
+
"""Import litellm in the background.
|
|
22
|
+
|
|
23
|
+
A program that waits for the user has time to spare: the import happens while
|
|
24
|
+
the user reads and types, and the first call does not wait for it.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def load() -> None:
|
|
28
|
+
try:
|
|
29
|
+
litellm_module()
|
|
30
|
+
except Exception:
|
|
31
|
+
"""The call that needs litellm reports the failure; here it would only be noise."""
|
|
32
|
+
|
|
33
|
+
threading.Thread(target=load, daemon=True).start()
|