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,472 @@
|
|
|
1
|
+
"""Permission modes, rules and the policy that evaluates them."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Protocol
|
|
8
|
+
|
|
9
|
+
from coderagent.core.os_sandbox import FULL_ACCESS, READ_ONLY
|
|
10
|
+
from coderagent.tools import bash_policy
|
|
11
|
+
|
|
12
|
+
READ_TOOLS = {"read", "glob", "grep", "ls"}
|
|
13
|
+
WRITE_TOOLS = {"write", "edit", "multi_edit", "apply_patch"}
|
|
14
|
+
INFO_TOOLS = {"todo_write", "bash_output", "bash_kill"}
|
|
15
|
+
"""Tools that only touch the agent's own bookkeeping, so they never need approval."""
|
|
16
|
+
PATH_TOOLS = READ_TOOLS | WRITE_TOOLS
|
|
17
|
+
|
|
18
|
+
NETWORK_POLICIES = ("allow", "deny")
|
|
19
|
+
"""What the network of a session may do."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class PermissionMode(str, Enum):
|
|
23
|
+
DEFAULT = "default"
|
|
24
|
+
ACCEPT_EDITS = "acceptEdits"
|
|
25
|
+
PLAN = "plan"
|
|
26
|
+
BYPASS = "bypass"
|
|
27
|
+
READONLY = "readonly"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Rule:
|
|
32
|
+
tool: str = "*"
|
|
33
|
+
pattern: str = "*"
|
|
34
|
+
"""Glob for path tools, regular expression for `bash`, tool name otherwise."""
|
|
35
|
+
decision: str = "ask"
|
|
36
|
+
reason: str = ""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
DECISIONS = ("allow", "ask", "deny")
|
|
40
|
+
"""What a rule may say."""
|
|
41
|
+
|
|
42
|
+
RULE_KEYS = ("tool", "pattern", "decision", "reason")
|
|
43
|
+
"""The keys a rule has."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def check_rule(rule: dict) -> None:
|
|
47
|
+
"""Refuse a rule that says something the policy does not know.
|
|
48
|
+
|
|
49
|
+
A decision that is not one of the three is not a decision: the policy would
|
|
50
|
+
take it for an allow, and a rule that may not deny is worse than no rule.
|
|
51
|
+
"""
|
|
52
|
+
if not isinstance(rule, dict):
|
|
53
|
+
raise ValueError(f"a rule must be a mapping, not {type(rule).__name__}.")
|
|
54
|
+
unknown = set(rule) - set(RULE_KEYS)
|
|
55
|
+
if unknown:
|
|
56
|
+
raise ValueError(
|
|
57
|
+
f"a rule has the unknown keys {', '.join(sorted(unknown))}. A rule has {', '.join(RULE_KEYS)}."
|
|
58
|
+
)
|
|
59
|
+
decision = str(rule.get("decision") or "ask")
|
|
60
|
+
if decision not in DECISIONS:
|
|
61
|
+
raise ValueError(f"a rule has the unknown decision '{decision}'. Use one of: {', '.join(DECISIONS)}.")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class Decision:
|
|
66
|
+
decision: str
|
|
67
|
+
rule: Rule | None = None
|
|
68
|
+
reason: str = ""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ApprovalDecision(str, Enum):
|
|
72
|
+
ALLOW = "allow"
|
|
73
|
+
DENY = "deny"
|
|
74
|
+
ALWAYS = "always"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
MODE_NOTES = {
|
|
78
|
+
PermissionMode.PLAN: (
|
|
79
|
+
"You are in plan mode. You may only look around: `read`, `glob`, `grep` and `ls` work, "
|
|
80
|
+
"but every tool that changes something, `bash` included, is refused. Investigate the task "
|
|
81
|
+
"and answer with the plan you would follow. The user decides whether it is executed."
|
|
82
|
+
),
|
|
83
|
+
PermissionMode.READONLY: (
|
|
84
|
+
"You are in read-only mode. You may only look around: `read`, `glob`, `grep` and `ls` work, "
|
|
85
|
+
"but every tool that changes something, `bash` included, is refused. Answer with what you "
|
|
86
|
+
"found and describe the change you would make, but do not make it."
|
|
87
|
+
),
|
|
88
|
+
}
|
|
89
|
+
"""What the model is told when the mode takes tools away from it."""
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
MODE_DENY_REASONS = {
|
|
93
|
+
PermissionMode.PLAN: "The session is in plan mode: only looking around is allowed, changing something is not.",
|
|
94
|
+
PermissionMode.READONLY: "The session is in read-only mode: nothing may be changed.",
|
|
95
|
+
}
|
|
96
|
+
"""Why the mode itself refuses a call, so that the model knows what to do instead."""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def mode_note(mode: PermissionMode) -> str:
|
|
100
|
+
"""The note for the model, empty when the mode needs no explanation."""
|
|
101
|
+
return MODE_NOTES.get(PermissionMode(mode), "")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def mode_block(mode: PermissionMode) -> str:
|
|
105
|
+
"""The note as the block the model sees, empty when the mode needs no explanation."""
|
|
106
|
+
note = mode_note(mode)
|
|
107
|
+
if not note:
|
|
108
|
+
return ""
|
|
109
|
+
return f'<permission_mode mode="{PermissionMode(mode).value}">\n{note}\n</permission_mode>'
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
NETWORK_NOTES = {
|
|
113
|
+
"deny": (
|
|
114
|
+
"The network is closed. A command that reaches it is refused: no `curl`, no `wget`, no "
|
|
115
|
+
"package install, no `git fetch`. Work with what is on the disk and say what you would "
|
|
116
|
+
"have fetched instead."
|
|
117
|
+
),
|
|
118
|
+
}
|
|
119
|
+
"""What the model is told when the network is closed."""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def network_block(network: str) -> str:
|
|
123
|
+
"""The note as the block the model sees, empty when the network is open."""
|
|
124
|
+
note = NETWORK_NOTES.get(network, "")
|
|
125
|
+
if not note:
|
|
126
|
+
return ""
|
|
127
|
+
return f'<permission_network policy="{network}">\n{note}\n</permission_network>'
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class Approver(Protocol):
|
|
131
|
+
def request(self, tool: str, params: dict, reason: str) -> ApprovalDecision: ...
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class HeadlessApprover:
|
|
135
|
+
"""Without a terminal there is nobody to ask, so approval-required calls are denied."""
|
|
136
|
+
|
|
137
|
+
def __init__(self, allow: bool = False) -> None:
|
|
138
|
+
self.allow = allow
|
|
139
|
+
|
|
140
|
+
def request(self, tool: str, params: dict, reason: str) -> ApprovalDecision:
|
|
141
|
+
return ApprovalDecision.ALLOW if self.allow else ApprovalDecision.DENY
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def glob_to_regex(pattern: str) -> re.Pattern:
|
|
145
|
+
"""Translate a glob into a regex where `*` does not cross `/` but `**` does."""
|
|
146
|
+
parts = ["^"]
|
|
147
|
+
index = 0
|
|
148
|
+
while index < len(pattern):
|
|
149
|
+
if pattern.startswith("**/", index):
|
|
150
|
+
parts.append("(?:.*/)?")
|
|
151
|
+
index += 3
|
|
152
|
+
elif pattern.startswith("**", index):
|
|
153
|
+
parts.append(".*")
|
|
154
|
+
index += 2
|
|
155
|
+
elif pattern[index] == "*":
|
|
156
|
+
parts.append("[^/]*")
|
|
157
|
+
index += 1
|
|
158
|
+
elif pattern[index] == "?":
|
|
159
|
+
parts.append("[^/]")
|
|
160
|
+
index += 1
|
|
161
|
+
else:
|
|
162
|
+
parts.append(re.escape(pattern[index]))
|
|
163
|
+
index += 1
|
|
164
|
+
parts.append("$")
|
|
165
|
+
return re.compile("".join(parts))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class PermissionPolicy:
|
|
169
|
+
"""Decides whether a tool call is allowed, needs approval or is denied."""
|
|
170
|
+
|
|
171
|
+
def __init__(
|
|
172
|
+
self,
|
|
173
|
+
mode: PermissionMode = PermissionMode.DEFAULT,
|
|
174
|
+
rules: list[Rule] | None = None,
|
|
175
|
+
*,
|
|
176
|
+
cwd: Path | None = None,
|
|
177
|
+
include_dirs: list[str] | None = None,
|
|
178
|
+
bounded: bool = True,
|
|
179
|
+
network: str = "allow",
|
|
180
|
+
sandbox_mode: str = FULL_ACCESS,
|
|
181
|
+
deny_paths: list[str] | None = None,
|
|
182
|
+
) -> None:
|
|
183
|
+
self.mode = PermissionMode(mode)
|
|
184
|
+
self.rules = list(rules or [])
|
|
185
|
+
self.cwd = Path(cwd).resolve() if cwd else Path.cwd().resolve()
|
|
186
|
+
self.include_dirs = [_resolve(directory, self.cwd) for directory in include_dirs or []]
|
|
187
|
+
"""A directory that is written down relative to the working directory."""
|
|
188
|
+
self.bounded = bounded
|
|
189
|
+
"""Whether the commands run on this disk. A container has its own boundary."""
|
|
190
|
+
if network not in NETWORK_POLICIES:
|
|
191
|
+
raise ValueError(f"unknown network policy '{network}'. Use one of: {', '.join(NETWORK_POLICIES)}.")
|
|
192
|
+
self.network = network
|
|
193
|
+
"""Whether the commands may reach the network. `deny` refuses them."""
|
|
194
|
+
self.sandbox_mode = sandbox_mode
|
|
195
|
+
"""The mode of the operating system sandbox. `read-only` takes the write tools away."""
|
|
196
|
+
self.deny_paths = list(deny_paths or [])
|
|
197
|
+
"""The paths that are off limits, whatever the mode says."""
|
|
198
|
+
self.restriction: dict[str, str] = {}
|
|
199
|
+
"""The tools a command may use, and the pattern each one is limited to.
|
|
200
|
+
|
|
201
|
+
A custom command may say `allowed-tools: bash(git diff:*)`. Then that command
|
|
202
|
+
may run `git diff` and nothing else. A rule of the user cannot widen this.
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
def check(self, tool: str, params: dict) -> str:
|
|
206
|
+
"""Return `allow`, `ask` or `deny`."""
|
|
207
|
+
return self.evaluate(tool, params).decision
|
|
208
|
+
|
|
209
|
+
def evaluate(self, tool: str, params: dict) -> Decision:
|
|
210
|
+
"""Like `check`, but also reports which rule was hit and why."""
|
|
211
|
+
reason = self._restriction_reason(tool, params)
|
|
212
|
+
if reason:
|
|
213
|
+
"""The command may only use some tools. That holds in every mode."""
|
|
214
|
+
return Decision("deny", None, reason)
|
|
215
|
+
if tool == "bash":
|
|
216
|
+
return self._evaluate_bash(str(params.get("command", "")))
|
|
217
|
+
matched = _strictest_rule([rule for rule in self.rules if self._matches(rule, tool, params)])
|
|
218
|
+
decision = matched.decision if matched else self._default_decision(tool)
|
|
219
|
+
if decision not in DECISIONS:
|
|
220
|
+
"""A decision that is not one of the three is not a decision: ask."""
|
|
221
|
+
decision = "ask"
|
|
222
|
+
if tool in PATH_TOOLS:
|
|
223
|
+
path = str(params.get("path", ""))
|
|
224
|
+
if path and not self.within_bounds(path):
|
|
225
|
+
"""A rule cannot open the disk: the bounds hold in every mode."""
|
|
226
|
+
return Decision("deny", matched, self._outside_reason(path))
|
|
227
|
+
if self.sandbox_mode == READ_ONLY and tool in WRITE_TOOLS:
|
|
228
|
+
"""The sandbox is read only: a rule cannot open it either."""
|
|
229
|
+
return Decision("deny", matched, "the sandbox is read only")
|
|
230
|
+
denied = self.denied_path(path)
|
|
231
|
+
if denied:
|
|
232
|
+
"""The denied paths come after the rules: they win over an allow."""
|
|
233
|
+
return Decision("deny", matched, self._denied_reason(path, denied))
|
|
234
|
+
reason = matched.reason if matched else ""
|
|
235
|
+
if decision == "deny" and not reason:
|
|
236
|
+
"""A refusal without a reason leaves the model guessing."""
|
|
237
|
+
reason = self._default_reason(decision)
|
|
238
|
+
return Decision(decision, matched, reason)
|
|
239
|
+
|
|
240
|
+
def _evaluate_bash(self, command: str) -> Decision:
|
|
241
|
+
"""The decision for a shell command.
|
|
242
|
+
|
|
243
|
+
Every part of the command is judged on its own and the strictest part
|
|
244
|
+
wins: an allowed `pytest` does not carry a `rm` along with it. A path
|
|
245
|
+
that leaves the working directory is refused in every mode.
|
|
246
|
+
"""
|
|
247
|
+
outside = bash_policy.outside_paths(command, self.cwd, self.include_dirs) if self.bounded else []
|
|
248
|
+
if outside:
|
|
249
|
+
"""The bounds of the disk hold in every mode, like they do for the file tools."""
|
|
250
|
+
return Decision("deny", None, self._outside_reason(outside[0]))
|
|
251
|
+
for named in bash_policy.named_paths(command, self.cwd):
|
|
252
|
+
denied = self.denied_path(named)
|
|
253
|
+
if denied:
|
|
254
|
+
"""A denied path is off limits for the command too, not only for the file tools."""
|
|
255
|
+
return Decision("deny", None, self._denied_reason(named, denied))
|
|
256
|
+
if self.network == "deny":
|
|
257
|
+
"""The network is closed: the commands that reach it are refused."""
|
|
258
|
+
for segment in bash_policy.segments(command):
|
|
259
|
+
reason = bash_policy.needs_network(segment)
|
|
260
|
+
if reason:
|
|
261
|
+
return Decision("deny", None, f"the network is closed: {reason}")
|
|
262
|
+
if self.mode == PermissionMode.BYPASS:
|
|
263
|
+
return Decision("allow", None, "")
|
|
264
|
+
if self.mode in (PermissionMode.PLAN, PermissionMode.READONLY):
|
|
265
|
+
return Decision("deny", None, MODE_DENY_REASONS.get(self.mode, ""))
|
|
266
|
+
decision = "allow"
|
|
267
|
+
rules: list[Rule] = []
|
|
268
|
+
why = ""
|
|
269
|
+
for segment in bash_policy.segments(command):
|
|
270
|
+
rule = self._bash_rule(segment)
|
|
271
|
+
if rule is not None:
|
|
272
|
+
rules.append(rule)
|
|
273
|
+
decision = _strictest(decision, rule.decision)
|
|
274
|
+
continue
|
|
275
|
+
kind, reason = bash_policy.classify_segment(segment)
|
|
276
|
+
if kind in ("dangerous", "unknown"):
|
|
277
|
+
decision = _strictest(decision, "ask")
|
|
278
|
+
why = why or reason
|
|
279
|
+
matched = _strictest_rule(rules)
|
|
280
|
+
"""The reason is the one of the rule that decided, or the one of the command."""
|
|
281
|
+
reason = matched.reason if matched and matched.decision == decision else why
|
|
282
|
+
if decision == "deny" and not reason:
|
|
283
|
+
"""A refusal without a reason leaves the model guessing."""
|
|
284
|
+
reason = self._default_reason(decision)
|
|
285
|
+
return Decision(decision, matched, reason)
|
|
286
|
+
|
|
287
|
+
def _restriction_reason(self, tool: str, params: dict) -> str:
|
|
288
|
+
"""Why this call is not one of the calls the command may make."""
|
|
289
|
+
if not self.restriction:
|
|
290
|
+
return ""
|
|
291
|
+
if tool not in self.restriction:
|
|
292
|
+
return f"the command may only use {', '.join(sorted(self.restriction))}"
|
|
293
|
+
pattern = self.restriction[tool]
|
|
294
|
+
if pattern == "*":
|
|
295
|
+
return ""
|
|
296
|
+
if tool == "bash":
|
|
297
|
+
for segment in bash_policy.segments(str(params.get("command", ""))):
|
|
298
|
+
if not _matches_bash(pattern, segment):
|
|
299
|
+
return f"the command may only run '{pattern}'"
|
|
300
|
+
return ""
|
|
301
|
+
if tool in PATH_TOOLS:
|
|
302
|
+
path = str(params.get("path", ""))
|
|
303
|
+
if not path:
|
|
304
|
+
return ""
|
|
305
|
+
if glob_to_regex(pattern).match(self._relative(path)):
|
|
306
|
+
return ""
|
|
307
|
+
return f"the command may only touch '{pattern}'"
|
|
308
|
+
return "" if pattern in ("*", tool) else f"the command may only use '{pattern}'"
|
|
309
|
+
|
|
310
|
+
def _bash_rule(self, segment: str) -> Rule | None:
|
|
311
|
+
"""The rule that wins for a part of the command."""
|
|
312
|
+
return _strictest_rule(
|
|
313
|
+
[rule for rule in self.rules if rule.tool in ("*", "bash") and _matches_bash(rule.pattern, segment)]
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
def _default_decision(self, tool: str) -> str:
|
|
317
|
+
if self.mode == PermissionMode.BYPASS:
|
|
318
|
+
return "allow"
|
|
319
|
+
if tool in READ_TOOLS | INFO_TOOLS:
|
|
320
|
+
return "allow"
|
|
321
|
+
if self.mode in (PermissionMode.PLAN, PermissionMode.READONLY):
|
|
322
|
+
return "deny"
|
|
323
|
+
if self.mode == PermissionMode.ACCEPT_EDITS:
|
|
324
|
+
return "allow" if tool in WRITE_TOOLS else "ask"
|
|
325
|
+
return "ask"
|
|
326
|
+
|
|
327
|
+
def _default_reason(self, decision: str) -> str:
|
|
328
|
+
"""Why the call is refused when no rule had a say.
|
|
329
|
+
|
|
330
|
+
A refusal without a reason leaves the model guessing, and it guesses
|
|
331
|
+
by trying the same call again.
|
|
332
|
+
"""
|
|
333
|
+
if decision != "deny":
|
|
334
|
+
return ""
|
|
335
|
+
return MODE_DENY_REASONS.get(self.mode, "") or "the rules of the session deny it."
|
|
336
|
+
|
|
337
|
+
def _matches(self, rule: Rule, tool: str, params: dict) -> bool:
|
|
338
|
+
if rule.tool not in ("*", tool):
|
|
339
|
+
return False
|
|
340
|
+
if tool in PATH_TOOLS:
|
|
341
|
+
path = str(params.get("path", ""))
|
|
342
|
+
if not path:
|
|
343
|
+
return rule.pattern == "*"
|
|
344
|
+
return bool(glob_to_regex(rule.pattern).match(self._relative(path)))
|
|
345
|
+
return rule.pattern in ("*", tool)
|
|
346
|
+
|
|
347
|
+
def _relative(self, path: str) -> str:
|
|
348
|
+
resolved = _resolve(path, self.cwd)
|
|
349
|
+
if resolved.is_relative_to(self.cwd):
|
|
350
|
+
return resolved.relative_to(self.cwd).as_posix()
|
|
351
|
+
return resolved.as_posix()
|
|
352
|
+
|
|
353
|
+
def roots(self) -> list[Path]:
|
|
354
|
+
"""The directories that are open to the agent.
|
|
355
|
+
|
|
356
|
+
The user opens the directories of the agent to it: the interfaces list those
|
|
357
|
+
and nothing else. Without them the working directory is the one.
|
|
358
|
+
"""
|
|
359
|
+
return list(self.include_dirs) or [self.cwd]
|
|
360
|
+
|
|
361
|
+
def within_bounds(self, path: str) -> bool:
|
|
362
|
+
"""Whether a path is inside the working directory or one of the extra directories.
|
|
363
|
+
|
|
364
|
+
The rules of the user cannot widen this: an `allow` rule for a path outside
|
|
365
|
+
the bounds is still a path the agent must not touch.
|
|
366
|
+
"""
|
|
367
|
+
resolved = _resolve(path, self.cwd)
|
|
368
|
+
if resolved.is_relative_to(self.cwd):
|
|
369
|
+
return True
|
|
370
|
+
return any(resolved.is_relative_to(directory) for directory in self.include_dirs)
|
|
371
|
+
|
|
372
|
+
def _outside_reason(self, path: str) -> str:
|
|
373
|
+
"""Why the path is refused, and where it would be allowed."""
|
|
374
|
+
reason = f"'{path}' is outside the working directory {self.cwd}"
|
|
375
|
+
if self.include_dirs:
|
|
376
|
+
directories = ", ".join(str(directory) for directory in self.include_dirs)
|
|
377
|
+
return f"{reason}. The directories that are open: {directories}"
|
|
378
|
+
return reason
|
|
379
|
+
|
|
380
|
+
def denied_path(self, path: str) -> str:
|
|
381
|
+
"""The pattern of a denied path that this path matches, empty when none does.
|
|
382
|
+
|
|
383
|
+
A path matches when the pattern matches it relative to the working
|
|
384
|
+
directory, when it matches the whole of it, or when it matches the name
|
|
385
|
+
of the file: `*.env` is the file of the working directory as well as
|
|
386
|
+
the one of any directory below it. A pattern that ends in `/**` denies
|
|
387
|
+
the directory as well, so that a search below it is refused too.
|
|
388
|
+
"""
|
|
389
|
+
if not path or not self.deny_paths:
|
|
390
|
+
return ""
|
|
391
|
+
relative = self._relative(path)
|
|
392
|
+
name = Path(path).name
|
|
393
|
+
for pattern in self.deny_paths:
|
|
394
|
+
regex = glob_to_regex(pattern)
|
|
395
|
+
if regex.match(relative) or regex.match(name):
|
|
396
|
+
return pattern
|
|
397
|
+
directory = pattern[:-3] if pattern.endswith("/**") and "*" not in pattern[:-3] else ""
|
|
398
|
+
if directory and (relative == directory or relative.startswith(f"{directory}/")):
|
|
399
|
+
return pattern
|
|
400
|
+
return ""
|
|
401
|
+
|
|
402
|
+
def _denied_reason(self, path: str, pattern: str) -> str:
|
|
403
|
+
"""Why the path is off limits."""
|
|
404
|
+
return f"'{path}' is denied by the configuration ('{pattern}')"
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def pattern_for(tool: str, params: dict[str, Any]) -> str:
|
|
408
|
+
"""The rule pattern that would allow exactly this call."""
|
|
409
|
+
if tool in PATH_TOOLS:
|
|
410
|
+
return str(params.get("path", "*"))
|
|
411
|
+
if tool == "bash":
|
|
412
|
+
"""A rule is matched against a part of the command, so the rule names the first one."""
|
|
413
|
+
parts = bash_policy.segments(str(params.get("command", "")))
|
|
414
|
+
return re.escape(parts[0]) if parts else "*"
|
|
415
|
+
return tool
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _strictest_rule(rules: list[Rule]) -> Rule | None:
|
|
419
|
+
"""The rule that wins among the ones that match.
|
|
420
|
+
|
|
421
|
+
A deny is not undone by a later rule: it holds in every mode, so a rule of
|
|
422
|
+
the project cannot be opened by a rule of the user. Among the other
|
|
423
|
+
decisions the last rule wins, so a rule of the user overrides a rule of the
|
|
424
|
+
project. A decision that is not one of the three holds as well: a rule that
|
|
425
|
+
was written wrong is not undone by a later rule.
|
|
426
|
+
"""
|
|
427
|
+
matched: Rule | None = None
|
|
428
|
+
for rule in rules:
|
|
429
|
+
if _holds(rule) or matched is None or not _holds(matched):
|
|
430
|
+
matched = rule
|
|
431
|
+
return matched
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _holds(rule: Rule) -> bool:
|
|
435
|
+
"""Whether the rule may not be undone by a later one."""
|
|
436
|
+
return rule.decision == "deny" or rule.decision not in DECISIONS
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _matches_bash(pattern: str, segment: str) -> bool:
|
|
440
|
+
"""Whether the pattern of a rule is the beginning of a part of the command.
|
|
441
|
+
|
|
442
|
+
A rule is about a command, not about a word somewhere in a line: `git push`
|
|
443
|
+
does not match `echo "git push"`.
|
|
444
|
+
"""
|
|
445
|
+
if pattern == "*":
|
|
446
|
+
return True
|
|
447
|
+
try:
|
|
448
|
+
return bool(re.match(pattern, segment))
|
|
449
|
+
except re.error:
|
|
450
|
+
return False
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _resolve(path: str, base: Path) -> Path:
|
|
454
|
+
"""Where a path is, relative to the working directory of the session.
|
|
455
|
+
|
|
456
|
+
A path that is written down relative is relative to the working directory
|
|
457
|
+
of the session, not to the directory the process happens to stand in.
|
|
458
|
+
"""
|
|
459
|
+
target = Path(path).expanduser()
|
|
460
|
+
return (target if target.is_absolute() else base / target).resolve()
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _strictest(first: str, second: str) -> str:
|
|
464
|
+
"""The stricter of two decisions.
|
|
465
|
+
|
|
466
|
+
A decision that is not one of the three is not a decision: it is an ask,
|
|
467
|
+
so that a rule which was written wrong never lets a call through.
|
|
468
|
+
"""
|
|
469
|
+
order = {"allow": 0, "ask": 1, "deny": 2}
|
|
470
|
+
if order.get(first, 1) >= order.get(second, 1):
|
|
471
|
+
return first if first in order else "ask"
|
|
472
|
+
return second if second in order else "ask"
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Tool registry: registration, schema generation and budget-aware trimming."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
|
|
6
|
+
from coderagent.tools.base import Tool
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger("coderagent.tools")
|
|
9
|
+
|
|
10
|
+
# Trim order: the first tool in this list is dropped first.
|
|
11
|
+
TRIM_ORDER = [
|
|
12
|
+
"web_search",
|
|
13
|
+
"web_fetch",
|
|
14
|
+
"todo_write",
|
|
15
|
+
"bash_output",
|
|
16
|
+
"bash_kill",
|
|
17
|
+
"multi_edit",
|
|
18
|
+
"apply_patch",
|
|
19
|
+
"write",
|
|
20
|
+
"edit",
|
|
21
|
+
"ls",
|
|
22
|
+
"glob",
|
|
23
|
+
"grep",
|
|
24
|
+
"read",
|
|
25
|
+
"bash",
|
|
26
|
+
]
|
|
27
|
+
NEVER_TRIM = {"bash", "read"}
|
|
28
|
+
CHARS_PER_TOKEN = 3.5
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ToolRegistry:
|
|
32
|
+
def __init__(self, tools: list[Tool] | None = None) -> None:
|
|
33
|
+
self._tools: dict[str, Tool] = {}
|
|
34
|
+
for tool in tools or []:
|
|
35
|
+
self.register(tool)
|
|
36
|
+
|
|
37
|
+
def register(self, tool: Tool) -> None:
|
|
38
|
+
if tool.name in self._tools:
|
|
39
|
+
logger.warning("Tool '%s' is already registered, overwriting it", tool.name)
|
|
40
|
+
self._tools[tool.name] = tool
|
|
41
|
+
|
|
42
|
+
def get(self, name: str) -> Tool | None:
|
|
43
|
+
return self._tools.get(name)
|
|
44
|
+
|
|
45
|
+
def names(self) -> list[str]:
|
|
46
|
+
return list(self._tools)
|
|
47
|
+
|
|
48
|
+
def all(self) -> list[Tool]:
|
|
49
|
+
return list(self._tools.values())
|
|
50
|
+
|
|
51
|
+
def schemas(self, budget_tokens: int | None = None) -> list[dict]:
|
|
52
|
+
"""OpenAI-compatible tool schemas, trimmed to fit the token budget."""
|
|
53
|
+
schemas = [self._schema(tool) for tool in self._tools.values()]
|
|
54
|
+
if budget_tokens is None:
|
|
55
|
+
return schemas
|
|
56
|
+
for name in TRIM_ORDER:
|
|
57
|
+
if estimate_tokens(schemas) <= budget_tokens:
|
|
58
|
+
break
|
|
59
|
+
if name in NEVER_TRIM:
|
|
60
|
+
continue
|
|
61
|
+
schemas = [schema for schema in schemas if schema["function"]["name"] != name]
|
|
62
|
+
while estimate_tokens(schemas) > budget_tokens:
|
|
63
|
+
"""What is left does not fit either: the biggest schema goes first."""
|
|
64
|
+
droppable = [schema for schema in schemas if schema["function"]["name"] not in NEVER_TRIM]
|
|
65
|
+
if not droppable:
|
|
66
|
+
break
|
|
67
|
+
schemas.remove(max(droppable, key=lambda schema: len(json.dumps(schema))))
|
|
68
|
+
return schemas
|
|
69
|
+
|
|
70
|
+
def _schema(self, tool: Tool) -> dict:
|
|
71
|
+
return {
|
|
72
|
+
"type": "function",
|
|
73
|
+
"function": {
|
|
74
|
+
"name": tool.name,
|
|
75
|
+
"description": tool.description,
|
|
76
|
+
"parameters": tool.parameters,
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def estimate_tokens(schemas: list[dict]) -> int:
|
|
82
|
+
"""Rough token estimate for a set of tool schemas. M2 replaces this with a real tokenizer."""
|
|
83
|
+
return int(len(json.dumps(schemas)) / CHARS_PER_TOKEN)
|