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,404 @@
|
|
|
1
|
+
"""Where a skill comes from: a GitHub repository, a git URL, a registry or one file.
|
|
2
|
+
|
|
3
|
+
The user writes a source and the agent gets a directory with a `SKILL.md` in
|
|
4
|
+
it. Five kinds of source do that:
|
|
5
|
+
|
|
6
|
+
| Kind | What the user writes |
|
|
7
|
+
|---|---|
|
|
8
|
+
| `github` | `owner/repo`, `owner/repo@ref`, `owner/repo/skills/pdf-report@v1` |
|
|
9
|
+
| `gitee` | `gitee:owner/repo`, `gitee:owner/repo/skills/pdf-report` |
|
|
10
|
+
| `git` | `https://host/org/repo.git`, `git@host:org/repo.git` |
|
|
11
|
+
| `registry` | the address of a `index.json` that lists skills |
|
|
12
|
+
| `direct` | the address of one `SKILL.md` |
|
|
13
|
+
|
|
14
|
+
Nothing here is fetched before the address has been checked: only `https` may
|
|
15
|
+
be fetched, and a host that points inside the network is refused.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import ipaddress
|
|
19
|
+
import json
|
|
20
|
+
import shutil
|
|
21
|
+
import socket
|
|
22
|
+
import subprocess
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from urllib.parse import urljoin, urlparse
|
|
26
|
+
|
|
27
|
+
import requests
|
|
28
|
+
|
|
29
|
+
from coderagent.skills.errors import SkillError
|
|
30
|
+
from coderagent.skills.sandbox import CHUNK, Policy, check_path, unpack_tar
|
|
31
|
+
|
|
32
|
+
REDIRECTS = (301, 302, 303, 307, 308)
|
|
33
|
+
"""The answers of a server that says the file is somewhere else."""
|
|
34
|
+
|
|
35
|
+
HOPS = 3
|
|
36
|
+
"""How many times a download may be sent to another address."""
|
|
37
|
+
|
|
38
|
+
CLONE_TIMEOUT = 120
|
|
39
|
+
"""The seconds a clone may take. A repository is bigger than a file."""
|
|
40
|
+
|
|
41
|
+
GITEE = "https://gitee.com"
|
|
42
|
+
"""Where the repositories of Gitee are fetched from."""
|
|
43
|
+
|
|
44
|
+
GITHUB = "https://github.com"
|
|
45
|
+
"""Where the repositories of GitHub are cloned from."""
|
|
46
|
+
|
|
47
|
+
GITHUB_API = "https://api.github.com"
|
|
48
|
+
"""Where the repositories of GitHub are fetched from."""
|
|
49
|
+
|
|
50
|
+
PRIVATE = (
|
|
51
|
+
ipaddress.ip_network("127.0.0.0/8"),
|
|
52
|
+
ipaddress.ip_network("10.0.0.0/8"),
|
|
53
|
+
ipaddress.ip_network("172.16.0.0/12"),
|
|
54
|
+
ipaddress.ip_network("192.168.0.0/16"),
|
|
55
|
+
ipaddress.ip_network("169.254.0.0/16"),
|
|
56
|
+
ipaddress.ip_network("::1/128"),
|
|
57
|
+
ipaddress.ip_network("fc00::/7"),
|
|
58
|
+
ipaddress.ip_network("fe80::/10"),
|
|
59
|
+
)
|
|
60
|
+
"""The addresses that are not out in the world. A download does not go there."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class Source:
|
|
65
|
+
"""Where a skill comes from."""
|
|
66
|
+
|
|
67
|
+
kind: str
|
|
68
|
+
"""One of `github`, `gitee`, `git`, `registry` or `direct`."""
|
|
69
|
+
url: str = ""
|
|
70
|
+
"""The address to fetch. Empty for a GitHub repository, which is built from `repo`."""
|
|
71
|
+
repo: str = ""
|
|
72
|
+
"""The repository of GitHub or of Gitee: `owner/name`."""
|
|
73
|
+
ref: str = ""
|
|
74
|
+
"""The tag, the branch or the commit of the repository."""
|
|
75
|
+
path: str = ""
|
|
76
|
+
"""The directory of the skill inside the repository."""
|
|
77
|
+
name: str = ""
|
|
78
|
+
"""The name of the skill, when the source names one."""
|
|
79
|
+
|
|
80
|
+
def as_dict(self) -> dict:
|
|
81
|
+
"""The source as it is written into the lock file."""
|
|
82
|
+
return {"kind": self.kind, "url": self.url, "repo": self.repo, "ref": self.ref, "path": self.path}
|
|
83
|
+
|
|
84
|
+
def describe(self) -> str:
|
|
85
|
+
"""The source as the user would write it."""
|
|
86
|
+
if self.kind in ("github", "gitee"):
|
|
87
|
+
text = "/".join(part for part in (self.repo, self.path) if part)
|
|
88
|
+
return f"{text}@{self.ref}" if self.ref else text
|
|
89
|
+
return self.url
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class Entry:
|
|
94
|
+
"""One skill of a registry."""
|
|
95
|
+
|
|
96
|
+
name: str
|
|
97
|
+
description: str
|
|
98
|
+
source: Source
|
|
99
|
+
sha256: str = ""
|
|
100
|
+
"""The digest of the content, when the registry pins it."""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def parse_source(text: str) -> Source:
|
|
104
|
+
"""The source a user wrote. Raises when the text is not one."""
|
|
105
|
+
text = text.strip()
|
|
106
|
+
if not text:
|
|
107
|
+
raise SkillError("there is no source")
|
|
108
|
+
for prefix, kind in (
|
|
109
|
+
("github:", "github"),
|
|
110
|
+
("gitee:", "gitee"),
|
|
111
|
+
("git:", "git"),
|
|
112
|
+
("registry:", "registry"),
|
|
113
|
+
("direct:", "direct"),
|
|
114
|
+
):
|
|
115
|
+
if text.lower().startswith(prefix):
|
|
116
|
+
return _parse(kind, text[len(prefix) :].strip())
|
|
117
|
+
if text.startswith("git@"):
|
|
118
|
+
return Source(kind="git", url=text)
|
|
119
|
+
if text.startswith(("http://", "https://")):
|
|
120
|
+
return _parse_url(text)
|
|
121
|
+
if "/" in text and " " not in text:
|
|
122
|
+
return _parse_github(text)
|
|
123
|
+
raise SkillError(f"'{text}' is not a source of a skill")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def source_of(data: object) -> Source:
|
|
127
|
+
"""The source of a registry entry or of the lock file."""
|
|
128
|
+
if not isinstance(data, dict):
|
|
129
|
+
raise SkillError("a source must be a mapping")
|
|
130
|
+
kind = str(data.get("kind") or "")
|
|
131
|
+
if not kind and data.get("repo"):
|
|
132
|
+
kind = "github"
|
|
133
|
+
if kind == "github":
|
|
134
|
+
repo = str(data.get("repo") or "")
|
|
135
|
+
if "/" not in repo:
|
|
136
|
+
raise SkillError("a github source needs a repository")
|
|
137
|
+
return Source(kind="github", repo=repo, ref=str(data.get("ref") or ""), path=str(data.get("path") or ""))
|
|
138
|
+
if kind == "gitee":
|
|
139
|
+
repo = str(data.get("repo") or "")
|
|
140
|
+
if "/" not in repo:
|
|
141
|
+
raise SkillError("a gitee source needs a repository")
|
|
142
|
+
return Source(kind="gitee", repo=repo, ref=str(data.get("ref") or ""), path=str(data.get("path") or ""))
|
|
143
|
+
if kind in ("git", "registry", "direct"):
|
|
144
|
+
url = str(data.get("url") or "")
|
|
145
|
+
if not url:
|
|
146
|
+
raise SkillError(f"a {kind} source needs a url")
|
|
147
|
+
return Source(kind=kind, url=url)
|
|
148
|
+
raise SkillError(f"'{kind}' is not a kind of source")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def fetch(source: Source, workdir: Path, policy: Policy, token: str = "") -> Path:
|
|
152
|
+
"""The skill of a source, downloaded into the work directory.
|
|
153
|
+
|
|
154
|
+
The answer is the directory of the skill, or the file of a `SKILL.md` that
|
|
155
|
+
stands alone.
|
|
156
|
+
"""
|
|
157
|
+
workdir.mkdir(parents=True, exist_ok=True)
|
|
158
|
+
if source.kind == "github":
|
|
159
|
+
return _fetch_github(source, workdir, policy, token)
|
|
160
|
+
if source.kind == "gitee":
|
|
161
|
+
return _fetch_gitee(source, workdir, policy)
|
|
162
|
+
if source.kind == "git":
|
|
163
|
+
return _fetch_git(source, workdir, policy)
|
|
164
|
+
if source.kind == "direct":
|
|
165
|
+
return _fetch_direct(source, workdir, policy)
|
|
166
|
+
raise SkillError(f"a {source.kind} is not a skill that can be installed")
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def fetch_registry(url: str, policy: Policy) -> list[Entry]:
|
|
170
|
+
"""The skills a registry lists. A bad entry is left out, not the whole list."""
|
|
171
|
+
try:
|
|
172
|
+
data = json.loads(download(url, policy).decode("utf-8"))
|
|
173
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
174
|
+
raise SkillError(f"the registry cannot be read: {error}") from None
|
|
175
|
+
items = data.get("skills") if isinstance(data, dict) else None
|
|
176
|
+
if not isinstance(items, list):
|
|
177
|
+
raise SkillError("the registry does not list any skills")
|
|
178
|
+
entries = []
|
|
179
|
+
for item in items:
|
|
180
|
+
entry = _entry(item)
|
|
181
|
+
if entry is not None:
|
|
182
|
+
entries.append(entry)
|
|
183
|
+
return entries
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def download(url: str, policy: Policy, headers: dict[str, str] | None = None) -> bytes:
|
|
187
|
+
"""The bytes of an address. Refuses what is too big or points inward."""
|
|
188
|
+
current = url
|
|
189
|
+
for _ in range(HOPS + 1):
|
|
190
|
+
check_url(current, policy)
|
|
191
|
+
try:
|
|
192
|
+
response = requests.get(current, stream=True, timeout=policy.timeout, headers=headers or {})
|
|
193
|
+
except requests.RequestException as error:
|
|
194
|
+
raise SkillError(f"the download failed: {error}") from None
|
|
195
|
+
with response:
|
|
196
|
+
if response.status_code in REDIRECTS:
|
|
197
|
+
location = response.headers.get("Location", "")
|
|
198
|
+
if not location:
|
|
199
|
+
raise SkillError("the server sent a redirect without a place to go")
|
|
200
|
+
current = urljoin(current, location)
|
|
201
|
+
continue
|
|
202
|
+
if response.status_code >= 400:
|
|
203
|
+
raise SkillError(f"the download failed: the server said {response.status_code}")
|
|
204
|
+
return _read(response, policy)
|
|
205
|
+
raise SkillError("the download went through too many redirects")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def clone_repository(url: str, target: Path, policy: Policy) -> Path:
|
|
209
|
+
"""A clone of a repository, without its history.
|
|
210
|
+
|
|
211
|
+
A skill is a directory of files: the commits that led to it are of no use
|
|
212
|
+
to anybody, and the history of a big repository is a lot of download.
|
|
213
|
+
"""
|
|
214
|
+
check_git_url(url, policy)
|
|
215
|
+
if shutil.which("git") is None:
|
|
216
|
+
raise SkillError("git is not installed, so a git URL cannot be used")
|
|
217
|
+
try:
|
|
218
|
+
result = subprocess.run(
|
|
219
|
+
["git", "clone", "--depth", "1", "--quiet", url, str(target)],
|
|
220
|
+
capture_output=True,
|
|
221
|
+
text=True,
|
|
222
|
+
timeout=CLONE_TIMEOUT,
|
|
223
|
+
)
|
|
224
|
+
except subprocess.TimeoutExpired:
|
|
225
|
+
raise SkillError("the clone took too long") from None
|
|
226
|
+
if result.returncode != 0:
|
|
227
|
+
raise SkillError(f"the clone failed: {result.stderr.strip() or 'git said nothing'}")
|
|
228
|
+
return target
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def check_url(url: str, policy: Policy) -> None:
|
|
232
|
+
"""Whether an address may be fetched: the scheme, and where it points."""
|
|
233
|
+
parsed = urlparse(url)
|
|
234
|
+
scheme = parsed.scheme.lower()
|
|
235
|
+
if scheme not in ("https", "http") or (scheme == "http" and not policy.allow_insecure):
|
|
236
|
+
raise SkillError(f"'{url}' may not be fetched: only https is allowed")
|
|
237
|
+
host = parsed.hostname or ""
|
|
238
|
+
if not host:
|
|
239
|
+
raise SkillError(f"'{url}' has no host")
|
|
240
|
+
check_host(host, policy.allowed_hosts)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def check_git_url(url: str, policy: Policy) -> None:
|
|
244
|
+
"""Whether an address may be cloned."""
|
|
245
|
+
if url.startswith("git@"):
|
|
246
|
+
check_host(url[4:].split(":")[0], policy.allowed_hosts)
|
|
247
|
+
return
|
|
248
|
+
parsed = urlparse(url)
|
|
249
|
+
scheme = parsed.scheme.lower()
|
|
250
|
+
if scheme not in ("https", "http", "ssh", "git") or (scheme == "http" and not policy.allow_insecure):
|
|
251
|
+
raise SkillError(f"'{url}' may not be cloned: only https and ssh are allowed")
|
|
252
|
+
if parsed.hostname:
|
|
253
|
+
check_host(parsed.hostname, policy.allowed_hosts)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def check_host(host: str, allowed_hosts: tuple[str, ...]) -> None:
|
|
257
|
+
"""Whether a host may be reached. A host inside the network may not."""
|
|
258
|
+
if host in allowed_hosts:
|
|
259
|
+
return
|
|
260
|
+
try:
|
|
261
|
+
addresses = socket.getaddrinfo(host, None)
|
|
262
|
+
except socket.gaierror:
|
|
263
|
+
raise SkillError(f"the host '{host}' cannot be found") from None
|
|
264
|
+
for address in addresses:
|
|
265
|
+
ip = ipaddress.ip_address(address[4][0])
|
|
266
|
+
if any(ip in network for network in PRIVATE):
|
|
267
|
+
raise SkillError(f"the host '{host}' is inside the network, it is not allowed")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _parse(kind: str, text: str) -> Source:
|
|
271
|
+
if kind == "github":
|
|
272
|
+
return _parse_github(text)
|
|
273
|
+
if kind == "gitee":
|
|
274
|
+
return _parse_gitee(text)
|
|
275
|
+
if not text:
|
|
276
|
+
raise SkillError("there is no source")
|
|
277
|
+
return Source(kind=kind, url=text)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _parse_github(text: str) -> Source:
|
|
281
|
+
reference, _, ref = text.partition("@")
|
|
282
|
+
parts = [part for part in reference.split("/") if part]
|
|
283
|
+
if len(parts) < 2:
|
|
284
|
+
raise SkillError(f"'{text}' is not a repository: it needs an owner and a name")
|
|
285
|
+
return Source(kind="github", repo="/".join(parts[:2]), path="/".join(parts[2:]), ref=ref)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _parse_gitee(text: str) -> Source:
|
|
289
|
+
"""A repository of Gitee. The clone takes the branch the repository has."""
|
|
290
|
+
parts = [part for part in text.split("/") if part]
|
|
291
|
+
if len(parts) < 2:
|
|
292
|
+
raise SkillError(f"'{text}' is not a repository: it needs an owner and a name")
|
|
293
|
+
return Source(kind="gitee", repo="/".join(parts[:2]), path="/".join(parts[2:]))
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _parse_url(text: str) -> Source:
|
|
297
|
+
parsed = urlparse(text)
|
|
298
|
+
path = parsed.path.lower()
|
|
299
|
+
if path.endswith(".json"):
|
|
300
|
+
return Source(kind="registry", url=text)
|
|
301
|
+
if path.endswith("skill.md"):
|
|
302
|
+
return Source(kind="direct", url=text)
|
|
303
|
+
if path.endswith(".git"):
|
|
304
|
+
return Source(kind="git", url=text)
|
|
305
|
+
if parsed.hostname in ("github.com", "www.github.com"):
|
|
306
|
+
parts = [part for part in parsed.path.split("/") if part]
|
|
307
|
+
if len(parts) >= 2:
|
|
308
|
+
ref = ""
|
|
309
|
+
if len(parts) > 3 and parts[2] == "tree":
|
|
310
|
+
ref, parts = parts[3], parts[:2] + parts[4:]
|
|
311
|
+
return Source(kind="github", repo=f"{parts[0]}/{parts[1]}", path="/".join(parts[2:]), ref=ref)
|
|
312
|
+
if parsed.hostname in ("gitee.com", "www.gitee.com"):
|
|
313
|
+
parts = [part for part in parsed.path.split("/") if part]
|
|
314
|
+
if len(parts) >= 2:
|
|
315
|
+
if len(parts) > 3 and parts[2] == "tree":
|
|
316
|
+
parts = parts[:2] + parts[4:]
|
|
317
|
+
return Source(kind="gitee", repo=f"{parts[0]}/{parts[1]}", path="/".join(parts[2:]))
|
|
318
|
+
raise SkillError(f"'{text}' does not point at a skill: it is not a registry, a SKILL.md or a repository")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _entry(item: object) -> Entry | None:
|
|
322
|
+
"""One entry of a registry. An entry that cannot be read is left out."""
|
|
323
|
+
if not isinstance(item, dict):
|
|
324
|
+
return None
|
|
325
|
+
try:
|
|
326
|
+
source = source_of(item.get("source"))
|
|
327
|
+
except SkillError:
|
|
328
|
+
return None
|
|
329
|
+
return Entry(
|
|
330
|
+
name=str(item.get("name") or ""),
|
|
331
|
+
description=str(item.get("description") or ""),
|
|
332
|
+
source=source,
|
|
333
|
+
sha256=str(item.get("sha256") or ""),
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _fetch_github(source: Source, workdir: Path, policy: Policy, token: str) -> Path:
|
|
338
|
+
owner, _, name = source.repo.partition("/")
|
|
339
|
+
if not owner or not name:
|
|
340
|
+
raise SkillError(f"'{source.repo}' is not a repository: it needs an owner and a name")
|
|
341
|
+
url = f"{GITHUB_API}/repos/{owner}/{name}/tarball/{source.ref or 'HEAD'}"
|
|
342
|
+
headers = {"Accept": "application/vnd.github+json"}
|
|
343
|
+
if token:
|
|
344
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
345
|
+
archive = workdir / "repo.tar.gz"
|
|
346
|
+
archive.write_bytes(download(url, policy, headers))
|
|
347
|
+
root = workdir / "repo"
|
|
348
|
+
entries = unpack_tar(archive, root, policy, prefix=source.path)
|
|
349
|
+
if source.path and not entries:
|
|
350
|
+
raise SkillError(f"there is no '{source.path}' in {source.repo}")
|
|
351
|
+
return root
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _fetch_gitee(source: Source, workdir: Path, policy: Policy) -> Path:
|
|
355
|
+
owner, _, name = source.repo.partition("/")
|
|
356
|
+
if not owner or not name:
|
|
357
|
+
raise SkillError(f"'{source.repo}' is not a repository: it needs an owner and a name")
|
|
358
|
+
root = clone_repository(f"{GITEE}/{owner}/{name}.git", workdir / "repo", policy)
|
|
359
|
+
target = check_path(root, source.path) if source.path else root
|
|
360
|
+
if not target.is_dir():
|
|
361
|
+
raise SkillError(f"there is no '{source.path}' in {source.repo}")
|
|
362
|
+
return target
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _fetch_git(source: Source, workdir: Path, policy: Policy) -> Path:
|
|
366
|
+
return clone_repository(source.url, workdir / "repo", policy)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _fetch_direct(source: Source, workdir: Path, policy: Policy) -> Path:
|
|
370
|
+
target = workdir / "SKILL.md"
|
|
371
|
+
target.write_bytes(download(source.url, policy))
|
|
372
|
+
return target
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _read(response: requests.Response, policy: Policy) -> bytes:
|
|
376
|
+
"""The body of a response, as long as it is not too long."""
|
|
377
|
+
length = response.headers.get("Content-Length", "")
|
|
378
|
+
if length.isdigit() and int(length) > policy.max_bytes:
|
|
379
|
+
raise SkillError(f"the download is bigger than {policy.max_bytes} bytes")
|
|
380
|
+
content = bytearray()
|
|
381
|
+
for chunk in response.iter_content(CHUNK):
|
|
382
|
+
content += chunk
|
|
383
|
+
if len(content) > policy.max_bytes:
|
|
384
|
+
raise SkillError(f"the download is bigger than {policy.max_bytes} bytes")
|
|
385
|
+
return bytes(content)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
__all__ = [
|
|
389
|
+
"Entry",
|
|
390
|
+
"GITEE",
|
|
391
|
+
"HOPS",
|
|
392
|
+
"PRIVATE",
|
|
393
|
+
"REDIRECTS",
|
|
394
|
+
"Source",
|
|
395
|
+
"check_git_url",
|
|
396
|
+
"check_host",
|
|
397
|
+
"check_url",
|
|
398
|
+
"clone_repository",
|
|
399
|
+
"download",
|
|
400
|
+
"fetch",
|
|
401
|
+
"fetch_registry",
|
|
402
|
+
"parse_source",
|
|
403
|
+
"source_of",
|
|
404
|
+
]
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Builders for tests and scripts: a tool context and executor to run tools in."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from coderagent.config.schema import ToolConfig
|
|
6
|
+
from coderagent.core.events import EventBus
|
|
7
|
+
from coderagent.core.session import Session
|
|
8
|
+
from coderagent.tools.base import ToolContext
|
|
9
|
+
from coderagent.tools.builtin import build_registry
|
|
10
|
+
from coderagent.tools.executor import ToolExecutor
|
|
11
|
+
from coderagent.tools.permissions import ApprovalDecision, Approver, HeadlessApprover, PermissionMode, PermissionPolicy
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AllowAllApprover:
|
|
15
|
+
"""Approves every request."""
|
|
16
|
+
|
|
17
|
+
def request(self, tool: str, params: dict, reason: str) -> ApprovalDecision:
|
|
18
|
+
return ApprovalDecision.ALLOW
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_context(
|
|
22
|
+
cwd: Path,
|
|
23
|
+
*,
|
|
24
|
+
session: Session | None = None,
|
|
25
|
+
bus: EventBus | None = None,
|
|
26
|
+
policy: PermissionPolicy | None = None,
|
|
27
|
+
config: ToolConfig | None = None,
|
|
28
|
+
) -> ToolContext:
|
|
29
|
+
return ToolContext(
|
|
30
|
+
cwd=Path(cwd),
|
|
31
|
+
session=session or Session(id="test", cwd=Path(cwd), created_at=0.0, updated_at=0.0),
|
|
32
|
+
bus=bus or EventBus(),
|
|
33
|
+
policy=policy or PermissionPolicy(PermissionMode.BYPASS, [], cwd=Path(cwd)),
|
|
34
|
+
config=config or ToolConfig(),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def build_executor(
|
|
39
|
+
cwd: Path,
|
|
40
|
+
*,
|
|
41
|
+
mode: PermissionMode = PermissionMode.BYPASS,
|
|
42
|
+
approver: Approver | None = None,
|
|
43
|
+
config: ToolConfig | None = None,
|
|
44
|
+
context: ToolContext | None = None,
|
|
45
|
+
rules_home=None,
|
|
46
|
+
hooks=None,
|
|
47
|
+
store=None,
|
|
48
|
+
) -> ToolExecutor:
|
|
49
|
+
registry = build_registry(config.enabled if config else None, config.disabled if config else None)
|
|
50
|
+
ctx = context or build_context(cwd, policy=PermissionPolicy(mode, [], cwd=Path(cwd)), config=config)
|
|
51
|
+
return ToolExecutor(
|
|
52
|
+
registry,
|
|
53
|
+
ctx.policy,
|
|
54
|
+
lambda: ctx,
|
|
55
|
+
approver or HeadlessApprover(allow=False),
|
|
56
|
+
rules_home=rules_home,
|
|
57
|
+
hooks=hooks,
|
|
58
|
+
store=store,
|
|
59
|
+
)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""A model that replays pre-written responses, so tests never hit a real API."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from coderagent.models.streaming import ModelEvent
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ScriptedModel:
|
|
10
|
+
model_name = "scripted"
|
|
11
|
+
|
|
12
|
+
def __init__(
|
|
13
|
+
self,
|
|
14
|
+
responses: list[dict] | None = None,
|
|
15
|
+
side_effect: Callable[[list[dict]], dict] | None = None,
|
|
16
|
+
) -> None:
|
|
17
|
+
self.responses = list(responses or [])
|
|
18
|
+
self.side_effect = side_effect
|
|
19
|
+
self.calls: list[list[dict]] = []
|
|
20
|
+
|
|
21
|
+
def query(self, messages: list[dict], tools: list[dict] | None = None, **kwargs) -> dict:
|
|
22
|
+
"""The call is recorded as it was: the messages are copied, not shared.
|
|
23
|
+
|
|
24
|
+
The caller changes the history in place, and the record has to show what
|
|
25
|
+
the model saw, not what the history looks like later.
|
|
26
|
+
"""
|
|
27
|
+
self.calls.append([dict(message) for message in messages])
|
|
28
|
+
if self.side_effect is not None:
|
|
29
|
+
return self.side_effect(messages)
|
|
30
|
+
if not self.responses:
|
|
31
|
+
msg = f"ScriptedModel ran out of responses after {len(self.calls)} calls"
|
|
32
|
+
raise AssertionError(msg)
|
|
33
|
+
return self.responses.pop(0)
|
|
34
|
+
|
|
35
|
+
def query_stream(self, messages: list[dict], tools: list[dict] | None = None, **kwargs):
|
|
36
|
+
message = self.query(messages, tools=tools, **kwargs)
|
|
37
|
+
if message.get("content"):
|
|
38
|
+
yield ModelEvent(type="text", content=message["content"])
|
|
39
|
+
for call in message.get("tool_calls") or []:
|
|
40
|
+
yield ModelEvent(type="tool_call_done", tool_call=call)
|
|
41
|
+
extra = message.get("extra") or {}
|
|
42
|
+
yield ModelEvent(
|
|
43
|
+
type="usage",
|
|
44
|
+
cost=extra.get("cost", 0.0),
|
|
45
|
+
raw={
|
|
46
|
+
"usage": {
|
|
47
|
+
"prompt_tokens": extra.get("tokens_in", 0),
|
|
48
|
+
"completion_tokens": extra.get("tokens_out", 0),
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def get_template_vars(self) -> dict[str, Any]:
|
|
54
|
+
return {"model_name": "scripted"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Tools: registry, permissions and the built-in tool implementations."""
|
coderagent/tools/base.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Tool abstractions shared by every tool implementation."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
from coderagent.config.schema import ToolConfig
|
|
9
|
+
from coderagent.core.events import EventBus
|
|
10
|
+
from coderagent.core.os_sandbox import Confinement
|
|
11
|
+
from coderagent.core.session import Session
|
|
12
|
+
from coderagent.tools.permissions import PermissionPolicy
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class ToolResult:
|
|
17
|
+
content: str
|
|
18
|
+
is_error: bool = False
|
|
19
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class ToolContext:
|
|
24
|
+
cwd: Path
|
|
25
|
+
session: Session
|
|
26
|
+
bus: EventBus
|
|
27
|
+
policy: PermissionPolicy
|
|
28
|
+
config: ToolConfig
|
|
29
|
+
env: Any = None
|
|
30
|
+
"""Execution environment for tools that need to run commands."""
|
|
31
|
+
sandbox: Confinement | None = None
|
|
32
|
+
"""The boundary of the operating system around the commands of the agent."""
|
|
33
|
+
background: dict[str, Any] = field(default_factory=dict)
|
|
34
|
+
"""Background shell tasks, keyed by task id."""
|
|
35
|
+
cancel: Callable[[], bool] | None = None
|
|
36
|
+
"""Whether the turn should stop. A tool that runs long asks it while it runs."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Tool(Protocol):
|
|
40
|
+
name: str
|
|
41
|
+
description: str
|
|
42
|
+
parameters: dict[str, Any]
|
|
43
|
+
"""JSON Schema of the tool's arguments."""
|
|
44
|
+
|
|
45
|
+
def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult: ...
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def resolve_path(ctx: ToolContext, path: str) -> Path:
|
|
49
|
+
"""Resolve a tool argument against the session's working directory."""
|
|
50
|
+
candidate = Path(path)
|
|
51
|
+
return candidate if candidate.is_absolute() else ctx.cwd / candidate
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
__all__ = ["Tool", "ToolContext", "ToolResult", "resolve_path"]
|