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.
Files changed (163) hide show
  1. coder_agent-0.1.0.dist-info/METADATA +262 -0
  2. coder_agent-0.1.0.dist-info/RECORD +163 -0
  3. coder_agent-0.1.0.dist-info/WHEEL +5 -0
  4. coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
  5. coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
  6. coder_agent-0.1.0.dist-info/top_level.txt +1 -0
  7. coderagent/__init__.py +20 -0
  8. coderagent/compat/__init__.py +27 -0
  9. coderagent/compat/cache_control.py +69 -0
  10. coderagent/compat/config_spec.py +60 -0
  11. coderagent/compat/exceptions.py +20 -0
  12. coderagent/compat/retry.py +27 -0
  13. coderagent/compat/serialize.py +31 -0
  14. coderagent/config/__init__.py +1 -0
  15. coderagent/config/defaults.yaml +103 -0
  16. coderagent/config/loader.py +264 -0
  17. coderagent/config/schema.py +548 -0
  18. coderagent/config/writer.py +218 -0
  19. coderagent/core/__init__.py +1 -0
  20. coderagent/core/budget.py +47 -0
  21. coderagent/core/capabilities.py +136 -0
  22. coderagent/core/checkpoint.py +164 -0
  23. coderagent/core/content.py +156 -0
  24. coderagent/core/context.py +618 -0
  25. coderagent/core/events.py +83 -0
  26. coderagent/core/history.py +56 -0
  27. coderagent/core/instructions.py +99 -0
  28. coderagent/core/loop.py +702 -0
  29. coderagent/core/memory.py +56 -0
  30. coderagent/core/mentions.py +81 -0
  31. coderagent/core/os_sandbox.py +191 -0
  32. coderagent/core/otel.py +214 -0
  33. coderagent/core/protocols.py +38 -0
  34. coderagent/core/redact.py +49 -0
  35. coderagent/core/sandbox.py +82 -0
  36. coderagent/core/schema.py +107 -0
  37. coderagent/core/session.py +344 -0
  38. coderagent/core/shell_env.py +74 -0
  39. coderagent/core/subagent.py +474 -0
  40. coderagent/core/summarize.py +312 -0
  41. coderagent/core/telemetry.py +209 -0
  42. coderagent/core/tokens.py +132 -0
  43. coderagent/core/trust.py +301 -0
  44. coderagent/environments/__init__.py +11 -0
  45. coderagent/environments/bubblewrap.py +150 -0
  46. coderagent/environments/contree.py +146 -0
  47. coderagent/environments/docker.py +160 -0
  48. coderagent/environments/local.py +110 -0
  49. coderagent/environments/singularity.py +138 -0
  50. coderagent/environments/swerex_docker.py +79 -0
  51. coderagent/environments/swerex_modal.py +123 -0
  52. coderagent/eval/__init__.py +1 -0
  53. coderagent/eval/compare.py +190 -0
  54. coderagent/eval/report.py +141 -0
  55. coderagent/eval/runner.py +368 -0
  56. coderagent/eval/task.py +194 -0
  57. coderagent/extensions/__init__.py +1 -0
  58. coderagent/extensions/hooks.py +121 -0
  59. coderagent/extensions/plugins.py +217 -0
  60. coderagent/extensions/reflect.py +342 -0
  61. coderagent/models/__init__.py +33 -0
  62. coderagent/models/backends.py +218 -0
  63. coderagent/models/call.py +18 -0
  64. coderagent/models/check.py +139 -0
  65. coderagent/models/gateway.py +60 -0
  66. coderagent/models/litellm_config.py +70 -0
  67. coderagent/models/provider.py +98 -0
  68. coderagent/models/reasoning.py +28 -0
  69. coderagent/models/router.py +136 -0
  70. coderagent/models/settings.py +172 -0
  71. coderagent/models/streaming.py +122 -0
  72. coderagent/models/verbosity.py +14 -0
  73. coderagent/paths.py +31 -0
  74. coderagent/run.py +454 -0
  75. coderagent/skills/__init__.py +119 -0
  76. coderagent/skills/errors.py +11 -0
  77. coderagent/skills/install.py +340 -0
  78. coderagent/skills/presets/code-review/SKILL.md +35 -0
  79. coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
  80. coderagent/skills/presets/data-analysis/SKILL.md +35 -0
  81. coderagent/skills/presets/deep-research/SKILL.md +38 -0
  82. coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
  83. coderagent/skills/presets/long-document/SKILL.md +37 -0
  84. coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
  85. coderagent/skills/presets/office-docx/SKILL.md +36 -0
  86. coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
  87. coderagent/skills/presets/office-pptx/SKILL.md +32 -0
  88. coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
  89. coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
  90. coderagent/skills/presets/writing/SKILL.md +31 -0
  91. coderagent/skills/sandbox.py +269 -0
  92. coderagent/skills/sites.py +177 -0
  93. coderagent/skills/source.py +404 -0
  94. coderagent/testing/__init__.py +5 -0
  95. coderagent/testing/factory.py +59 -0
  96. coderagent/testing/scripted_model.py +54 -0
  97. coderagent/tools/__init__.py +1 -0
  98. coderagent/tools/base.py +54 -0
  99. coderagent/tools/bash_policy.py +486 -0
  100. coderagent/tools/builtin/__init__.py +35 -0
  101. coderagent/tools/builtin/fs.py +283 -0
  102. coderagent/tools/builtin/patch.py +279 -0
  103. coderagent/tools/builtin/search.py +242 -0
  104. coderagent/tools/builtin/shell.py +336 -0
  105. coderagent/tools/builtin/skill.py +41 -0
  106. coderagent/tools/builtin/task.py +53 -0
  107. coderagent/tools/builtin/todo.py +63 -0
  108. coderagent/tools/executor.py +243 -0
  109. coderagent/tools/mcp.py +317 -0
  110. coderagent/tools/permissions.py +472 -0
  111. coderagent/tools/registry.py +83 -0
  112. coderagent/tools/rules.py +138 -0
  113. coderagent/ui/__init__.py +1 -0
  114. coderagent/ui/cli.py +498 -0
  115. coderagent/ui/commands/__init__.py +109 -0
  116. coderagent/ui/commands/builtin.py +778 -0
  117. coderagent/ui/commands/compact.py +12 -0
  118. coderagent/ui/commands/resume.py +26 -0
  119. coderagent/ui/commands/review.py +73 -0
  120. coderagent/ui/commands/rewind.py +28 -0
  121. coderagent/ui/custom_commands.py +179 -0
  122. coderagent/ui/notify.py +46 -0
  123. coderagent/ui/open_file.py +48 -0
  124. coderagent/ui/render.py +62 -0
  125. coderagent/ui/spinner.py +68 -0
  126. coderagent/ui/tui.py +610 -0
  127. coderagent/ui/widgets/__init__.py +29 -0
  128. coderagent/ui/widgets/approval_prompt.py +129 -0
  129. coderagent/ui/widgets/diff_view.py +97 -0
  130. coderagent/ui/widgets/file_tree.py +105 -0
  131. coderagent/ui/widgets/markdown_message.py +44 -0
  132. coderagent/ui/widgets/markup.py +10 -0
  133. coderagent/ui/widgets/message_block.py +61 -0
  134. coderagent/ui/widgets/path_suggester.py +66 -0
  135. coderagent/ui/widgets/session_picker.py +49 -0
  136. coderagent/ui/widgets/status_bar.py +44 -0
  137. coderagent/ui/widgets/todo_panel.py +40 -0
  138. coderagent/ui/widgets/tool_card.py +104 -0
  139. coderagent/ui/widgets/working_dots.py +26 -0
  140. coderagent/version.py +7 -0
  141. coderagent/web/__init__.py +5 -0
  142. coderagent/web/api.py +449 -0
  143. coderagent/web/app.py +113 -0
  144. coderagent/web/approver.py +73 -0
  145. coderagent/web/config_api.py +53 -0
  146. coderagent/web/events.py +159 -0
  147. coderagent/web/files.py +115 -0
  148. coderagent/web/i18n.py +346 -0
  149. coderagent/web/server.py +100 -0
  150. coderagent/web/sessions.py +404 -0
  151. coderagent/web/skills_api.py +376 -0
  152. coderagent/web/static/app.css +283 -0
  153. coderagent/web/static/app.js +1466 -0
  154. coderagent/web/templates/en/base.html +31 -0
  155. coderagent/web/templates/en/chat.html +60 -0
  156. coderagent/web/templates/en/macros.html +9 -0
  157. coderagent/web/templates/en/settings.html +80 -0
  158. coderagent/web/templates/en/skills.html +64 -0
  159. coderagent/web/templates/zh/base.html +31 -0
  160. coderagent/web/templates/zh/chat.html +60 -0
  161. coderagent/web/templates/zh/macros.html +9 -0
  162. coderagent/web/templates/zh/settings.html +77 -0
  163. 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
@@ -0,0 +1,7 @@
1
+ """The version of the coding agent.
2
+
3
+ It lives in a module of its own: the build reads it without importing the
4
+ package, and the package imports it without pulling the world in.
5
+ """
6
+
7
+ __version__ = "0.1.0"
@@ -0,0 +1,5 @@
1
+ """The web interface of the coding agent: FastAPI, SSE and a browser UI.
2
+
3
+ Nothing here imports FastAPI or uvicorn at module level: `coderagent.web` is
4
+ importable on its own, and the server is only pulled in by `coder web`.
5
+ """
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))