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,56 @@
|
|
|
1
|
+
"""The memory layers. M2 only reads them, writing is M4.
|
|
2
|
+
|
|
3
|
+
Working memory lives in the session metadata, session memory in the summary,
|
|
4
|
+
project memory in `.coderagent/memory/` and user memory in `~/.coderagent/CLAUDE.md`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from coderagent.config.schema import MemoryConfig
|
|
10
|
+
from coderagent.core.instructions import InstructionBlock, load_instructions, once_per_file, read_block
|
|
11
|
+
from coderagent.paths import config_home
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def project_memory_files(cwd: Path, config: MemoryConfig) -> list[Path]:
|
|
15
|
+
directory = Path(cwd) / config.project_path
|
|
16
|
+
if not directory.is_dir():
|
|
17
|
+
return []
|
|
18
|
+
return sorted(path for path in directory.glob("*.md") if path.is_file())
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def load_project_memory(cwd: Path, config: MemoryConfig, max_bytes: int = 0) -> list[InstructionBlock]:
|
|
22
|
+
blocks = []
|
|
23
|
+
for path in project_memory_files(cwd, config):
|
|
24
|
+
block = read_block(path, max_bytes)
|
|
25
|
+
if block:
|
|
26
|
+
blocks.append(block)
|
|
27
|
+
return blocks
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def user_memory_file(config: MemoryConfig, user_home: Path | None = None) -> Path:
|
|
31
|
+
"""The file with the preferences of the user."""
|
|
32
|
+
home = Path(user_home) if user_home else config_home()
|
|
33
|
+
return home / Path(config.user_path).name
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def load_user_memory(
|
|
37
|
+
config: MemoryConfig, user_home: Path | None = None, max_bytes: int = 0
|
|
38
|
+
) -> InstructionBlock | None:
|
|
39
|
+
return read_block(user_memory_file(config, user_home), max_bytes)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def project_text(cwd: Path, user_home: Path | None, config: MemoryConfig, max_bytes: int = 0) -> str:
|
|
43
|
+
"""The instructions and the memory of a directory, as the model sees them.
|
|
44
|
+
|
|
45
|
+
The sub agent gets them too: it works in the same project, and the rules of
|
|
46
|
+
the project are the rules of the work.
|
|
47
|
+
|
|
48
|
+
Every file is read once: the file of the user is an instruction and a memory
|
|
49
|
+
at the same time, and it is shown once.
|
|
50
|
+
"""
|
|
51
|
+
blocks = load_instructions(cwd, user_home, max_bytes)
|
|
52
|
+
blocks += load_project_memory(cwd, config, max_bytes)
|
|
53
|
+
user_memory = load_user_memory(config, user_home, max_bytes)
|
|
54
|
+
if user_memory and user_memory.path not in {block.path for block in blocks}:
|
|
55
|
+
blocks.append(user_memory)
|
|
56
|
+
return "\n\n".join(block.render() for block in once_per_file(blocks))
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""The files a user mentions: `@path` in a prompt and `/mention <path>`.
|
|
2
|
+
|
|
3
|
+
The content of the file goes into the message, so that the model does not have
|
|
4
|
+
to spend a tool call on reading it again. A file that the agent may not see
|
|
5
|
+
does not go into the message either: the message says that it may not be seen.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from coderagent.core.redact import redact
|
|
12
|
+
|
|
13
|
+
MAX_CHARS = 20000
|
|
14
|
+
"""How much of a mentioned file goes into the message."""
|
|
15
|
+
|
|
16
|
+
MENTION = re.compile(r"@([^\s@]+)")
|
|
17
|
+
"""A mention in a prompt: an @ and a path without spaces."""
|
|
18
|
+
|
|
19
|
+
FILE_BLOCK = re.compile(r'<file path="[^"]*">.*?</file>', re.DOTALL)
|
|
20
|
+
"""A block of a file that is already in the message."""
|
|
21
|
+
|
|
22
|
+
TRAILING = ",;:!?)]}\"'"
|
|
23
|
+
"""The punctuation that ends a sentence, not a path."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def expand(text: str, cwd: Path, policy) -> str:
|
|
27
|
+
"""The text with the content of the mentioned files in it.
|
|
28
|
+
|
|
29
|
+
A name that is not a file stays as it is: `@` is used for other things
|
|
30
|
+
too, in an address or in a decorator.
|
|
31
|
+
"""
|
|
32
|
+
parts = FILE_BLOCK.split(text)
|
|
33
|
+
blocks = FILE_BLOCK.findall(text)
|
|
34
|
+
expanded = [MENTION.sub(lambda match: _replacement(match.group(1), cwd, policy), part) for part in parts]
|
|
35
|
+
result = []
|
|
36
|
+
for index, part in enumerate(expanded):
|
|
37
|
+
result.append(part)
|
|
38
|
+
if index < len(blocks):
|
|
39
|
+
result.append(blocks[index])
|
|
40
|
+
return "".join(result)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _replacement(name: str, cwd: Path, policy) -> str:
|
|
44
|
+
"""What an `@name` in a prompt turns into."""
|
|
45
|
+
path_text, tail = _split(name)
|
|
46
|
+
content = _content(path_text, cwd, policy)
|
|
47
|
+
if content is None:
|
|
48
|
+
"""There is no such file: the text stays as it is."""
|
|
49
|
+
return f"@{name}"
|
|
50
|
+
return f"{content}{tail}"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _split(name: str) -> tuple[str, str]:
|
|
54
|
+
"""The path in a mention, and the punctuation that follows it."""
|
|
55
|
+
stripped = name.rstrip(TRAILING)
|
|
56
|
+
return stripped, name[len(stripped) :]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _content(path_text: str, cwd: Path, policy) -> str | None:
|
|
60
|
+
"""The content of the file as a block. None when there is no such file."""
|
|
61
|
+
path = Path(path_text).expanduser()
|
|
62
|
+
if not path.is_absolute():
|
|
63
|
+
path = cwd / path
|
|
64
|
+
if not path.is_file():
|
|
65
|
+
return None
|
|
66
|
+
if policy is not None and policy.check("read", {"path": str(path)}) != "allow":
|
|
67
|
+
"""The agent may not read this file, so the content does not go in."""
|
|
68
|
+
return f'<file path="{path_text}">\nThe agent may not read this file.\n</file>'
|
|
69
|
+
try:
|
|
70
|
+
text = path.read_text(encoding="utf-8")
|
|
71
|
+
except (OSError, UnicodeDecodeError):
|
|
72
|
+
return f'<file path="{path_text}">\nThis file is not text.\n</file>'
|
|
73
|
+
if "\x00" in text:
|
|
74
|
+
"""A file with a null byte in it is not a file of text."""
|
|
75
|
+
return f'<file path="{path_text}">\nThis file is not text.\n</file>'
|
|
76
|
+
text = redact(text)
|
|
77
|
+
"""The content of the file goes into the prompt and into the log of the session,
|
|
78
|
+
so the secrets in it are taken out, as they are in the output of a tool."""
|
|
79
|
+
if len(text) > MAX_CHARS:
|
|
80
|
+
text = text[:MAX_CHARS] + "\n... (the rest of the file is not here)"
|
|
81
|
+
return f'<file path="{path_text}">\n{text}\n</file>'
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""The boundary of the commands, enforced by the operating system.
|
|
2
|
+
|
|
3
|
+
The permission layer asks the user. This one asks nobody: the commands of the
|
|
4
|
+
agent run inside a Seatbelt profile (macOS) or inside a bubblewrap namespace
|
|
5
|
+
(Linux), so a command that goes too far is stopped by the kernel and not by a
|
|
6
|
+
rule in a file.
|
|
7
|
+
|
|
8
|
+
The modes are the ones of Codex:
|
|
9
|
+
|
|
10
|
+
| Mode | What the commands may do |
|
|
11
|
+
|---|---|
|
|
12
|
+
| `full-access` | Everything the user may do. The default. |
|
|
13
|
+
| `workspace-write` | Read the disk, write inside the working directory |
|
|
14
|
+
| `read-only` | Read the disk, write nothing |
|
|
15
|
+
|
|
16
|
+
The commands are wrapped, not the tools: the file tools of the agent write
|
|
17
|
+
through the operating system of the user, and the permission layer is what
|
|
18
|
+
keeps them inside the bounds.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import platform
|
|
22
|
+
import shlex
|
|
23
|
+
import shutil
|
|
24
|
+
import tempfile
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
READ_ONLY = "read-only"
|
|
28
|
+
WORKSPACE_WRITE = "workspace-write"
|
|
29
|
+
FULL_ACCESS = "full-access"
|
|
30
|
+
MODES = (READ_ONLY, WORKSPACE_WRITE, FULL_ACCESS)
|
|
31
|
+
"""The modes from the tightest to the loosest."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class UnsupportedSandbox(RuntimeError):
|
|
35
|
+
"""The mode cannot be enforced on this machine."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def scratch_dir() -> Path:
|
|
39
|
+
"""The directory the commands may always write to, even in the read-only mode.
|
|
40
|
+
|
|
41
|
+
A build needs somewhere to put its files, and a temporary file is not a
|
|
42
|
+
change of the machine.
|
|
43
|
+
"""
|
|
44
|
+
return Path(tempfile.gettempdir()).resolve()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Confinement:
|
|
48
|
+
"""The OS level boundary around the commands of a session."""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
mode: str,
|
|
53
|
+
cwd: Path,
|
|
54
|
+
include_dirs: list[str] | None = None,
|
|
55
|
+
network: str = "allow",
|
|
56
|
+
scratch: Path | None = None,
|
|
57
|
+
) -> None:
|
|
58
|
+
if mode not in MODES:
|
|
59
|
+
raise ValueError(f"unknown sandbox mode '{mode}'. Use one of: {', '.join(MODES)}.")
|
|
60
|
+
self.mode = mode
|
|
61
|
+
self.cwd = Path(cwd).resolve()
|
|
62
|
+
self.include_dirs = [_resolve(directory, self.cwd) for directory in include_dirs or []]
|
|
63
|
+
"""The extra directories, relative to the working directory of the session."""
|
|
64
|
+
self.network = network
|
|
65
|
+
"""Whether the commands may reach the network. `deny` closes it in the sandbox too."""
|
|
66
|
+
self.scratch = Path(scratch).resolve() if scratch else scratch_dir()
|
|
67
|
+
"""The one directory the commands may write to, even in the read-only mode."""
|
|
68
|
+
self.tool = self._tool() if mode != FULL_ACCESS else ""
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def active(self) -> bool:
|
|
72
|
+
"""Whether the commands run inside a sandbox at all."""
|
|
73
|
+
return self.mode != FULL_ACCESS
|
|
74
|
+
|
|
75
|
+
def writable(self) -> list[Path]:
|
|
76
|
+
"""The directories the commands may write to."""
|
|
77
|
+
if not self.active:
|
|
78
|
+
return []
|
|
79
|
+
if self.mode == READ_ONLY:
|
|
80
|
+
return [self.scratch]
|
|
81
|
+
return [self.scratch, self.cwd, *self.include_dirs]
|
|
82
|
+
|
|
83
|
+
def wrap(self, command: str) -> str:
|
|
84
|
+
"""The command, with the sandbox in front of it.
|
|
85
|
+
|
|
86
|
+
The command goes to the sandbox as one argument, so the shell that
|
|
87
|
+
parses it runs inside the sandbox too. A pipeline that was parsed
|
|
88
|
+
outside would run half of it outside.
|
|
89
|
+
"""
|
|
90
|
+
if not self.active:
|
|
91
|
+
return command
|
|
92
|
+
return f"{self._prefix()} /bin/sh -c {shlex.quote(command)}"
|
|
93
|
+
|
|
94
|
+
def _tool(self) -> str:
|
|
95
|
+
"""The program that builds the sandbox."""
|
|
96
|
+
return find_tool(platform.system(), self.mode)
|
|
97
|
+
|
|
98
|
+
def _prefix(self) -> str:
|
|
99
|
+
if platform.system() == "Darwin":
|
|
100
|
+
return " ".join(shlex.quote(part) for part in [self.tool, "-p", self._profile()])
|
|
101
|
+
return " ".join(shlex.quote(part) for part in self._bubblewrap())
|
|
102
|
+
|
|
103
|
+
def _profile(self) -> str:
|
|
104
|
+
"""The Seatbelt profile. The last rule that matches is the one that holds."""
|
|
105
|
+
lines = ["(version 1)", "(allow default)", "(deny file-write*)"]
|
|
106
|
+
lines += [f'(allow file-write* (subpath "{_escape(path)}"))' for path in self.writable()]
|
|
107
|
+
if self.network == "deny":
|
|
108
|
+
lines.append("(deny network*)")
|
|
109
|
+
return "\n".join(lines)
|
|
110
|
+
|
|
111
|
+
def _bubblewrap(self) -> list[str]:
|
|
112
|
+
"""The arguments of bubblewrap. The disk is read only, except for the writable directories."""
|
|
113
|
+
args = [self.tool, "--ro-bind", "/", "/", "--dev-bind", "/dev", "/dev"]
|
|
114
|
+
for path in self.writable():
|
|
115
|
+
args += ["--bind", str(path), str(path)]
|
|
116
|
+
if self.network == "deny":
|
|
117
|
+
args.append("--unshare-net")
|
|
118
|
+
return args
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _escape(path: Path) -> str:
|
|
122
|
+
"""A path as the Seatbelt profile wants it."""
|
|
123
|
+
return path.as_posix().replace('"', '\\"')
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _resolve(directory: str, base: Path) -> Path:
|
|
127
|
+
"""Where a directory is, relative to the working directory of the session."""
|
|
128
|
+
target = Path(directory).expanduser()
|
|
129
|
+
return (target if target.is_absolute() else base / target).resolve()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
SANDBOX_TOOLS = {"Darwin": ("sandbox-exec", "Seatbelt"), "Linux": ("bwrap", "bubblewrap")}
|
|
133
|
+
"""The program that builds the sandbox on a system, and the name of the technology."""
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def find_tool(system: str, mode: str) -> str:
|
|
137
|
+
"""The program that builds the sandbox on this system."""
|
|
138
|
+
if system not in SANDBOX_TOOLS:
|
|
139
|
+
raise UnsupportedSandbox(f"The {mode} mode is not supported on {system}.")
|
|
140
|
+
program, name = SANDBOX_TOOLS[system]
|
|
141
|
+
tool = shutil.which(program)
|
|
142
|
+
if not tool:
|
|
143
|
+
raise UnsupportedSandbox(f"The {mode} mode needs {name} (`{program}`), which this machine does not have.")
|
|
144
|
+
return tool
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
SANDBOX_NOTES = {
|
|
148
|
+
READ_ONLY: (
|
|
149
|
+
"The commands run in a read-only sandbox: they may read the disk, but they may not write "
|
|
150
|
+
"anything outside the scratch directory. The tools that write files are refused as well. "
|
|
151
|
+
"Answer with what you found and describe the change you would make, but do not make it."
|
|
152
|
+
),
|
|
153
|
+
WORKSPACE_WRITE: (
|
|
154
|
+
"The commands run in a sandbox: they may read the disk, but they may only write inside the working directory."
|
|
155
|
+
),
|
|
156
|
+
}
|
|
157
|
+
"""What the model is told when the sandbox takes something away from it."""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def sandbox_block(mode: str) -> str:
|
|
161
|
+
"""The note as the block the model sees, empty when the commands may do everything."""
|
|
162
|
+
note = SANDBOX_NOTES.get(mode, "")
|
|
163
|
+
if not note:
|
|
164
|
+
return ""
|
|
165
|
+
return f'<sandbox mode="{mode}">\n{note}\n</sandbox>'
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def build(
|
|
169
|
+
mode: str,
|
|
170
|
+
cwd: Path,
|
|
171
|
+
include_dirs: list[str] | None = None,
|
|
172
|
+
network: str = "allow",
|
|
173
|
+
scratch: Path | None = None,
|
|
174
|
+
) -> Confinement | None:
|
|
175
|
+
"""The confinement of a sandbox, or nothing when the commands may do everything."""
|
|
176
|
+
if mode == FULL_ACCESS:
|
|
177
|
+
return None
|
|
178
|
+
return Confinement(mode, cwd, include_dirs, network, scratch)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
__all__ = [
|
|
182
|
+
"FULL_ACCESS",
|
|
183
|
+
"MODES",
|
|
184
|
+
"READ_ONLY",
|
|
185
|
+
"WORKSPACE_WRITE",
|
|
186
|
+
"Confinement",
|
|
187
|
+
"UnsupportedSandbox",
|
|
188
|
+
"build",
|
|
189
|
+
"find_tool",
|
|
190
|
+
"sandbox_block",
|
|
191
|
+
]
|
coderagent/core/otel.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""The trace of a session, in the shape an OTel backend understands, and where it goes.
|
|
2
|
+
|
|
3
|
+
The event log stays the source of truth. This module only turns the events into
|
|
4
|
+
spans and hands them to an exporter. A backend that is down is a warning and
|
|
5
|
+
nothing more: the session does not care about the trace.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import hashlib
|
|
9
|
+
import logging
|
|
10
|
+
from typing import Any, Protocol
|
|
11
|
+
|
|
12
|
+
from coderagent.core.events import Event, EventType
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("coderagent.core.otel")
|
|
15
|
+
|
|
16
|
+
SCOPE = "coderagent"
|
|
17
|
+
DEFAULT_ENDPOINT = "http://localhost:4318/v1/traces"
|
|
18
|
+
"""Where a collector listens, when the user does not say."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Exporter(Protocol):
|
|
22
|
+
"""Where the spans of a session go."""
|
|
23
|
+
|
|
24
|
+
def export(self, payload: dict[str, Any]) -> bool:
|
|
25
|
+
"""Send the trace. Returns whether it arrived."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class OtlpExporter:
|
|
29
|
+
"""Sends the trace to an OTLP endpoint over HTTP."""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self, endpoint: str = DEFAULT_ENDPOINT, headers: dict[str, str] | None = None, timeout: float = 5.0
|
|
33
|
+
) -> None:
|
|
34
|
+
self.endpoint = endpoint
|
|
35
|
+
self.headers = headers or {}
|
|
36
|
+
"""The headers the backend wants, like the key it asks for."""
|
|
37
|
+
self.timeout = timeout
|
|
38
|
+
|
|
39
|
+
def export(self, payload: dict[str, Any]) -> bool:
|
|
40
|
+
import requests
|
|
41
|
+
|
|
42
|
+
try:
|
|
43
|
+
response = requests.post(
|
|
44
|
+
self.endpoint,
|
|
45
|
+
json=payload,
|
|
46
|
+
headers={"Content-Type": "application/json", **self.headers},
|
|
47
|
+
timeout=self.timeout,
|
|
48
|
+
)
|
|
49
|
+
except requests.RequestException as error:
|
|
50
|
+
logger.warning("The trace did not reach %s: %s", self.endpoint, error)
|
|
51
|
+
return False
|
|
52
|
+
if response.status_code >= 400:
|
|
53
|
+
logger.warning("%s refused the trace: %s", self.endpoint, response.status_code)
|
|
54
|
+
return False
|
|
55
|
+
return True
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def build_trace(events: list[Event], session=None) -> dict[str, Any]:
|
|
59
|
+
"""The events of a session as OTLP/JSON.
|
|
60
|
+
|
|
61
|
+
One span per turn, one per model call, one per tool call. The spans of a
|
|
62
|
+
turn are children of that turn, and the turn is a child of nothing: the
|
|
63
|
+
trace of a session is the trace of its id.
|
|
64
|
+
"""
|
|
65
|
+
session_id = getattr(session, "id", "") or (events[0].session_id if events else "")
|
|
66
|
+
trace_id = _hex(session_id, 32)
|
|
67
|
+
spans: list[dict[str, Any]] = []
|
|
68
|
+
turn: dict[str, Any] | None = None
|
|
69
|
+
last = 0.0
|
|
70
|
+
"""The time of the event before the one at hand. A model call lasts until its answer."""
|
|
71
|
+
tools: dict[str, dict[str, Any]] = {}
|
|
72
|
+
"""The span of every tool call, by the id of the call."""
|
|
73
|
+
turn_ends: list[tuple[dict[str, Any], float]] = []
|
|
74
|
+
"""The span of every turn, with the time it was last heard from."""
|
|
75
|
+
turn_done = True
|
|
76
|
+
for event in events:
|
|
77
|
+
timestamp = event.timestamp
|
|
78
|
+
if event.type == EventType.USER_MESSAGE:
|
|
79
|
+
if turn is not None and not turn_done:
|
|
80
|
+
turn_ends.append((turn, last))
|
|
81
|
+
turn = _span(trace_id, _hex(f"{session_id}:{timestamp}", 16), "turn", timestamp, timestamp)
|
|
82
|
+
spans.append(turn)
|
|
83
|
+
last = timestamp
|
|
84
|
+
turn_done = False
|
|
85
|
+
continue
|
|
86
|
+
if turn is None:
|
|
87
|
+
"""What happened before the first turn is not part of a turn."""
|
|
88
|
+
continue
|
|
89
|
+
if event.type == EventType.ASSISTANT_MESSAGE:
|
|
90
|
+
message = event.payload.get("message") or {}
|
|
91
|
+
extra = message.get("extra") or {}
|
|
92
|
+
spans.append(
|
|
93
|
+
_span(
|
|
94
|
+
trace_id,
|
|
95
|
+
_hex(f"{session_id}:{timestamp}:model", 16),
|
|
96
|
+
"model",
|
|
97
|
+
last or timestamp,
|
|
98
|
+
timestamp,
|
|
99
|
+
parent=turn["spanId"],
|
|
100
|
+
attributes=[
|
|
101
|
+
_attr("model.name", extra.get("model", "")),
|
|
102
|
+
_attr("model.purpose", extra.get("purpose", "main")),
|
|
103
|
+
_attr("cost", float(extra.get("cost") or event.payload.get("cost") or 0.0)),
|
|
104
|
+
_attr("tokens.in", int(extra.get("tokens_in") or 0)),
|
|
105
|
+
_attr("tokens.out", int(extra.get("tokens_out") or 0)),
|
|
106
|
+
],
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
last = timestamp
|
|
110
|
+
elif event.type == EventType.TOOL_CALL:
|
|
111
|
+
for index, action in enumerate(event.payload.get("actions") or []):
|
|
112
|
+
span = _span(
|
|
113
|
+
trace_id,
|
|
114
|
+
_hex(f"{session_id}:{timestamp}:{action.get('tool_call_id', index)}", 16),
|
|
115
|
+
f"tool.{action.get('tool', '')}",
|
|
116
|
+
timestamp,
|
|
117
|
+
timestamp,
|
|
118
|
+
parent=turn["spanId"],
|
|
119
|
+
attributes=[
|
|
120
|
+
_attr("tool.name", action.get("tool", "")),
|
|
121
|
+
_attr("tool.call_id", action.get("tool_call_id", "")),
|
|
122
|
+
],
|
|
123
|
+
)
|
|
124
|
+
spans.append(span)
|
|
125
|
+
tools[action.get("tool_call_id", "")] = span
|
|
126
|
+
last = timestamp
|
|
127
|
+
elif event.type == EventType.TOOL_RESULT:
|
|
128
|
+
span = tools.get(event.payload.get("tool_call_id", ""))
|
|
129
|
+
if span is not None:
|
|
130
|
+
span["endTimeUnixNano"] = _nanos(timestamp)
|
|
131
|
+
if event.payload.get("is_error"):
|
|
132
|
+
span["status"] = {"code": 2, "message": "the tool failed"}
|
|
133
|
+
last = timestamp
|
|
134
|
+
elif event.type == EventType.TURN_END:
|
|
135
|
+
turn["endTimeUnixNano"] = _nanos(timestamp)
|
|
136
|
+
turn["attributes"] += [
|
|
137
|
+
_attr("turn.cost", float(event.payload.get("cost") or 0.0)),
|
|
138
|
+
_attr("turn.stop_reason", event.payload.get("stop_reason", "")),
|
|
139
|
+
]
|
|
140
|
+
last = timestamp
|
|
141
|
+
turn_ends.append((turn, last))
|
|
142
|
+
turn_done = True
|
|
143
|
+
elif event.type == EventType.ERROR:
|
|
144
|
+
turn["attributes"].append(_attr("error", event.payload.get("error", "")))
|
|
145
|
+
turn["status"] = {"code": 2, "message": str(event.payload.get("error", ""))[:200]}
|
|
146
|
+
last = timestamp
|
|
147
|
+
else:
|
|
148
|
+
turn["endTimeUnixNano"] = _nanos(timestamp)
|
|
149
|
+
last = timestamp
|
|
150
|
+
if turn is not None and not turn_done:
|
|
151
|
+
turn_ends.append((turn, last))
|
|
152
|
+
for span, end in turn_ends:
|
|
153
|
+
if span["endTimeUnixNano"] == span["startTimeUnixNano"]:
|
|
154
|
+
"""A turn that never ended still has to have a length."""
|
|
155
|
+
span["endTimeUnixNano"] = _nanos(end)
|
|
156
|
+
return {
|
|
157
|
+
"resourceSpans": [
|
|
158
|
+
{
|
|
159
|
+
"resource": {
|
|
160
|
+
"attributes": [
|
|
161
|
+
_attr("service.name", SCOPE),
|
|
162
|
+
_attr("session.id", session_id),
|
|
163
|
+
_attr("session.cwd", str(getattr(session, "cwd", ""))),
|
|
164
|
+
_attr("model.name", getattr(session, "model_name", "")),
|
|
165
|
+
]
|
|
166
|
+
},
|
|
167
|
+
"scopeSpans": [{"scope": {"name": SCOPE}, "spans": spans}],
|
|
168
|
+
}
|
|
169
|
+
]
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _span(
|
|
174
|
+
trace_id: str,
|
|
175
|
+
span_id: str,
|
|
176
|
+
name: str,
|
|
177
|
+
start: float,
|
|
178
|
+
end: float,
|
|
179
|
+
parent: str = "",
|
|
180
|
+
attributes: list[dict[str, Any]] | None = None,
|
|
181
|
+
) -> dict[str, Any]:
|
|
182
|
+
span = {
|
|
183
|
+
"traceId": trace_id,
|
|
184
|
+
"spanId": span_id,
|
|
185
|
+
"name": name,
|
|
186
|
+
"kind": 1,
|
|
187
|
+
"startTimeUnixNano": _nanos(start),
|
|
188
|
+
"endTimeUnixNano": _nanos(end),
|
|
189
|
+
"attributes": attributes or [],
|
|
190
|
+
}
|
|
191
|
+
if parent:
|
|
192
|
+
span["parentSpanId"] = parent
|
|
193
|
+
return span
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _attr(key: str, value: Any) -> dict[str, Any]:
|
|
197
|
+
if isinstance(value, bool):
|
|
198
|
+
return {"key": key, "value": {"boolValue": value}}
|
|
199
|
+
if isinstance(value, int):
|
|
200
|
+
return {"key": key, "value": {"intValue": value}}
|
|
201
|
+
if isinstance(value, float):
|
|
202
|
+
return {"key": key, "value": {"doubleValue": value}}
|
|
203
|
+
return {"key": key, "value": {"stringValue": str(value)}}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _hex(seed: str, length: int) -> str:
|
|
207
|
+
return hashlib.sha256(seed.encode("utf-8")).hexdigest()[:length]
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _nanos(timestamp: float) -> str:
|
|
211
|
+
return str(int(timestamp * 1_000_000_000))
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
__all__ = ["DEFAULT_ENDPOINT", "Exporter", "OtlpExporter", "SCOPE", "build_trace"]
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Protocols for the pluggable parts of the coding agent."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterator
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Protocol
|
|
5
|
+
|
|
6
|
+
from coderagent.models.streaming import ModelEvent
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from coderagent.tools.permissions import PermissionPolicy
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ModelBackend(Protocol):
|
|
13
|
+
"""A language model backend."""
|
|
14
|
+
|
|
15
|
+
def query(self, messages: list[dict], tools: list[dict] | None = None, **kwargs) -> dict:
|
|
16
|
+
"""Return a normalized assistant message: content, tool_calls and cost."""
|
|
17
|
+
...
|
|
18
|
+
|
|
19
|
+
def query_stream(self, messages: list[dict], tools: list[dict] | None = None, **kwargs) -> Iterator[ModelEvent]:
|
|
20
|
+
"""Yield the answer as it arrives."""
|
|
21
|
+
...
|
|
22
|
+
|
|
23
|
+
def get_template_vars(self) -> dict[str, Any]: ...
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ToolExecutor(Protocol):
|
|
27
|
+
"""Turns model tool calls into normalized actions and observations."""
|
|
28
|
+
|
|
29
|
+
policy: "PermissionPolicy"
|
|
30
|
+
"""The permission policy of the session. It changes while the session runs."""
|
|
31
|
+
|
|
32
|
+
def plan(self, actions: list[dict]) -> list[dict]:
|
|
33
|
+
"""Parse tool calls into normalized actions (tool, tool_call_id, args, raw)."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
def execute(self, actions: list[dict]) -> list[dict]:
|
|
37
|
+
"""Execute actions and return observation messages, in input order."""
|
|
38
|
+
...
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Secrets do not belong in the log of a session, nor in the context of the model.
|
|
2
|
+
|
|
3
|
+
The output of a tool is written to the event log and sent to the provider. A
|
|
4
|
+
secret that is read from a file or printed by a command ends up in both.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
PLACEHOLDER = "[redacted]"
|
|
10
|
+
|
|
11
|
+
PATTERNS: list[tuple[re.Pattern, str]] = [
|
|
12
|
+
(
|
|
13
|
+
re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----", re.DOTALL),
|
|
14
|
+
"[redacted private key]",
|
|
15
|
+
),
|
|
16
|
+
(re.compile(r"\bsk-[A-Za-z0-9_\-]{16,}"), PLACEHOLDER),
|
|
17
|
+
(re.compile(r"\b(?:ghp|gho|ghs|ghu|ghr)_[A-Za-z0-9]{16,}"), PLACEHOLDER),
|
|
18
|
+
(re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}"), PLACEHOLDER),
|
|
19
|
+
(re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), PLACEHOLDER),
|
|
20
|
+
(re.compile(r"\bxox[baprs]-[A-Za-z0-9\-]{10,}"), PLACEHOLDER),
|
|
21
|
+
(re.compile(r"\bAIza[A-Za-z0-9_\-]{35}\b"), PLACEHOLDER),
|
|
22
|
+
(re.compile(r"\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}"), PLACEHOLDER),
|
|
23
|
+
(re.compile(r"(?i)\b(bearer\s+)[A-Za-z0-9_\-\.=]{8,}"), rf"\1{PLACEHOLDER}"),
|
|
24
|
+
(
|
|
25
|
+
re.compile(
|
|
26
|
+
r"(?i)\b((?:password|passwd|pwd|secret|api[_\-]?key|access[_\-]?token|refresh[_\-]?token"
|
|
27
|
+
r"|auth[_\-]?token|client[_\-]?secret|private[_\-]?key)\s*[:=]\s*[\"']?)([^\s\"',;}]{4,})"
|
|
28
|
+
),
|
|
29
|
+
rf"\1{PLACEHOLDER}",
|
|
30
|
+
),
|
|
31
|
+
]
|
|
32
|
+
"""The secrets that are known by their shape, and the name of the key that holds them."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def redact(text: str) -> str:
|
|
36
|
+
"""The text without the secrets in it."""
|
|
37
|
+
if not text:
|
|
38
|
+
return text
|
|
39
|
+
for pattern, replacement in PATTERNS:
|
|
40
|
+
text = pattern.sub(replacement, text)
|
|
41
|
+
return text
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def has_secret(text: str) -> bool:
|
|
45
|
+
"""True when the text holds something that looks like a secret."""
|
|
46
|
+
return bool(text) and redact(text) != text
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
__all__ = ["PATTERNS", "PLACEHOLDER", "has_secret", "redact"]
|