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,104 @@
|
|
|
1
|
+
"""The card of a tool call: what was called, how long it took and what it returned."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from textual.widgets import Static
|
|
7
|
+
|
|
8
|
+
from coderagent.ui.spinner import INTERVAL, dots
|
|
9
|
+
from coderagent.ui.widgets.diff_view import colorize_diff
|
|
10
|
+
from coderagent.ui.widgets.markup import literal
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def summarize(args: dict[str, Any]) -> str:
|
|
14
|
+
"""The part of the arguments that is worth showing."""
|
|
15
|
+
for key in ("path", "command", "pattern", "query", "url"):
|
|
16
|
+
if key in args:
|
|
17
|
+
return f"{key}={args[key]}"
|
|
18
|
+
return ", ".join(f"{key}={value}" for key, value in list(args.items())[:2])
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _fold(text: str, lines: int = 8) -> str:
|
|
22
|
+
"""The first lines of a long output; the rest is only counted."""
|
|
23
|
+
rows = text.splitlines()
|
|
24
|
+
if len(rows) <= lines:
|
|
25
|
+
return text
|
|
26
|
+
return "\n".join([*rows[:lines], f"▸ {len(rows) - lines} more lines"])
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ToolCard(Static):
|
|
30
|
+
"""One tool call, from the moment it starts until it is done."""
|
|
31
|
+
|
|
32
|
+
DEFAULT_CSS = """
|
|
33
|
+
ToolCard {
|
|
34
|
+
height: auto;
|
|
35
|
+
margin: 1 0 0 0;
|
|
36
|
+
padding: 0 1;
|
|
37
|
+
}
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, tool: str, args: dict[str, Any], call_id: str = "", **kwargs) -> None:
|
|
41
|
+
super().__init__(**kwargs)
|
|
42
|
+
self.tool = tool
|
|
43
|
+
self.args = args
|
|
44
|
+
self.call_id = call_id
|
|
45
|
+
self.started = time.time()
|
|
46
|
+
self.duration = 0.0
|
|
47
|
+
self.text = ""
|
|
48
|
+
"""What the tool returned. It is not markup."""
|
|
49
|
+
self.is_error = False
|
|
50
|
+
self.diff = ""
|
|
51
|
+
self.step = 0
|
|
52
|
+
"""The frame of the animation that says the tool is running."""
|
|
53
|
+
self._timer = None
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def content(self) -> str:
|
|
57
|
+
"""What the tool returned. It is not markup."""
|
|
58
|
+
return self.text
|
|
59
|
+
|
|
60
|
+
@content.setter
|
|
61
|
+
def content(self, text: str) -> None:
|
|
62
|
+
"""Set what the tool returned. The output of the tool is not markup."""
|
|
63
|
+
self.text = text
|
|
64
|
+
self.clear_cached_dimensions()
|
|
65
|
+
self.refresh(layout=True)
|
|
66
|
+
|
|
67
|
+
def on_mount(self) -> None:
|
|
68
|
+
"""The tool is running: the dots grow and shrink until it is done."""
|
|
69
|
+
self._timer = self.set_interval(INTERVAL, self._tick)
|
|
70
|
+
|
|
71
|
+
def _tick(self) -> None:
|
|
72
|
+
"""The next frame of the animation."""
|
|
73
|
+
self.step += 1
|
|
74
|
+
self.refresh()
|
|
75
|
+
|
|
76
|
+
def render(self) -> str:
|
|
77
|
+
summary = summarize(self.args)
|
|
78
|
+
title = f"[bold]Tool: {literal(self.tool)}[/bold]" + (f" ({literal(summary)})" if summary else "")
|
|
79
|
+
if not self.text:
|
|
80
|
+
return f"{title} [dim]{dots(self.step)}[/dim]"
|
|
81
|
+
mark = "[red]✗[/red]" if self.is_error else "[green]✓[/green]"
|
|
82
|
+
lines = [f"{title} {mark} {self.duration * 1000:.0f}ms"]
|
|
83
|
+
if self.diff:
|
|
84
|
+
lines.append(colorize_diff(self.diff))
|
|
85
|
+
else:
|
|
86
|
+
lines.append(f"[dim]{literal(_fold(self.text))}[/dim]")
|
|
87
|
+
return "\n".join(lines)
|
|
88
|
+
|
|
89
|
+
def start(self) -> None:
|
|
90
|
+
"""The tool is running."""
|
|
91
|
+
self.started = time.time()
|
|
92
|
+
self.refresh()
|
|
93
|
+
|
|
94
|
+
def finish(self, content: str, is_error: bool = False, diff: str = "") -> None:
|
|
95
|
+
"""The tool is done."""
|
|
96
|
+
if self._timer is not None:
|
|
97
|
+
self._timer.stop()
|
|
98
|
+
self._timer = None
|
|
99
|
+
"""The dots have nothing left to say."""
|
|
100
|
+
self.duration = time.time() - self.started
|
|
101
|
+
self.content = content
|
|
102
|
+
self.is_error = is_error
|
|
103
|
+
self.diff = diff
|
|
104
|
+
self.refresh()
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""The dots that say the agent is still working."""
|
|
2
|
+
|
|
3
|
+
from textual.widgets import Static
|
|
4
|
+
|
|
5
|
+
from coderagent.ui.spinner import INTERVAL, dots
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class WorkingDots(Static):
|
|
9
|
+
"""The sign that the agent has not answered yet."""
|
|
10
|
+
|
|
11
|
+
DEFAULT_CSS = """
|
|
12
|
+
WorkingDots {
|
|
13
|
+
height: auto;
|
|
14
|
+
margin: 1 0 0 0;
|
|
15
|
+
padding: 0 1;
|
|
16
|
+
}
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def on_mount(self) -> None:
|
|
20
|
+
self.step = 0
|
|
21
|
+
self._timer = self.set_interval(INTERVAL, self._tick)
|
|
22
|
+
|
|
23
|
+
def _tick(self) -> None:
|
|
24
|
+
"""The next frame of the animation."""
|
|
25
|
+
self.step += 1
|
|
26
|
+
self.update(f"[dim]{dots(self.step)}[/dim]")
|
coderagent/version.py
ADDED
coderagent/web/api.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""The HTTP API of the web interface.
|
|
2
|
+
|
|
3
|
+
The pages are thin: everything they show comes from here. The events of a
|
|
4
|
+
session are pushed over SSE, everything else is a plain request and answer.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import json
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request
|
|
13
|
+
from fastapi.responses import StreamingResponse
|
|
14
|
+
from pydantic import BaseModel, ValidationError
|
|
15
|
+
|
|
16
|
+
from coderagent.config import writer
|
|
17
|
+
from coderagent.config.loader import problems
|
|
18
|
+
from coderagent.core.checkpoint import CheckpointStore
|
|
19
|
+
from coderagent.core.content import check_image
|
|
20
|
+
from coderagent.core.session import session_priced
|
|
21
|
+
from coderagent.core.subagent import effective_turns, load_subagents
|
|
22
|
+
from coderagent.core.telemetry import collect
|
|
23
|
+
from coderagent.models import check, settings
|
|
24
|
+
from coderagent.models.backends import priced_name
|
|
25
|
+
from coderagent.tools.permissions import ApprovalDecision, PermissionMode
|
|
26
|
+
from coderagent.ui.commands import COMMANDS, load_builtins
|
|
27
|
+
from coderagent.ui.widgets.diff_view import make_diff
|
|
28
|
+
from coderagent.web import config_api, files
|
|
29
|
+
from coderagent.web.events import normalize
|
|
30
|
+
from coderagent.web.sessions import SessionBusy, SessionRuntime
|
|
31
|
+
|
|
32
|
+
router = APIRouter(prefix="/api")
|
|
33
|
+
|
|
34
|
+
KEEP_ALIVE = 15
|
|
35
|
+
"""Seconds between two keep-alives of the event stream."""
|
|
36
|
+
|
|
37
|
+
STREAM_ENDS = ("turn_end", "command_end")
|
|
38
|
+
"""The items that close the event stream; the browser opens a new one."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class MessageBody(BaseModel):
|
|
42
|
+
text: str
|
|
43
|
+
images: list[str] = []
|
|
44
|
+
"""The images of the message, as the data urls a provider takes."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ApprovalBody(BaseModel):
|
|
48
|
+
decision: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def require_client(x_coder_client: str = Header(default="")) -> None:
|
|
52
|
+
"""The write requests need a header a browser on another site cannot send.
|
|
53
|
+
|
|
54
|
+
The header makes the browser ask for a permission first, and no permission
|
|
55
|
+
is granted, so a page somewhere else cannot drive the agent.
|
|
56
|
+
"""
|
|
57
|
+
if x_coder_client != "1":
|
|
58
|
+
raise HTTPException(status_code=403, detail="the X-Coder-Client header is missing")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _runtime(request: Request, session_id: str) -> SessionRuntime:
|
|
62
|
+
"""The runtime of a session. A session of the log that has no runtime gets one."""
|
|
63
|
+
registry = request.app.state.registry
|
|
64
|
+
runtime = registry.get(session_id)
|
|
65
|
+
if runtime is not None:
|
|
66
|
+
return runtime
|
|
67
|
+
session = registry.store.rebuild(session_id)
|
|
68
|
+
if not session.created_at:
|
|
69
|
+
raise HTTPException(status_code=404, detail=f"there is no session with the id {session_id}")
|
|
70
|
+
return registry.create(session)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _config(request: Request):
|
|
74
|
+
"""The configuration as it is now."""
|
|
75
|
+
return request.app.state.config_of()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _server_mode(request: Request) -> str:
|
|
79
|
+
"""The mode the server was started with, empty when it was not pinned."""
|
|
80
|
+
return request.app.state.registry.permission_mode or ""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# -- the sessions --------------------------------------------------------
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@router.get("/sessions")
|
|
87
|
+
def list_sessions(request: Request, cwd: str = "") -> dict[str, Any]:
|
|
88
|
+
"""The sessions of a directory, newest first."""
|
|
89
|
+
directory = Path(cwd) if cwd else request.app.state.cwd
|
|
90
|
+
sessions = request.app.state.registry.store.list(directory)
|
|
91
|
+
model = _config(request).model
|
|
92
|
+
"""A session that has not called a model yet belongs to the model of the server."""
|
|
93
|
+
name = priced_name(model.model_name, model.litellm_config)
|
|
94
|
+
return {
|
|
95
|
+
"sessions": [
|
|
96
|
+
{
|
|
97
|
+
"id": session.id,
|
|
98
|
+
"name": session.name,
|
|
99
|
+
"title": session.name or session.summary or session.id,
|
|
100
|
+
"archived": session.archived,
|
|
101
|
+
"cwd": str(session.cwd),
|
|
102
|
+
"created_at": session.created_at,
|
|
103
|
+
"updated_at": session.updated_at,
|
|
104
|
+
"turns": session.turn_count,
|
|
105
|
+
"cost": session.total_cost,
|
|
106
|
+
"priced": session_priced(session, name),
|
|
107
|
+
"state": session.state.value,
|
|
108
|
+
}
|
|
109
|
+
for session in sessions
|
|
110
|
+
]
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@router.post("/sessions", status_code=201)
|
|
115
|
+
def create_session(request: Request) -> dict[str, Any]:
|
|
116
|
+
"""Start a new session."""
|
|
117
|
+
runtime = request.app.state.registry.create()
|
|
118
|
+
return {"id": runtime.session.id, "cwd": str(runtime.cwd)}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@router.get("/sessions/{session_id}")
|
|
122
|
+
def get_session(session_id: str, request: Request) -> dict[str, Any]:
|
|
123
|
+
runtime = _runtime(request, session_id)
|
|
124
|
+
session = runtime.session
|
|
125
|
+
model = _config(request).model
|
|
126
|
+
return {
|
|
127
|
+
"id": session.id,
|
|
128
|
+
"cwd": str(session.cwd),
|
|
129
|
+
"created_at": session.created_at,
|
|
130
|
+
"updated_at": session.updated_at,
|
|
131
|
+
"turns": session.turn_count,
|
|
132
|
+
"cost": session.total_cost,
|
|
133
|
+
"priced": session_priced(session, priced_name(model.model_name, model.litellm_config)),
|
|
134
|
+
"state": session.state.value,
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@router.get("/sessions/{session_id}/events")
|
|
139
|
+
def replay(session_id: str, request: Request) -> dict[str, Any]:
|
|
140
|
+
"""The whole session, read from the event log."""
|
|
141
|
+
runtime = _runtime(request, session_id)
|
|
142
|
+
items: list[dict] = []
|
|
143
|
+
for event in runtime.store.events(session_id):
|
|
144
|
+
items.extend(normalize(event))
|
|
145
|
+
return {"items": items}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@router.get("/sessions/{session_id}/items")
|
|
149
|
+
def items(session_id: str, request: Request, since: int = 0) -> dict[str, Any]:
|
|
150
|
+
"""The items of the session that the browser has not seen yet."""
|
|
151
|
+
runtime = _runtime(request, session_id)
|
|
152
|
+
return {"items": runtime.items(since)}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@router.get("/sessions/{session_id}/stream")
|
|
156
|
+
async def stream(session_id: str, request: Request, since: int = 0) -> StreamingResponse:
|
|
157
|
+
"""The events of the session, as they happen."""
|
|
158
|
+
runtime = _runtime(request, session_id)
|
|
159
|
+
queue: asyncio.Queue = asyncio.Queue()
|
|
160
|
+
loop = asyncio.get_running_loop()
|
|
161
|
+
runtime.attach(loop, queue, since)
|
|
162
|
+
|
|
163
|
+
async def events():
|
|
164
|
+
try:
|
|
165
|
+
while True:
|
|
166
|
+
try:
|
|
167
|
+
item = await asyncio.wait_for(queue.get(), timeout=KEEP_ALIVE)
|
|
168
|
+
except asyncio.TimeoutError:
|
|
169
|
+
yield ": keep-alive\n\n"
|
|
170
|
+
continue
|
|
171
|
+
if item.get("kind") == "stream_end":
|
|
172
|
+
"""The server is stopping: the stream ends here."""
|
|
173
|
+
break
|
|
174
|
+
yield f"data: {json.dumps(item, ensure_ascii=False)}\n\n"
|
|
175
|
+
if item.get("kind") in STREAM_ENDS:
|
|
176
|
+
break
|
|
177
|
+
finally:
|
|
178
|
+
runtime.detach(queue)
|
|
179
|
+
|
|
180
|
+
return StreamingResponse(events(), media_type="text/event-stream")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@router.get("/sessions/{session_id}/status")
|
|
184
|
+
def status(session_id: str, request: Request) -> dict[str, Any]:
|
|
185
|
+
runtime = _runtime(request, session_id)
|
|
186
|
+
return runtime.status()
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@router.get("/sessions/{session_id}/metrics")
|
|
190
|
+
def metrics(session_id: str, request: Request) -> dict[str, Any]:
|
|
191
|
+
runtime = _runtime(request, session_id)
|
|
192
|
+
return collect(runtime.store.events(session_id)).to_dict()
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@router.get("/sessions/{session_id}/changes")
|
|
196
|
+
def changes(session_id: str, request: Request) -> dict[str, Any]:
|
|
197
|
+
"""The files this session changed, with the diff of the change."""
|
|
198
|
+
runtime = _runtime(request, session_id)
|
|
199
|
+
config = _config(request)
|
|
200
|
+
store = CheckpointStore(keep=config.checkpoint.keep)
|
|
201
|
+
seen: dict[str, str] = {}
|
|
202
|
+
for checkpoint in store.all(session_id):
|
|
203
|
+
for name, before in checkpoint.payload.items():
|
|
204
|
+
seen.setdefault(name, before or "")
|
|
205
|
+
result = []
|
|
206
|
+
for name, before in seen.items():
|
|
207
|
+
path = runtime.cwd / name
|
|
208
|
+
after = path.read_text(encoding="utf-8", errors="replace") if path.exists() else ""
|
|
209
|
+
result.append({"path": name, "diff": make_diff(before, after, name)})
|
|
210
|
+
return {"changes": result}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@router.post("/sessions/{session_id}/resume")
|
|
214
|
+
def resume(session_id: str, request: Request) -> dict[str, Any]:
|
|
215
|
+
"""Continue a session of the log."""
|
|
216
|
+
runtime = _runtime(request, session_id)
|
|
217
|
+
session = runtime.resume()
|
|
218
|
+
return {"id": session.id}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@router.post("/sessions/{session_id}/fork")
|
|
222
|
+
def fork(session_id: str, request: Request) -> dict[str, Any]:
|
|
223
|
+
"""Copy a session into a new one."""
|
|
224
|
+
runtime = _runtime(request, session_id)
|
|
225
|
+
forked = runtime.store.fork(session_id)
|
|
226
|
+
new_runtime = request.app.state.registry.create(forked)
|
|
227
|
+
return {"id": new_runtime.session.id, "forked_from": session_id}
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
@router.post("/sessions/{session_id}/messages", status_code=202)
|
|
231
|
+
def send_message(session_id: str, body: MessageBody, request: Request, _: None = Depends(require_client)) -> dict:
|
|
232
|
+
"""Send a message, with the images that go with it, or run a slash command."""
|
|
233
|
+
runtime = _runtime(request, session_id)
|
|
234
|
+
text = body.text.strip()
|
|
235
|
+
images = []
|
|
236
|
+
for url in body.images:
|
|
237
|
+
try:
|
|
238
|
+
images.append(check_image(url))
|
|
239
|
+
except ValueError as error:
|
|
240
|
+
raise HTTPException(status_code=400, detail=str(error))
|
|
241
|
+
if not text and not images:
|
|
242
|
+
raise HTTPException(status_code=400, detail="the message is empty")
|
|
243
|
+
try:
|
|
244
|
+
runtime.submit(text, images=images)
|
|
245
|
+
except SessionBusy as error:
|
|
246
|
+
raise HTTPException(status_code=409, detail=str(error))
|
|
247
|
+
return {"accepted": True, "session_id": runtime.session.id}
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@router.post("/sessions/{session_id}/review", status_code=202)
|
|
251
|
+
def review(session_id: str, request: Request, _: None = Depends(require_client)) -> dict:
|
|
252
|
+
"""Review the changes of the project.
|
|
253
|
+
|
|
254
|
+
The diff goes into the prompt of a turn of its own, and the answer comes
|
|
255
|
+
back in the stream of the session.
|
|
256
|
+
"""
|
|
257
|
+
runtime = _runtime(request, session_id)
|
|
258
|
+
try:
|
|
259
|
+
result = runtime.review()
|
|
260
|
+
except SessionBusy as error:
|
|
261
|
+
raise HTTPException(status_code=409, detail=str(error))
|
|
262
|
+
if "error" in result:
|
|
263
|
+
raise HTTPException(status_code=400, detail=result["error"])
|
|
264
|
+
return {"accepted": True, **result}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
@router.post("/sessions/{session_id}/interrupt")
|
|
268
|
+
def interrupt(session_id: str, request: Request, _: None = Depends(require_client)) -> dict[str, Any]:
|
|
269
|
+
"""Stop the turn that is running."""
|
|
270
|
+
runtime = _runtime(request, session_id)
|
|
271
|
+
runtime.interrupt()
|
|
272
|
+
return {"ok": True}
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
@router.post("/sessions/{session_id}/mode")
|
|
276
|
+
def set_mode(session_id: str, body: dict, request: Request, _: None = Depends(require_client)) -> dict:
|
|
277
|
+
"""Change the permission mode of a session while it runs."""
|
|
278
|
+
runtime = _runtime(request, session_id)
|
|
279
|
+
value = str(body.get("mode") or "")
|
|
280
|
+
try:
|
|
281
|
+
mode = PermissionMode(value)
|
|
282
|
+
except ValueError:
|
|
283
|
+
raise HTTPException(status_code=400, detail=f"unknown permission mode '{value}'")
|
|
284
|
+
if mode is PermissionMode.BYPASS and not body.get("confirm"):
|
|
285
|
+
"""Bypass takes the guards off: the browser has to say that it is meant."""
|
|
286
|
+
raise HTTPException(status_code=400, detail="bypass mode needs a confirmation")
|
|
287
|
+
runtime.set_mode(mode)
|
|
288
|
+
return {"ok": True, "mode": mode.value}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
# -- the approvals --------------------------------------------------------
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
@router.post("/approvals/{approval_id}")
|
|
295
|
+
def answer_approval(
|
|
296
|
+
approval_id: str, body: ApprovalBody, request: Request, _: None = Depends(require_client)
|
|
297
|
+
) -> dict[str, Any]:
|
|
298
|
+
"""Let a tool run, or not."""
|
|
299
|
+
decision = {"allow": ApprovalDecision.ALLOW, "deny": ApprovalDecision.DENY, "always": ApprovalDecision.ALWAYS}
|
|
300
|
+
if body.decision not in decision:
|
|
301
|
+
raise HTTPException(status_code=400, detail="the decision must be allow, deny or always")
|
|
302
|
+
for runtime in request.app.state.registry.runtimes():
|
|
303
|
+
if runtime.approver.answer(approval_id, decision[body.decision]):
|
|
304
|
+
return {"ok": True, "decision": body.decision}
|
|
305
|
+
raise HTTPException(status_code=404, detail=f"no approval is waiting for the id {approval_id}")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# -- the commands ---------------------------------------------------------
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
@router.get("/commands")
|
|
312
|
+
def commands() -> dict[str, Any]:
|
|
313
|
+
"""The slash commands the user can type."""
|
|
314
|
+
load_builtins()
|
|
315
|
+
return {
|
|
316
|
+
"commands": [
|
|
317
|
+
{
|
|
318
|
+
"name": command.name,
|
|
319
|
+
"description": command.description,
|
|
320
|
+
"aliases": command.aliases,
|
|
321
|
+
"usage": command.usage,
|
|
322
|
+
}
|
|
323
|
+
for command in COMMANDS
|
|
324
|
+
]
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
@router.get("/agents")
|
|
329
|
+
def agents(request: Request) -> dict[str, Any]:
|
|
330
|
+
"""The sub agents, with the turns they may really make.
|
|
331
|
+
|
|
332
|
+
The turns of a sub agent are its own, but the ceiling of the configuration
|
|
333
|
+
holds them down. The number here is the one that counts.
|
|
334
|
+
"""
|
|
335
|
+
ceiling = _config(request).agent.subagent_max_turns
|
|
336
|
+
specs = load_subagents(request.app.state.cwd)
|
|
337
|
+
return {
|
|
338
|
+
"ceiling": ceiling,
|
|
339
|
+
"agents": [
|
|
340
|
+
{
|
|
341
|
+
"name": spec.name,
|
|
342
|
+
"description": spec.description,
|
|
343
|
+
"tools": spec.tools,
|
|
344
|
+
"purpose": spec.model_purpose,
|
|
345
|
+
"turns": effective_turns(spec, ceiling),
|
|
346
|
+
}
|
|
347
|
+
for spec in specs.values()
|
|
348
|
+
],
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
# -- the configuration -----------------------------------------------------
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
@router.get("/config")
|
|
356
|
+
def get_config(request: Request) -> dict[str, Any]:
|
|
357
|
+
"""The model and the permission configuration, as the settings page sees them."""
|
|
358
|
+
cwd = request.app.state.cwd
|
|
359
|
+
try:
|
|
360
|
+
return {
|
|
361
|
+
"model": settings.model_view(cwd),
|
|
362
|
+
"permissions": config_api.permissions_view(cwd, server_mode=_server_mode(request)),
|
|
363
|
+
"user_config_path": str(writer.user_config_path()),
|
|
364
|
+
}
|
|
365
|
+
except ValidationError as error:
|
|
366
|
+
"""A configuration that is not understood is the fault of the user, not of the server."""
|
|
367
|
+
raise HTTPException(status_code=400, detail=problems(error)) from None
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
@router.put("/config/model")
|
|
371
|
+
def put_config(body: dict, request: Request, _: None = Depends(require_client)) -> dict[str, Any]:
|
|
372
|
+
"""Write the model settings to the user level configuration file."""
|
|
373
|
+
try:
|
|
374
|
+
path = writer.write_user_model(body)
|
|
375
|
+
except ValueError as error:
|
|
376
|
+
raise HTTPException(status_code=400, detail=str(error))
|
|
377
|
+
return {"ok": True, "path": str(path), "model": settings.model_view(request.app.state.cwd)}
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
@router.get("/config/model/key")
|
|
381
|
+
def get_config_key(request: Request, _: None = Depends(require_client)) -> dict[str, Any]:
|
|
382
|
+
"""The key of the model, so that it can be read in the settings page."""
|
|
383
|
+
return {"api_key": settings.effective_api_key(request.app.state.cwd)}
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
@router.put("/config/permissions")
|
|
387
|
+
def put_permissions(body: dict, request: Request, _: None = Depends(require_client)) -> dict[str, Any]:
|
|
388
|
+
"""Write the permission settings to the user level configuration file."""
|
|
389
|
+
try:
|
|
390
|
+
path = writer.write_user_permissions(body)
|
|
391
|
+
except ValueError as error:
|
|
392
|
+
raise HTTPException(status_code=400, detail=str(error))
|
|
393
|
+
return {
|
|
394
|
+
"ok": True,
|
|
395
|
+
"path": str(path),
|
|
396
|
+
"permissions": config_api.permissions_view(request.app.state.cwd, server_mode=_server_mode(request)),
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
@router.post("/config/model/test")
|
|
401
|
+
def check_model(body: dict, request: Request, _: None = Depends(require_client)) -> dict[str, Any]:
|
|
402
|
+
"""Try the model out, to see whether the settings work."""
|
|
403
|
+
return check.test_connection(settings.effective_model(request.app.state.cwd, body))
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
# -- the files -------------------------------------------------------------
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
@router.get("/files")
|
|
410
|
+
def list_files(request: Request, path: str = "", depth: int = Query(1, ge=-1, le=10)) -> dict[str, Any]:
|
|
411
|
+
"""The entries of a directory that the browser may list.
|
|
412
|
+
|
|
413
|
+
Only the directories that the user opened to the agent are listed.
|
|
414
|
+
"""
|
|
415
|
+
cwd = request.app.state.cwd
|
|
416
|
+
policy = files.policy_for(_config(request), cwd)
|
|
417
|
+
try:
|
|
418
|
+
listed, entries = files.listing(cwd, path, depth, policy)
|
|
419
|
+
except files.OutsideBounds as error:
|
|
420
|
+
raise HTTPException(status_code=403, detail=str(error))
|
|
421
|
+
except (NotADirectoryError, OSError) as error:
|
|
422
|
+
raise HTTPException(status_code=400, detail=str(error))
|
|
423
|
+
return {"path": listed, "entries": entries}
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@router.get("/file")
|
|
427
|
+
def read_file(path: str, request: Request) -> dict[str, Any]:
|
|
428
|
+
"""The content of a file of the working directory."""
|
|
429
|
+
cwd = request.app.state.cwd
|
|
430
|
+
policy = files.policy_for(_config(request), cwd)
|
|
431
|
+
try:
|
|
432
|
+
return files.read(cwd, path, policy, _config(request))
|
|
433
|
+
except files.OutsideBounds as error:
|
|
434
|
+
raise HTTPException(status_code=403, detail=str(error))
|
|
435
|
+
except OSError as error:
|
|
436
|
+
raise HTTPException(status_code=400, detail=str(error))
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
@router.get("/diff")
|
|
440
|
+
def diff(path: str, request: Request) -> dict[str, Any]:
|
|
441
|
+
"""The changes of the working tree for a path."""
|
|
442
|
+
cwd = request.app.state.cwd
|
|
443
|
+
policy = files.policy_for(_config(request), cwd)
|
|
444
|
+
try:
|
|
445
|
+
return {"path": path, "diff": files.diff(cwd, path, policy)}
|
|
446
|
+
except files.OutsideBounds as error:
|
|
447
|
+
raise HTTPException(status_code=403, detail=str(error))
|
|
448
|
+
except OSError as error:
|
|
449
|
+
raise HTTPException(status_code=400, detail=str(error))
|