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
coderagent/web/app.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""The FastAPI application: the pages, the API and the state they share."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
7
|
+
from fastapi.responses import RedirectResponse
|
|
8
|
+
from fastapi.staticfiles import StaticFiles
|
|
9
|
+
from fastapi.templating import Jinja2Templates
|
|
10
|
+
|
|
11
|
+
from coderagent.config.loader import load_config
|
|
12
|
+
from coderagent.config.schema import Config
|
|
13
|
+
from coderagent.core.protocols import ModelBackend
|
|
14
|
+
from coderagent.core.session import SessionStore
|
|
15
|
+
from coderagent.ui.spinner import FRAMES
|
|
16
|
+
from coderagent.web.api import router
|
|
17
|
+
from coderagent.web.i18n import COOKIE, DEFAULT_LANGUAGE, LANGUAGES, STRINGS, Language, locale_of
|
|
18
|
+
from coderagent.web.sessions import SessionRegistry
|
|
19
|
+
from coderagent.web.skills_api import router as skills_router
|
|
20
|
+
|
|
21
|
+
TEMPLATES = Path(__file__).parent / "templates"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def available_languages() -> tuple[Language, ...]:
|
|
25
|
+
"""The languages that can be served: templates and strings are both there."""
|
|
26
|
+
return tuple(
|
|
27
|
+
language for language in LANGUAGES if (TEMPLATES / language.code).is_dir() and language.code in STRINGS
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def create_app(
|
|
32
|
+
config: Config,
|
|
33
|
+
cwd: Path,
|
|
34
|
+
*,
|
|
35
|
+
store: SessionStore | None = None,
|
|
36
|
+
model: ModelBackend | None = None,
|
|
37
|
+
config_spec: list[str] | None = None,
|
|
38
|
+
permission_mode: str | None = None,
|
|
39
|
+
) -> FastAPI:
|
|
40
|
+
"""The web interface of the coding agent.
|
|
41
|
+
|
|
42
|
+
`config` is the configuration the server started with. A new session reads
|
|
43
|
+
the configuration files again, so what the user writes in the settings page
|
|
44
|
+
is picked up by the sessions that come after it.
|
|
45
|
+
"""
|
|
46
|
+
cwd = Path(cwd)
|
|
47
|
+
spec = list(config_spec or [])
|
|
48
|
+
registry = SessionRegistry(config, cwd, store=store, model=model, permission_mode=permission_mode, config_spec=spec)
|
|
49
|
+
app = FastAPI(title="coderagent", docs_url="/api/docs")
|
|
50
|
+
app.state.registry = registry
|
|
51
|
+
app.state.cwd = cwd
|
|
52
|
+
app.state.config = config
|
|
53
|
+
app.state.config_spec = spec
|
|
54
|
+
app.state.config_of = lambda: load_config(app.state.config_spec, cwd=cwd)
|
|
55
|
+
app.include_router(router)
|
|
56
|
+
app.include_router(skills_router)
|
|
57
|
+
|
|
58
|
+
languages = available_languages()
|
|
59
|
+
codes = [language.code for language in languages]
|
|
60
|
+
templates = {language.code: Jinja2Templates(directory=str(TEMPLATES / language.code)) for language in languages}
|
|
61
|
+
app.mount("/static", StaticFiles(directory=str(Path(__file__).parent / "static")), name="static")
|
|
62
|
+
|
|
63
|
+
def page(request: Request, name: str) -> Any:
|
|
64
|
+
"""A page in the language of the visitor."""
|
|
65
|
+
language = locale_of(request, codes)
|
|
66
|
+
return templates[language].TemplateResponse(
|
|
67
|
+
request,
|
|
68
|
+
name,
|
|
69
|
+
{
|
|
70
|
+
"cwd": str(cwd),
|
|
71
|
+
"language": language,
|
|
72
|
+
"languages": languages,
|
|
73
|
+
"strings": STRINGS[language],
|
|
74
|
+
"dots": list(FRAMES),
|
|
75
|
+
# the dots that say the agent is working: the same as in the terminal
|
|
76
|
+
},
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
@app.get("/")
|
|
80
|
+
def chat(request: Request):
|
|
81
|
+
"""The chat page."""
|
|
82
|
+
return page(request, "chat.html")
|
|
83
|
+
|
|
84
|
+
@app.get("/settings")
|
|
85
|
+
def settings(request: Request):
|
|
86
|
+
"""The page where the model is configured."""
|
|
87
|
+
return page(request, "settings.html")
|
|
88
|
+
|
|
89
|
+
@app.get("/skills")
|
|
90
|
+
def skills(request: Request):
|
|
91
|
+
"""The page where the skills are looked at and installed."""
|
|
92
|
+
return page(request, "skills.html")
|
|
93
|
+
|
|
94
|
+
@app.get("/api/i18n/{language}")
|
|
95
|
+
def strings_of(language: str):
|
|
96
|
+
"""The strings of a language, for a browser that switches without a reload."""
|
|
97
|
+
if language not in codes:
|
|
98
|
+
raise HTTPException(status_code=404, detail="unknown language")
|
|
99
|
+
return {"language": language, "strings": STRINGS[language]}
|
|
100
|
+
|
|
101
|
+
@app.get("/lang/{language}")
|
|
102
|
+
def set_language(language: str, request: Request):
|
|
103
|
+
"""The language the visitor chose, remembered in a cookie."""
|
|
104
|
+
if language not in codes:
|
|
105
|
+
language = DEFAULT_LANGUAGE if DEFAULT_LANGUAGE in codes else codes[0]
|
|
106
|
+
target = request.query_params.get("next", "/")
|
|
107
|
+
if not target.startswith("/") or target.startswith("//"):
|
|
108
|
+
target = "/"
|
|
109
|
+
response = RedirectResponse(target, status_code=303)
|
|
110
|
+
response.set_cookie(COOKIE, language, max_age=31536000, samesite="lax")
|
|
111
|
+
return response
|
|
112
|
+
|
|
113
|
+
return app
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Approval over HTTP: the tool waits in its thread until the browser answers."""
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from coderagent.core.events import Event, EventBus, EventType
|
|
7
|
+
from coderagent.tools.permissions import ApprovalDecision
|
|
8
|
+
|
|
9
|
+
DEFAULT_TIMEOUT = 300
|
|
10
|
+
"""Seconds to wait for an answer before the tool is denied."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class WebApprover:
|
|
14
|
+
"""Asks the browser whether a tool may run.
|
|
15
|
+
|
|
16
|
+
The request goes into the event stream, the answer comes back over HTTP and
|
|
17
|
+
wakes the tool up. Without an answer the tool is denied, never run.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, bus: EventBus, session_id: str = "", timeout: int = 0) -> None:
|
|
21
|
+
self.bus = bus
|
|
22
|
+
self.session_id = session_id
|
|
23
|
+
self.timeout = timeout or DEFAULT_TIMEOUT
|
|
24
|
+
self._events: dict[str, threading.Event] = {}
|
|
25
|
+
self._decisions: dict[str, ApprovalDecision] = {}
|
|
26
|
+
self._lock = threading.Lock()
|
|
27
|
+
self._counter = 0
|
|
28
|
+
|
|
29
|
+
def request(self, tool: str, params: dict, reason: str) -> ApprovalDecision:
|
|
30
|
+
"""Wait until the user answers."""
|
|
31
|
+
with self._lock:
|
|
32
|
+
self._counter += 1
|
|
33
|
+
key = str(self._counter)
|
|
34
|
+
event = threading.Event()
|
|
35
|
+
self._events[key] = event
|
|
36
|
+
self.bus.publish(
|
|
37
|
+
Event(
|
|
38
|
+
type=EventType.APPROVAL_REQUEST,
|
|
39
|
+
session_id=self.session_id,
|
|
40
|
+
timestamp=time.time(),
|
|
41
|
+
payload={"id": key, "tool": tool, "params": params, "reason": reason},
|
|
42
|
+
)
|
|
43
|
+
)
|
|
44
|
+
if not event.wait(self.timeout):
|
|
45
|
+
with self._lock:
|
|
46
|
+
self._events.pop(key, None)
|
|
47
|
+
self._decisions.pop(key, None)
|
|
48
|
+
self._respond(key, "deny", timed_out=True)
|
|
49
|
+
return ApprovalDecision.DENY
|
|
50
|
+
with self._lock:
|
|
51
|
+
self._events.pop(key, None)
|
|
52
|
+
return self._decisions.pop(key, ApprovalDecision.DENY)
|
|
53
|
+
|
|
54
|
+
def answer(self, key: str, decision: ApprovalDecision) -> bool:
|
|
55
|
+
"""Give the answer of the user to the waiting tool."""
|
|
56
|
+
with self._lock:
|
|
57
|
+
if key not in self._events:
|
|
58
|
+
return False
|
|
59
|
+
self._decisions[key] = decision
|
|
60
|
+
self._events[key].set()
|
|
61
|
+
self._respond(key, decision.value)
|
|
62
|
+
return True
|
|
63
|
+
|
|
64
|
+
def _respond(self, key: str, decision: str, timed_out: bool = False) -> None:
|
|
65
|
+
"""Tell the browser what the answer was."""
|
|
66
|
+
self.bus.publish(
|
|
67
|
+
Event(
|
|
68
|
+
type=EventType.APPROVAL_RESPONSE,
|
|
69
|
+
session_id=self.session_id,
|
|
70
|
+
timestamp=time.time(),
|
|
71
|
+
payload={"id": key, "decision": decision, "timed_out": timed_out},
|
|
72
|
+
)
|
|
73
|
+
)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""The permission settings, as the browser sees them.
|
|
2
|
+
|
|
3
|
+
The settings of the model have their own modules now: `coderagent.models.settings`
|
|
4
|
+
holds them, `coderagent.config.writer` writes them and `coderagent.models.check`
|
|
5
|
+
tries them out.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from coderagent.config.loader import config_layers, load_config
|
|
12
|
+
from coderagent.config.writer import NETWORK_POLICIES, PERMISSION_FIELDS, PERMISSION_MODES
|
|
13
|
+
from coderagent.models.provider import PROVIDERS
|
|
14
|
+
|
|
15
|
+
ENV_KEYS = PROVIDERS
|
|
16
|
+
"""The environment variable of the key of a provider. The name of the model says which provider it is."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _permission_of(layer: dict) -> dict:
|
|
20
|
+
permissions = layer.get("permissions")
|
|
21
|
+
return permissions if isinstance(permissions, dict) else {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _permission_source(layers: list[tuple[str, dict]], field: str) -> str:
|
|
25
|
+
"""The layer the setting comes from, the last one that defines it."""
|
|
26
|
+
source = "defaults"
|
|
27
|
+
for name, layer in layers:
|
|
28
|
+
if field in _permission_of(layer):
|
|
29
|
+
source = name
|
|
30
|
+
return source
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def permissions_view(cwd: Path, *, server_mode: str = "") -> dict[str, Any]:
|
|
34
|
+
"""The permission settings, as the browser sees them.
|
|
35
|
+
|
|
36
|
+
`server_mode` is the mode the server was started with. It wins over the
|
|
37
|
+
files, so it is what the page shows and what the user has to be told about.
|
|
38
|
+
"""
|
|
39
|
+
layers = config_layers(cwd)
|
|
40
|
+
permissions = load_config([], cwd=cwd).permissions
|
|
41
|
+
source = {field: _permission_source(layers, field) for field in PERMISSION_FIELDS}
|
|
42
|
+
if server_mode:
|
|
43
|
+
source["mode"] = "server"
|
|
44
|
+
return {
|
|
45
|
+
"mode": server_mode or permissions.mode,
|
|
46
|
+
"modes": list(PERMISSION_MODES),
|
|
47
|
+
"deny_paths": list(permissions.deny_paths),
|
|
48
|
+
"include_dirs": list(permissions.include_dirs),
|
|
49
|
+
"network": permissions.network,
|
|
50
|
+
"networks": list(NETWORK_POLICIES),
|
|
51
|
+
"source": source,
|
|
52
|
+
"server_mode": server_mode,
|
|
53
|
+
}
|
coderagent/web/events.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Translate the events of the core into the items the browser renders.
|
|
2
|
+
|
|
3
|
+
The core speaks in events, the browser in items. Most events are one item; a tool
|
|
4
|
+
call is one item per action, and a tool result is one item per observation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from coderagent.core.content import describe_message, images_of, text_of
|
|
8
|
+
from coderagent.core.events import Event, EventType
|
|
9
|
+
from coderagent.core.loop import REVIEW_NOTE
|
|
10
|
+
from coderagent.ui.widgets.tool_card import summarize
|
|
11
|
+
|
|
12
|
+
TRANSIENT_KINDS = frozenset({"text_delta", "reasoning_delta"})
|
|
13
|
+
"""The items that are only for the moment.
|
|
14
|
+
|
|
15
|
+
The model streams its answer in pieces. The browser sees them while they arrive,
|
|
16
|
+
but they are not kept: a long answer would push the history of the session out of
|
|
17
|
+
the buffer. The whole answer comes later as one `assistant_message`.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def normalize(event: Event) -> list[dict]:
|
|
22
|
+
"""The items of one event. An event that says nothing renders nothing."""
|
|
23
|
+
payload = event.payload
|
|
24
|
+
if event.type == EventType.USER_MESSAGE:
|
|
25
|
+
content = payload.get("content", "")
|
|
26
|
+
if content == REVIEW_NOTE:
|
|
27
|
+
"""The diff of a review has its own card. The note that replaces it says nothing to the user."""
|
|
28
|
+
return []
|
|
29
|
+
return [
|
|
30
|
+
{
|
|
31
|
+
"kind": "user_message",
|
|
32
|
+
"content": describe_message(content),
|
|
33
|
+
"text": text_of(content),
|
|
34
|
+
"original": payload.get("original", ""),
|
|
35
|
+
"images": images_of(content),
|
|
36
|
+
}
|
|
37
|
+
]
|
|
38
|
+
if event.type == EventType.ASSISTANT_MESSAGE:
|
|
39
|
+
message = payload.get("message") or {}
|
|
40
|
+
return [
|
|
41
|
+
{
|
|
42
|
+
"kind": "assistant_message",
|
|
43
|
+
"content": message.get("content", ""),
|
|
44
|
+
"reasoning": (message.get("extra") or {}).get("reasoning", ""),
|
|
45
|
+
}
|
|
46
|
+
]
|
|
47
|
+
if event.type == EventType.TEXT_DELTA:
|
|
48
|
+
return [{"kind": "text_delta", "content": payload.get("content", "")}]
|
|
49
|
+
if event.type == EventType.REASONING:
|
|
50
|
+
return [{"kind": "reasoning_delta", "content": payload.get("content", "")}]
|
|
51
|
+
if event.type == EventType.TOOL_CALL:
|
|
52
|
+
return [_tool_call(action) for action in payload.get("actions") or []]
|
|
53
|
+
if event.type == EventType.TOOL_RESULT:
|
|
54
|
+
return _tool_result(payload)
|
|
55
|
+
if event.type == EventType.APPROVAL_REQUEST:
|
|
56
|
+
return [
|
|
57
|
+
{
|
|
58
|
+
"kind": "approval_request",
|
|
59
|
+
"id": payload.get("id", ""),
|
|
60
|
+
"tool": payload.get("tool", ""),
|
|
61
|
+
"params": payload.get("params", {}),
|
|
62
|
+
"reason": payload.get("reason", ""),
|
|
63
|
+
}
|
|
64
|
+
]
|
|
65
|
+
if event.type == EventType.APPROVAL_RESPONSE:
|
|
66
|
+
return [
|
|
67
|
+
{
|
|
68
|
+
"kind": "approval_response",
|
|
69
|
+
"id": payload.get("id", ""),
|
|
70
|
+
"decision": payload.get("decision", ""),
|
|
71
|
+
"timed_out": bool(payload.get("timed_out")),
|
|
72
|
+
}
|
|
73
|
+
]
|
|
74
|
+
if event.type == EventType.STATE_CHANGE:
|
|
75
|
+
return [{"kind": "state", **{key: value for key, value in payload.items() if value is not None}}]
|
|
76
|
+
if event.type == EventType.COMPACTION:
|
|
77
|
+
return [{"kind": "compaction", "tokens": payload.get("tokens", 0), "cost": payload.get("cost", 0.0)}]
|
|
78
|
+
if event.type == EventType.RECAP:
|
|
79
|
+
return [{"kind": "recap", "text": payload.get("text", ""), "cost": payload.get("cost", 0.0)}]
|
|
80
|
+
if event.type == EventType.SIDE_CONVERSATION:
|
|
81
|
+
return [{"kind": "side_conversation", "question": payload.get("question", "")}]
|
|
82
|
+
if event.type == EventType.VERIFY:
|
|
83
|
+
return [
|
|
84
|
+
{
|
|
85
|
+
"kind": "verify",
|
|
86
|
+
"commands": payload.get("commands", []),
|
|
87
|
+
"failed": payload.get("failed", []),
|
|
88
|
+
}
|
|
89
|
+
]
|
|
90
|
+
if event.type == EventType.REFLECTION:
|
|
91
|
+
return [
|
|
92
|
+
{
|
|
93
|
+
"kind": "reflection",
|
|
94
|
+
"cost": payload.get("cost", 0.0),
|
|
95
|
+
"priced": payload.get("priced", True),
|
|
96
|
+
"purpose": payload.get("purpose", ""),
|
|
97
|
+
"model": payload.get("model", ""),
|
|
98
|
+
"project_facts": payload.get("project_facts", []),
|
|
99
|
+
"user_preferences": payload.get("user_preferences", []),
|
|
100
|
+
}
|
|
101
|
+
]
|
|
102
|
+
if event.type == EventType.TURN_END:
|
|
103
|
+
"""Why the turn ended. The browser says it, so that a turn that was cut
|
|
104
|
+
off does not look like a turn that ended well."""
|
|
105
|
+
return [
|
|
106
|
+
{
|
|
107
|
+
"kind": "turn_stopped",
|
|
108
|
+
"stop_reason": payload.get("stop_reason", ""),
|
|
109
|
+
"calls": payload.get("calls", 0),
|
|
110
|
+
"error": payload.get("error", ""),
|
|
111
|
+
}
|
|
112
|
+
]
|
|
113
|
+
if event.type == EventType.REVERTED:
|
|
114
|
+
return [{"kind": "reverted", "messages": payload.get("messages", 0)}]
|
|
115
|
+
if event.type == EventType.ERROR:
|
|
116
|
+
return [{"kind": "error", "error": payload.get("error", "")}]
|
|
117
|
+
return []
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _tool_call(action: dict) -> dict:
|
|
121
|
+
args = action.get("args") or {}
|
|
122
|
+
return {
|
|
123
|
+
"kind": "tool_call",
|
|
124
|
+
"tool": action.get("tool", ""),
|
|
125
|
+
"args": args,
|
|
126
|
+
"summary": summarize(args),
|
|
127
|
+
"tool_call_id": action.get("tool_call_id", ""),
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _tool_result(payload: dict) -> list[dict]:
|
|
132
|
+
"""A tool result comes in two shapes: from the executor and from the context."""
|
|
133
|
+
items = []
|
|
134
|
+
if "tool" in payload:
|
|
135
|
+
"""The executor knows the tool and the diff of the change."""
|
|
136
|
+
items.append(
|
|
137
|
+
{
|
|
138
|
+
"kind": "tool_result",
|
|
139
|
+
"tool": payload.get("tool", ""),
|
|
140
|
+
"tool_call_id": payload.get("tool_call_id", ""),
|
|
141
|
+
"content": payload.get("content", ""),
|
|
142
|
+
"is_error": bool(payload.get("is_error")),
|
|
143
|
+
"diff": payload.get("diff", ""),
|
|
144
|
+
}
|
|
145
|
+
)
|
|
146
|
+
for message in payload.get("messages") or []:
|
|
147
|
+
"""The context records what the model gets to see."""
|
|
148
|
+
items.append(
|
|
149
|
+
{
|
|
150
|
+
"kind": "tool_result",
|
|
151
|
+
"tool_call_id": message.get("tool_call_id", ""),
|
|
152
|
+
"content": message.get("content", ""),
|
|
153
|
+
"is_error": str(message.get("content", "")).startswith("Error:"),
|
|
154
|
+
"diff": "",
|
|
155
|
+
}
|
|
156
|
+
)
|
|
157
|
+
if payload.get("todos"):
|
|
158
|
+
items.append({"kind": "todos", "todos": payload.get("todos") or []})
|
|
159
|
+
return items
|
coderagent/web/files.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Browsing the working directory from the browser.
|
|
2
|
+
|
|
3
|
+
The paths the browser asks for have to stay inside the working directory. The
|
|
4
|
+
rules of the user cannot widen that, so the check is done here with
|
|
5
|
+
`within_bounds` and not through `evaluate`, which judges whether a call is
|
|
6
|
+
allowed rather than whether a path is in range.
|
|
7
|
+
|
|
8
|
+
The panel of the files lists the directories the user opened to the agent
|
|
9
|
+
(`permissions.include_dirs`) and nothing else. Without them the working
|
|
10
|
+
directory is the one.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import subprocess
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from coderagent.config.schema import Config
|
|
18
|
+
from coderagent.core.events import EventBus
|
|
19
|
+
from coderagent.core.session import Session
|
|
20
|
+
from coderagent.tools.base import ToolContext
|
|
21
|
+
from coderagent.tools.builtin.fs import ReadTool
|
|
22
|
+
from coderagent.tools.builtin.search import list_entries
|
|
23
|
+
from coderagent.tools.permissions import PermissionPolicy
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class OutsideBounds(ValueError):
|
|
27
|
+
"""The path is not in the working directory."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def policy_for(config: Config, cwd: Path) -> PermissionPolicy:
|
|
31
|
+
"""The policy of the boundaries. The rules are not part of it."""
|
|
32
|
+
return PermissionPolicy(
|
|
33
|
+
config.permissions.mode,
|
|
34
|
+
[],
|
|
35
|
+
cwd=cwd,
|
|
36
|
+
include_dirs=config.permissions.include_dirs,
|
|
37
|
+
deny_paths=config.permissions.deny_paths,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def resolve(cwd: Path, path: str, policy: PermissionPolicy) -> Path:
|
|
42
|
+
"""The absolute path of a file of the working directory."""
|
|
43
|
+
target = Path(path or ".")
|
|
44
|
+
resolved = (target if target.is_absolute() else cwd / target).resolve()
|
|
45
|
+
if not policy.within_bounds(str(resolved)):
|
|
46
|
+
raise OutsideBounds(f"'{path}' is outside the working directory {policy.cwd}")
|
|
47
|
+
denied = policy.denied_path(str(resolved))
|
|
48
|
+
if denied:
|
|
49
|
+
raise OutsideBounds(f"'{path}' is denied by the configuration ('{denied}')")
|
|
50
|
+
return resolved
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def listing(cwd: Path, path: str, depth: int, policy: PermissionPolicy) -> tuple[str, list[dict[str, Any]]]:
|
|
54
|
+
"""The directory that is listed and the entries of it.
|
|
55
|
+
|
|
56
|
+
Only the directories that are open may be listed: the other files and
|
|
57
|
+
directories of the disk are not shown to the browser.
|
|
58
|
+
"""
|
|
59
|
+
directories = policy.roots()
|
|
60
|
+
if not path or path == ".":
|
|
61
|
+
if len(directories) == 1:
|
|
62
|
+
return _entries(directories[0], depth)
|
|
63
|
+
return "", [_entry(directory, True) for directory in directories]
|
|
64
|
+
target = resolve(cwd, path, policy)
|
|
65
|
+
if not any(target == directory or target.is_relative_to(directory) for directory in directories):
|
|
66
|
+
raise OutsideBounds(
|
|
67
|
+
f"'{path}' is not in the directories that are open: {', '.join(str(d) for d in directories)}"
|
|
68
|
+
)
|
|
69
|
+
return _entries(target, depth)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _entries(target: Path, depth: int) -> tuple[str, list[dict[str, Any]]]:
|
|
73
|
+
"""The entries of a directory, one level or the whole tree."""
|
|
74
|
+
if not target.is_dir():
|
|
75
|
+
raise NotADirectoryError(f"'{target}' is not a directory")
|
|
76
|
+
entries = []
|
|
77
|
+
for absolute, kind in list_entries(target, depth):
|
|
78
|
+
entries.append(_entry(absolute, kind == "d"))
|
|
79
|
+
return target.as_posix(), entries
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _entry(absolute: Path, is_dir: bool) -> dict[str, Any]:
|
|
83
|
+
"""One entry of the list. The path is absolute: the browser sends it back."""
|
|
84
|
+
return {
|
|
85
|
+
"path": absolute.as_posix(),
|
|
86
|
+
"name": absolute.name,
|
|
87
|
+
"is_dir": is_dir,
|
|
88
|
+
"size": absolute.stat().st_size if not is_dir else 0,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def read(cwd: Path, path: str, policy: PermissionPolicy, config: Config) -> dict[str, Any]:
|
|
93
|
+
"""The content of a file, with the line numbers the agent gets to see."""
|
|
94
|
+
target = resolve(cwd, path, policy)
|
|
95
|
+
context = ToolContext(
|
|
96
|
+
cwd=cwd,
|
|
97
|
+
session=Session(id="web", cwd=cwd, created_at=0.0, updated_at=0.0),
|
|
98
|
+
bus=EventBus(),
|
|
99
|
+
policy=policy,
|
|
100
|
+
config=config.tools,
|
|
101
|
+
)
|
|
102
|
+
result = ReadTool().run({"path": str(target)}, context)
|
|
103
|
+
return {"path": str(target), "content": result.content, "is_error": result.is_error}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def diff(cwd: Path, path: str, policy: PermissionPolicy) -> str:
|
|
107
|
+
"""The changes of the working tree for a path."""
|
|
108
|
+
target = resolve(cwd, path, policy)
|
|
109
|
+
if not target.is_relative_to(cwd):
|
|
110
|
+
"""The file is not in the working tree: it has no diff."""
|
|
111
|
+
return ""
|
|
112
|
+
result = subprocess.run(["git", "diff", "--", str(target)], cwd=cwd, capture_output=True, text=True, check=False)
|
|
113
|
+
if result.returncode != 0:
|
|
114
|
+
return result.stderr.strip() or f"git diff failed with code {result.returncode}"
|
|
115
|
+
return result.stdout
|