braid-coding-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 (192) hide show
  1. braid_coding_agent/__init__.py +13 -0
  2. braid_coding_agent/assembly.py +460 -0
  3. braid_coding_agent/cancellation.py +25 -0
  4. braid_coding_agent/checkpoint/__init__.py +106 -0
  5. braid_coding_agent/checkpoint/git.py +305 -0
  6. braid_coding_agent/checkpoint/settings.py +26 -0
  7. braid_coding_agent/checkpoint/store.py +1261 -0
  8. braid_coding_agent/checkpoint/workspace.py +220 -0
  9. braid_coding_agent/cli.py +2168 -0
  10. braid_coding_agent/commands/__init__.py +50 -0
  11. braid_coding_agent/commands/auth.py +161 -0
  12. braid_coding_agent/commands/config.py +180 -0
  13. braid_coding_agent/commands/doctor.py +511 -0
  14. braid_coding_agent/commands/mcp.py +928 -0
  15. braid_coding_agent/commands/models.py +95 -0
  16. braid_coding_agent/commands/setup.py +89 -0
  17. braid_coding_agent/commands/uninstall.py +277 -0
  18. braid_coding_agent/commands/upgrade.py +381 -0
  19. braid_coding_agent/compaction/__init__.py +174 -0
  20. braid_coding_agent/compaction/prepare.py +430 -0
  21. braid_coding_agent/compaction/summarize.py +542 -0
  22. braid_coding_agent/compaction/tokens.py +204 -0
  23. braid_coding_agent/compaction/tool_results.py +196 -0
  24. braid_coding_agent/compaction/utils.py +181 -0
  25. braid_coding_agent/config.py +2776 -0
  26. braid_coding_agent/config_files.py +191 -0
  27. braid_coding_agent/credentials.py +252 -0
  28. braid_coding_agent/discovery.py +415 -0
  29. braid_coding_agent/extensions/__init__.py +77 -0
  30. braid_coding_agent/extensions/api.py +480 -0
  31. braid_coding_agent/extensions/runner.py +553 -0
  32. braid_coding_agent/formatting/__init__.py +62 -0
  33. braid_coding_agent/formatting/settings.py +87 -0
  34. braid_coding_agent/formatting/tool.py +179 -0
  35. braid_coding_agent/lsp/__init__.py +105 -0
  36. braid_coding_agent/lsp/client.py +546 -0
  37. braid_coding_agent/lsp/manager.py +187 -0
  38. braid_coding_agent/lsp/model.py +316 -0
  39. braid_coding_agent/lsp/protocol.py +105 -0
  40. braid_coding_agent/lsp/settings.py +120 -0
  41. braid_coding_agent/lsp/tool.py +429 -0
  42. braid_coding_agent/mcp/__init__.py +101 -0
  43. braid_coding_agent/mcp/cache.py +230 -0
  44. braid_coding_agent/mcp/catalog.py +108 -0
  45. braid_coding_agent/mcp/config.py +664 -0
  46. braid_coding_agent/mcp/config_store.py +142 -0
  47. braid_coding_agent/mcp/inspector.py +85 -0
  48. braid_coding_agent/mcp/panel.py +254 -0
  49. braid_coding_agent/mcp/runtime.py +1060 -0
  50. braid_coding_agent/mcp/tools.py +579 -0
  51. braid_coding_agent/mcp/trust.py +150 -0
  52. braid_coding_agent/mcp/tui_panel.py +444 -0
  53. braid_coding_agent/messages.py +152 -0
  54. braid_coding_agent/models_view.py +105 -0
  55. braid_coding_agent/modes/__init__.py +64 -0
  56. braid_coding_agent/modes/json_mode.py +480 -0
  57. braid_coding_agent/modes/lifecycle.py +217 -0
  58. braid_coding_agent/modes/print_mode.py +257 -0
  59. braid_coding_agent/modes/repl.py +2687 -0
  60. braid_coding_agent/modes/repl_commands.py +263 -0
  61. braid_coding_agent/modes/rpc.py +953 -0
  62. braid_coding_agent/modes/skill_commands.py +88 -0
  63. braid_coding_agent/modes/tui.py +2226 -0
  64. braid_coding_agent/modes/tui_control.py +90 -0
  65. braid_coding_agent/modes/tui_model.py +1043 -0
  66. braid_coding_agent/modes/tui_render.py +327 -0
  67. braid_coding_agent/modes/tui_rich.py +751 -0
  68. braid_coding_agent/modes/tui_style.py +42 -0
  69. braid_coding_agent/modes/wire.py +81 -0
  70. braid_coding_agent/netsafe.py +82 -0
  71. braid_coding_agent/network/__init__.py +20 -0
  72. braid_coding_agent/network/cache.py +77 -0
  73. braid_coding_agent/network/fetch.py +311 -0
  74. braid_coding_agent/network/html_text.py +160 -0
  75. braid_coding_agent/network/search.py +347 -0
  76. braid_coding_agent/network/settings.py +103 -0
  77. braid_coding_agent/network/urls.py +89 -0
  78. braid_coding_agent/observability/__init__.py +101 -0
  79. braid_coding_agent/observability/audit.py +124 -0
  80. braid_coding_agent/observability/collector.py +314 -0
  81. braid_coding_agent/observability/exporter.py +74 -0
  82. braid_coding_agent/observability/logging_setup.py +149 -0
  83. braid_coding_agent/observability/redaction.py +96 -0
  84. braid_coding_agent/observability/settings.py +29 -0
  85. braid_coding_agent/observability/spans.py +239 -0
  86. braid_coding_agent/permissions/__init__.py +185 -0
  87. braid_coding_agent/permissions/command.py +586 -0
  88. braid_coding_agent/permissions/engine.py +522 -0
  89. braid_coding_agent/permissions/evaluate.py +309 -0
  90. braid_coding_agent/permissions/matching.py +233 -0
  91. braid_coding_agent/permissions/model.py +278 -0
  92. braid_coding_agent/permissions/policy.py +99 -0
  93. braid_coding_agent/permissions/readonly.py +236 -0
  94. braid_coding_agent/permissions/store.py +379 -0
  95. braid_coding_agent/project_init.py +313 -0
  96. braid_coding_agent/prompt/__init__.py +98 -0
  97. braid_coding_agent/prompt/context_files.py +253 -0
  98. braid_coding_agent/prompt/project_context.py +172 -0
  99. braid_coding_agent/prompt/system_prompt.py +378 -0
  100. braid_coding_agent/questions.py +71 -0
  101. braid_coding_agent/render/__init__.py +56 -0
  102. braid_coding_agent/render/batch.py +66 -0
  103. braid_coding_agent/render/history.py +143 -0
  104. braid_coding_agent/render/stream.py +823 -0
  105. braid_coding_agent/render/theme.py +243 -0
  106. braid_coding_agent/sandbox/__init__.py +89 -0
  107. braid_coding_agent/sandbox/backend.py +184 -0
  108. braid_coding_agent/sandbox/bubblewrap.py +96 -0
  109. braid_coding_agent/sandbox/operations.py +301 -0
  110. braid_coding_agent/sandbox/policy.py +221 -0
  111. braid_coding_agent/sandbox/proxy.py +320 -0
  112. braid_coding_agent/sandbox/seatbelt.py +222 -0
  113. braid_coding_agent/sdk/__init__.py +31 -0
  114. braid_coding_agent/sdk/async_client.py +366 -0
  115. braid_coding_agent/sdk/client.py +386 -0
  116. braid_coding_agent/sdk/errors.py +52 -0
  117. braid_coding_agent/sdk/events.py +162 -0
  118. braid_coding_agent/sdk/types.py +63 -0
  119. braid_coding_agent/sdk/wire.py +59 -0
  120. braid_coding_agent/server/__init__.py +54 -0
  121. braid_coding_agent/server/errors.py +52 -0
  122. braid_coding_agent/server/http_server.py +419 -0
  123. braid_coding_agent/server/hub.py +530 -0
  124. braid_coding_agent/server/openapi.py +157 -0
  125. braid_coding_agent/server/registry.py +354 -0
  126. braid_coding_agent/server/router.py +275 -0
  127. braid_coding_agent/server/run.py +148 -0
  128. braid_coding_agent/server/schema.py +194 -0
  129. braid_coding_agent/server/service.py +975 -0
  130. braid_coding_agent/session/__init__.py +293 -0
  131. braid_coding_agent/session/agent_session.py +2706 -0
  132. braid_coding_agent/session/context_breakdown.py +302 -0
  133. braid_coding_agent/session/discovery.py +212 -0
  134. braid_coding_agent/session/entries.py +809 -0
  135. braid_coding_agent/session/evidence.py +295 -0
  136. braid_coding_agent/session/lock.py +176 -0
  137. braid_coding_agent/session/manager.py +1185 -0
  138. braid_coding_agent/session/plan.py +243 -0
  139. braid_coding_agent/session/plan_mode.py +423 -0
  140. braid_coding_agent/session/projection.py +262 -0
  141. braid_coding_agent/session/rewind.py +257 -0
  142. braid_coding_agent/session/status.py +240 -0
  143. braid_coding_agent/settings.py +94 -0
  144. braid_coding_agent/skills/__init__.py +70 -0
  145. braid_coding_agent/skills/loader.py +681 -0
  146. braid_coding_agent/startup/__init__.py +76 -0
  147. braid_coding_agent/startup/cache.py +72 -0
  148. braid_coding_agent/startup/diagnostics.py +37 -0
  149. braid_coding_agent/startup/monitor.py +245 -0
  150. braid_coding_agent/startup/phases.py +79 -0
  151. braid_coding_agent/startup/project.py +165 -0
  152. braid_coding_agent/startup/report.py +560 -0
  153. braid_coding_agent/startup/scheduler.py +347 -0
  154. braid_coding_agent/statusline.py +163 -0
  155. braid_coding_agent/subagents/__init__.py +22 -0
  156. braid_coding_agent/subagents/contract.py +75 -0
  157. braid_coding_agent/subagents/definitions.py +583 -0
  158. braid_coding_agent/subagents/registry.py +277 -0
  159. braid_coding_agent/subagents/runtime.py +610 -0
  160. braid_coding_agent/subagents/settings.py +156 -0
  161. braid_coding_agent/subagents/worktree.py +63 -0
  162. braid_coding_agent/tools/__init__.py +327 -0
  163. braid_coding_agent/tools/args.py +87 -0
  164. braid_coding_agent/tools/bash.py +359 -0
  165. braid_coding_agent/tools/edit.py +298 -0
  166. braid_coding_agent/tools/edit_diff.py +344 -0
  167. braid_coding_agent/tools/find.py +158 -0
  168. braid_coding_agent/tools/grep.py +305 -0
  169. braid_coding_agent/tools/ignore.py +198 -0
  170. braid_coding_agent/tools/ls.py +127 -0
  171. braid_coding_agent/tools/mutation_queue.py +90 -0
  172. braid_coding_agent/tools/operations.py +274 -0
  173. braid_coding_agent/tools/output_accumulator.py +282 -0
  174. braid_coding_agent/tools/output_store.py +244 -0
  175. braid_coding_agent/tools/path_utils.py +91 -0
  176. braid_coding_agent/tools/plan.py +141 -0
  177. braid_coding_agent/tools/prompt_notes.py +52 -0
  178. braid_coding_agent/tools/question.py +180 -0
  179. braid_coding_agent/tools/read.py +223 -0
  180. braid_coding_agent/tools/submit_plan.py +102 -0
  181. braid_coding_agent/tools/truncate.py +423 -0
  182. braid_coding_agent/tools/write.py +100 -0
  183. braid_coding_agent/untrusted.py +50 -0
  184. braid_coding_agent/verify/__init__.py +78 -0
  185. braid_coding_agent/verify/runner.py +260 -0
  186. braid_coding_agent/verify/settings.py +64 -0
  187. braid_coding_agent/verify/tool.py +143 -0
  188. braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
  189. braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
  190. braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
  191. braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
  192. braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,975 @@
1
+ """HTTP 接口的全部处理函数与路由表。
2
+
3
+ 这个模块只做三件事:把请求折成会话操作、把结果折成 JSON、把异常折成
4
+ :class:`~braid_coding_agent.server.errors.ApiError`。它不解析 HTTP(那是
5
+ :mod:`.http_server` 的事),也不直接管理会话对象(那是 :mod:`.registry` 的事)。
6
+
7
+ ## 与会话层的关系
8
+
9
+ 每个处理函数都走 ``AgentSession`` 的公开方法:``prompt`` / ``abort`` /
10
+ ``set_model`` / ``compact`` / ``checkpoints``。没有一条路径绕过会话层直接动
11
+ ``Agent`` 或 ``SessionManager``——绕过一次,落盘、重试、压缩与事件流就会缺一块。
12
+
13
+ ## 事件流的形状
14
+
15
+ ``GET /sessions/{id}/events`` 是唯一一条非 JSON 的路由。它先发一个 ``ready``
16
+ 事件告诉客户端"从哪个序号开始",之后按会话事件原样转发。断线重连时客户端带
17
+ ``Last-Event-ID``(或 ``?since=N``),服务端从缓冲里补发;补不齐就回 409,让
18
+ 客户端重新拉状态,而不是假装补齐。
19
+
20
+ ## 错误码
21
+
22
+ | 状态 | 含义 |
23
+ |---|---|
24
+ | 400 | 请求体或查询参数不合法 |
25
+ | 401 | 缺少或错误的 Bearer Token |
26
+ | 404 | 会话、文件、挂起请求不存在 |
27
+ | 409 | 状态冲突:会话正忙、已被别的进程持有、补不齐事件 |
28
+ | 500 | 服务端内部错误,``message`` 里带原因 |
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import asyncio
34
+ import json
35
+ import os
36
+ from collections.abc import Iterator, Mapping
37
+ from dataclasses import dataclass, field
38
+ from typing import Literal
39
+
40
+ from braid_ai import Models
41
+ from braid_ai.types import ImageContent, JsonValue
42
+ from braid_coding_agent.checkpoint import CheckpointError
43
+ from braid_coding_agent.checkpoint.git import GitError
44
+ from braid_coding_agent.compaction.summarize import SummarizationError
45
+ from braid_coding_agent.mcp import McpRuntime
46
+ from braid_coding_agent.modes.json_mode import (
47
+ compaction_result_to_wire,
48
+ model_to_wire,
49
+ transcript_message_to_wire,
50
+ )
51
+ from braid_coding_agent.modes.wire import (
52
+ checkpoint_wire,
53
+ diff_wire,
54
+ mcp_status_wire,
55
+ undo_wire,
56
+ )
57
+ from braid_coding_agent.permissions.engine import APPROVAL_SCOPES
58
+ from braid_coding_agent.server.errors import ApiError, bad_request, conflict, not_found
59
+ from braid_coding_agent.server.hub import SessionHub
60
+ from braid_coding_agent.server.openapi import document
61
+ from braid_coding_agent.server.registry import SessionRegistry
62
+ from braid_coding_agent.server.router import (
63
+ Frame,
64
+ Handler,
65
+ QueryParam,
66
+ RequestContext,
67
+ Response,
68
+ Route,
69
+ Router,
70
+ SseStream,
71
+ json_response,
72
+ query_bool,
73
+ query_int,
74
+ query_str,
75
+ )
76
+ from braid_coding_agent.server.schema import SCHEMA_KEY, decode_body
77
+ from braid_coding_agent.session.status import plan_mode_wire, plan_wire, status_wire_parts
78
+ from braid_coding_agent.tools.find import find_paths
79
+ from braid_coding_agent.tools.grep import search_contents
80
+ from braid_coding_agent.tools.operations import LocalFileOperations
81
+ from braid_coding_agent.tools.path_utils import to_posix
82
+ from braid_coding_agent.tools.truncate import format_size, truncate_head
83
+
84
+ __all__ = ["Service", "create_service", "state_wire"]
85
+
86
+ #: ``/files`` 单次返回的字节上限。比工具读文件的 50KB 宽:编辑器要的是整屏内容。
87
+ FILE_MAX_BYTES = 256 * 1024
88
+ #: ``/files`` 单次返回的行数上限。
89
+ FILE_MAX_LINES = 5000
90
+ #: 允许通过 ``/files`` 打开的文件大小上限。超过就拒绝:这个接口把整个文件读进内存,
91
+ #: 一个 1GB 的日志会同时占满服务端内存并卡住事件循环。
92
+ FILE_MAX_READ_BYTES = 32 * 1024 * 1024
93
+
94
+ _THINKING_LEVELS = ("off", "minimal", "low", "medium", "high", "xhigh", "max")
95
+
96
+ _BEHAVIORS = ("prompt", "steer", "followUp")
97
+
98
+
99
+ # ------------------------------------------------------------------ 请求体
100
+
101
+
102
+ @dataclass(slots=True)
103
+ class CreateSessionBody:
104
+ """``POST /sessions``。"""
105
+
106
+ name: str | None = field(default=None, metadata={SCHEMA_KEY: "会话标题,显示在会话列表里"})
107
+ parentSession: str | None = field(
108
+ default=None, metadata={SCHEMA_KEY: "父会话 id;分叉或派生时写进会话头"}
109
+ )
110
+
111
+
112
+ @dataclass(slots=True)
113
+ class ForkSessionBody:
114
+ """``POST /sessions/{id}/fork``。"""
115
+
116
+ entryId: str | None = field(
117
+ default=None, metadata={SCHEMA_KEY: "从哪个条目分叉;缺省用当前叶子"}
118
+ )
119
+
120
+
121
+ @dataclass(slots=True)
122
+ class ImageBody:
123
+ """一张图片。``data`` 是 base64。"""
124
+
125
+ data: str = field(metadata={SCHEMA_KEY: "base64 编码的图片内容"})
126
+ mimeType: str = field(metadata={SCHEMA_KEY: "例如 image/png"})
127
+
128
+
129
+ @dataclass(slots=True)
130
+ class SendMessageBody:
131
+ """``POST /sessions/{id}/messages``。"""
132
+
133
+ text: str = field(metadata={SCHEMA_KEY: "用户消息文本"})
134
+ images: list[ImageBody] | None = field(default=None, metadata={SCHEMA_KEY: "附带图片"})
135
+ behavior: Literal["prompt", "steer", "followUp"] = field(
136
+ default="prompt",
137
+ metadata={SCHEMA_KEY: "prompt 起新回合;steer / followUp 在当前回合排队"},
138
+ )
139
+ wait: bool = field(
140
+ default=False,
141
+ metadata={SCHEMA_KEY: "true 表示等到回合结束并返回最后一条助手消息"},
142
+ )
143
+
144
+
145
+ @dataclass(slots=True)
146
+ class SetModelBody:
147
+ """``PUT /sessions/{id}/model``。"""
148
+
149
+ provider: str = field(metadata={SCHEMA_KEY: "提供商 id,例如 deepseek"})
150
+ modelId: str = field(metadata={SCHEMA_KEY: "模型 id,例如 deepseek-flash"})
151
+
152
+
153
+ @dataclass(slots=True)
154
+ class SetThinkingBody:
155
+ """``PUT /sessions/{id}/thinking``。"""
156
+
157
+ level: Literal["off", "minimal", "low", "medium", "high", "xhigh", "max"] = field(
158
+ metadata={SCHEMA_KEY: "思考级别"}
159
+ )
160
+
161
+
162
+ @dataclass(slots=True)
163
+ class CompactBody:
164
+ """``POST /sessions/{id}/compact``。"""
165
+
166
+ instructions: str | None = field(default=None, metadata={SCHEMA_KEY: "给摘要模型的额外要求"})
167
+
168
+
169
+ @dataclass(slots=True)
170
+ class PlanBody:
171
+ """``POST /sessions/{id}/plan``。"""
172
+
173
+ action: Literal["enter", "approve", "leave"] = field(
174
+ metadata={SCHEMA_KEY: "enter 进入规划模式;approve 批准待批计划;leave 退出"}
175
+ )
176
+ goal: str | None = field(default=None, metadata={SCHEMA_KEY: "enter 时的规划目标"})
177
+
178
+
179
+ @dataclass(slots=True)
180
+ class PermissionAnswerBody:
181
+ """``POST /sessions/{id}/permissions/{requestId}``。"""
182
+
183
+ scope: Literal["once", "session", "deny"] = field(
184
+ metadata={SCHEMA_KEY: "once 只批准这一次;session 记住同类操作;deny 拒绝"}
185
+ )
186
+
187
+
188
+ @dataclass(slots=True)
189
+ class QuestionAnswerBody:
190
+ """``POST /sessions/{id}/questions/{requestId}``。"""
191
+
192
+ selected: list[str] | None = field(default=None, metadata={SCHEMA_KEY: "选中的选项 label"})
193
+ custom: str | None = field(default=None, metadata={SCHEMA_KEY: "自定义回答"})
194
+
195
+
196
+ # -------------------------------------------------------------------- 服务
197
+
198
+
199
+ @dataclass(slots=True)
200
+ class Service:
201
+ """一份运行中的 HTTP 服务:路由表、会话注册表、模型目录与 MCP 运行时。"""
202
+
203
+ registry: SessionRegistry
204
+ models: Models
205
+ mcp: McpRuntime | None
206
+ cwd: str
207
+ version: str
208
+ auth: str
209
+ router: Router = field(default_factory=Router)
210
+
211
+ def decode(self, cls: type, payload: JsonValue | None) -> object:
212
+ """请求体解码。处理函数通过 ``ctx.body()`` 用到它。"""
213
+ return decode_body(cls, payload)
214
+
215
+ def live_session_ids(self) -> list[str]:
216
+ return sorted(self.registry.live_ids())
217
+
218
+ async def close(self) -> None:
219
+ """关闭全部会话。MCP 与沙箱由进程收尾统一关闭。"""
220
+ await self.registry.close()
221
+
222
+
223
+ def create_service(
224
+ *,
225
+ registry: SessionRegistry,
226
+ models: Models,
227
+ mcp: McpRuntime | None,
228
+ cwd: str,
229
+ version: str,
230
+ auth: str,
231
+ ) -> Service:
232
+ """建服务并注册全部路由。"""
233
+ service = Service(
234
+ registry=registry,
235
+ models=models,
236
+ mcp=mcp,
237
+ cwd=cwd,
238
+ version=version,
239
+ auth=auth,
240
+ )
241
+
242
+ def add(
243
+ method: str,
244
+ path: str,
245
+ handler: Handler,
246
+ summary: str,
247
+ *,
248
+ body: type | None = None,
249
+ status: int = 200,
250
+ tags: tuple[str, ...] = (),
251
+ query: tuple[QueryParam, ...] = (),
252
+ sse: bool = False,
253
+ timeout: float = 60.0,
254
+ response: dict[str, JsonValue] | None = None,
255
+ ) -> None:
256
+ service.router.add(
257
+ Route(
258
+ method=method,
259
+ path=path,
260
+ handler=handler,
261
+ summary=summary,
262
+ body=body,
263
+ status=status,
264
+ tags=tags,
265
+ query=query,
266
+ sse=sse,
267
+ timeout=timeout,
268
+ response=response,
269
+ )
270
+ )
271
+
272
+ # ---- 元信息
273
+ add("GET", "/health", health, "存活检查:版本、工作目录、认证方式")
274
+ add("GET", "/openapi.json", openapi_document, "本服务的 OpenAPI 3.1 文档")
275
+ add("GET", "/models", list_models, "模型目录")
276
+
277
+ # ---- 会话
278
+ add(
279
+ "POST",
280
+ "/sessions",
281
+ create_session,
282
+ "新建会话",
283
+ body=CreateSessionBody,
284
+ status=201,
285
+ tags=("sessions",),
286
+ )
287
+ add(
288
+ "GET",
289
+ "/sessions",
290
+ list_sessions,
291
+ "列出会话(磁盘与内存合并,按最后活动时间倒序)",
292
+ tags=("sessions",),
293
+ query=(QueryParam("limit", "最多返回多少条,默认 50", {"type": "integer"}),),
294
+ )
295
+ add("GET", "/sessions/{sessionId}", get_session, "读取一个会话的摘要与状态", tags=("sessions",))
296
+ add(
297
+ "DELETE",
298
+ "/sessions/{sessionId}",
299
+ delete_session,
300
+ "删除会话文件与检查点快照",
301
+ status=204,
302
+ tags=("sessions",),
303
+ )
304
+ add(
305
+ "POST",
306
+ "/sessions/{sessionId}/fork",
307
+ fork_session,
308
+ "从指定条目分叉出一个新会话",
309
+ body=ForkSessionBody,
310
+ status=201,
311
+ tags=("sessions",),
312
+ )
313
+
314
+ # ---- 消息与运行控制
315
+ add(
316
+ "POST",
317
+ "/sessions/{sessionId}/messages",
318
+ send_message,
319
+ "发送消息;默认异步返回 started,wait=true 时等到回合结束",
320
+ body=SendMessageBody,
321
+ tags=("messages",),
322
+ timeout=600.0,
323
+ )
324
+ add(
325
+ "GET",
326
+ "/sessions/{sessionId}/messages",
327
+ get_messages,
328
+ "读取转录消息",
329
+ tags=("messages",),
330
+ )
331
+ add(
332
+ "POST",
333
+ "/sessions/{sessionId}/abort",
334
+ abort_session,
335
+ "中止当前回合",
336
+ tags=("messages",),
337
+ timeout=120.0,
338
+ )
339
+ add(
340
+ "GET",
341
+ "/sessions/{sessionId}/events",
342
+ stream_events,
343
+ "会话事件流(Server-Sent Events,可用 Last-Event-ID 续传)",
344
+ tags=("events",),
345
+ sse=True,
346
+ query=(QueryParam("since", "从这个序号之后开始;0 表示从头", {"type": "integer"}),),
347
+ )
348
+
349
+ # ---- 状态与模型
350
+ add("GET", "/sessions/{sessionId}/state", get_state, "会话状态:模型、上下文、费用、计划")
351
+ add(
352
+ "PUT",
353
+ "/sessions/{sessionId}/model",
354
+ set_model,
355
+ "切换模型",
356
+ body=SetModelBody,
357
+ )
358
+ add(
359
+ "PUT",
360
+ "/sessions/{sessionId}/thinking",
361
+ set_thinking,
362
+ "设置思考级别",
363
+ body=SetThinkingBody,
364
+ )
365
+ add(
366
+ "POST",
367
+ "/sessions/{sessionId}/compact",
368
+ compact_session,
369
+ "手动压缩上下文",
370
+ body=CompactBody,
371
+ timeout=300.0,
372
+ )
373
+ add(
374
+ "POST",
375
+ "/sessions/{sessionId}/plan",
376
+ plan_session,
377
+ "进入、批准或退出规划模式",
378
+ body=PlanBody,
379
+ tags=("sessions",),
380
+ )
381
+
382
+ # ---- 检查点
383
+ add("POST", "/sessions/{sessionId}/undo", undo_session, "撤销最近一个回合")
384
+ add("POST", "/sessions/{sessionId}/redo", redo_session, "重做被撤销的回合")
385
+ add("GET", "/sessions/{sessionId}/diff", get_diff, "当前会话产生的文件差异")
386
+
387
+ # ---- 批准与提问
388
+ add(
389
+ "GET",
390
+ "/sessions/{sessionId}/pending",
391
+ pending_requests,
392
+ "当前挂起的权限请求与提问",
393
+ )
394
+ add(
395
+ "POST",
396
+ "/sessions/{sessionId}/permissions/{requestId}",
397
+ answer_permission,
398
+ "回答一次权限请求",
399
+ body=PermissionAnswerBody,
400
+ )
401
+ add(
402
+ "POST",
403
+ "/sessions/{sessionId}/questions/{requestId}",
404
+ answer_question,
405
+ "回答一次提问",
406
+ body=QuestionAnswerBody,
407
+ )
408
+
409
+ # ---- 文件
410
+ add(
411
+ "GET",
412
+ "/files",
413
+ read_file,
414
+ "读取工作区内的文本文件",
415
+ tags=("files",),
416
+ query=(
417
+ QueryParam("path", "相对工作区的路径", required=True),
418
+ QueryParam("offset", "起始行号,从 1 开始", {"type": "integer"}),
419
+ QueryParam("limit", "最多读多少行", {"type": "integer"}),
420
+ ),
421
+ )
422
+ add(
423
+ "GET",
424
+ "/files/search",
425
+ search_files,
426
+ "按正则或字面量搜索文件内容",
427
+ tags=("files",),
428
+ query=(
429
+ QueryParam("pattern", "搜索模式", required=True),
430
+ QueryParam("path", "搜索目录,默认工作区"),
431
+ QueryParam("glob", "文件过滤,例如 *.py"),
432
+ QueryParam("ignoreCase", "忽略大小写", {"type": "boolean"}),
433
+ QueryParam("literal", "按字面量而非正则", {"type": "boolean"}),
434
+ QueryParam("context", "每条命中前后各带几行", {"type": "integer"}),
435
+ QueryParam("limit", "最多多少条命中", {"type": "integer"}),
436
+ ),
437
+ )
438
+ add(
439
+ "GET",
440
+ "/files/find",
441
+ find_files,
442
+ "按 glob 查找文件",
443
+ tags=("files",),
444
+ query=(
445
+ QueryParam("pattern", "glob 模式", required=True),
446
+ QueryParam("path", "搜索目录,默认工作区"),
447
+ QueryParam("limit", "最多返回多少个路径", {"type": "integer"}),
448
+ ),
449
+ )
450
+
451
+ # ---- MCP
452
+ add("GET", "/mcp", mcp_status, "MCP 服务器状态", tags=("mcp",))
453
+ add(
454
+ "POST",
455
+ "/mcp/{name}/enable",
456
+ enable_mcp,
457
+ "连接一个 MCP 服务器并注册它的工具",
458
+ tags=("mcp",),
459
+ )
460
+ add(
461
+ "POST",
462
+ "/mcp/{name}/disable",
463
+ disable_mcp,
464
+ "断开一个 MCP 服务器并撤下它的工具",
465
+ tags=("mcp",),
466
+ )
467
+
468
+ return service
469
+
470
+
471
+ # ------------------------------------------------------------------ 元信息
472
+
473
+
474
+ async def health(ctx: RequestContext) -> Response:
475
+ """存活检查。这是唯一不需要 Token 的路由,供进程管理器探活。"""
476
+ service = ctx.service
477
+ return json_response(
478
+ {
479
+ "status": "ok",
480
+ "version": service.version,
481
+ "protocol": 1,
482
+ "cwd": service.cwd,
483
+ "auth": service.auth,
484
+ "liveSessions": len(service.live_session_ids()),
485
+ }
486
+ )
487
+
488
+
489
+ async def openapi_document(ctx: RequestContext) -> Response:
490
+ """OpenAPI 文档。从路由表生成,不是手写 JSON。"""
491
+ return json_response(document(ctx.service.router.routes, version=ctx.service.version))
492
+
493
+
494
+ async def list_models(ctx: RequestContext) -> Response:
495
+ """模型目录。与 ``braid models`` 读同一份目录对象。"""
496
+ catalog = ctx.service.models.list_models()
497
+ return json_response({"models": [model_to_wire(model) for model in catalog]})
498
+
499
+
500
+ # -------------------------------------------------------------------- 会话
501
+
502
+
503
+ async def create_session(ctx: RequestContext) -> Response:
504
+ body: CreateSessionBody = ctx.body()
505
+ hub = await ctx.service.registry.create(name=body.name, parent=body.parentSession)
506
+ return json_response(
507
+ {
508
+ "session": ctx.service.registry.summary_of(hub.session_id).to_wire(),
509
+ "state": state_wire(hub),
510
+ },
511
+ status=201,
512
+ )
513
+
514
+
515
+ async def list_sessions(ctx: RequestContext) -> Response:
516
+ limit = query_int(ctx.query, "limit", 50)
517
+ assert limit is not None
518
+ if limit <= 0:
519
+ raise bad_request("查询参数 limit 必须是正整数")
520
+ summaries = ctx.service.registry.list(limit=limit)
521
+ return json_response({"sessions": [summary.to_wire() for summary in summaries]})
522
+
523
+
524
+ async def get_session(ctx: RequestContext) -> Response:
525
+ hub = await ctx.service.registry.open(ctx.param("sessionId"))
526
+ summary = ctx.service.registry.summary_of(hub.session_id)
527
+ return json_response({"session": summary.to_wire(), "state": state_wire(hub)})
528
+
529
+
530
+ async def delete_session(ctx: RequestContext) -> Response:
531
+ await ctx.service.registry.delete(ctx.param("sessionId"))
532
+ return Response(status=204)
533
+
534
+
535
+ async def fork_session(ctx: RequestContext) -> Response:
536
+ body: ForkSessionBody = ctx.body()
537
+ hub = await ctx.service.registry.fork(ctx.param("sessionId"), body.entryId)
538
+ return json_response(
539
+ {
540
+ "session": ctx.service.registry.summary_of(hub.session_id).to_wire(),
541
+ "state": state_wire(hub),
542
+ },
543
+ status=201,
544
+ )
545
+
546
+
547
+ # ---------------------------------------------------------------- 消息
548
+
549
+
550
+ async def send_message(ctx: RequestContext) -> Response:
551
+ """提交一条消息。
552
+
553
+ 默认立刻返回 ``disposition: started``,进度由事件流表达;``wait=true`` 等到
554
+ ``agent_settled`` 再返回最后一条助手消息。两条路径都走
555
+ :meth:`SessionHub.prompt`,区别只在是否等待。
556
+ """
557
+ body: SendMessageBody = ctx.body()
558
+ if not body.text.strip():
559
+ raise bad_request("text 不能为空")
560
+ hub = await _hub(ctx)
561
+ images: list[ImageContent] | None = None
562
+ if body.images:
563
+ images = [ImageContent(data=image.data, mime_type=image.mimeType) for image in body.images]
564
+ result = await hub.prompt(body.text, images=images, behavior=body.behavior, wait=body.wait)
565
+ return json_response(result)
566
+
567
+
568
+ async def get_messages(ctx: RequestContext) -> Response:
569
+ hub = await _hub(ctx)
570
+ return json_response(
571
+ {
572
+ "messages": [
573
+ transcript_message_to_wire(message) for message in hub.session.agent.state.messages
574
+ ]
575
+ }
576
+ )
577
+
578
+
579
+ async def abort_session(ctx: RequestContext) -> Response:
580
+ hub = await _hub(ctx)
581
+ await hub.abort()
582
+ return json_response({"aborted": True})
583
+
584
+
585
+ async def stream_events(ctx: RequestContext) -> SseStream:
586
+ """会话事件流。
587
+
588
+ ``ready`` 是第一帧:``{"sessionId", "seq"}``。``truncated=true`` 表示客户端要的
589
+ 起点早于缓冲,服务端没有补发——客户端应当重新拉一次状态。
590
+ """
591
+ hub = await _hub(ctx)
592
+ since = _since(ctx)
593
+ truncated = False
594
+ try:
595
+ subscription = hub.subscribe(since)
596
+ except ValueError:
597
+ # 缓冲里已经没有这一段:不补发,让客户端重新拉状态。
598
+ subscription = hub.subscribe(None)
599
+ truncated = True
600
+ loop = asyncio.get_running_loop()
601
+ session_id = hub.session_id
602
+
603
+ def frames() -> Iterator[Frame]:
604
+ ready: dict[str, JsonValue] = {"sessionId": session_id, "seq": hub.seq}
605
+ if truncated:
606
+ ready["truncated"] = True
607
+ yield Frame(event="ready", data=_json(ready))
608
+ while True:
609
+ batch, closed = hub.subscription_frames(subscription)
610
+ if closed:
611
+ return
612
+ if not batch:
613
+ yield Frame(event=None)
614
+ continue
615
+ yield from batch
616
+
617
+ def close() -> None:
618
+ if not loop.is_closed():
619
+ loop.call_soon_threadsafe(hub.unsubscribe, subscription)
620
+
621
+ return SseStream(frames=frames(), headers={"Cache-Control": "no-cache"}, on_close=close)
622
+
623
+
624
+ # ---------------------------------------------------------------- 状态与模型
625
+
626
+
627
+ async def get_state(ctx: RequestContext) -> Response:
628
+ hub = await _hub(ctx)
629
+ return json_response(state_wire(hub))
630
+
631
+
632
+ async def set_model(ctx: RequestContext) -> Response:
633
+ body: SetModelBody = ctx.body()
634
+ hub = await _hub(ctx)
635
+ try:
636
+ await hub.session.set_model(body.provider, body.modelId)
637
+ except ValueError as exc:
638
+ raise not_found(f"模型不存在: {body.provider}/{body.modelId}") from exc
639
+ return json_response({"model": model_to_wire(hub.session.model)})
640
+
641
+
642
+ async def set_thinking(ctx: RequestContext) -> Response:
643
+ body: SetThinkingBody = ctx.body()
644
+ hub = await _hub(ctx)
645
+ await hub.session.set_thinking_level(body.level)
646
+ return json_response({"thinkingLevel": hub.session.thinking_level})
647
+
648
+
649
+ async def compact_session(ctx: RequestContext) -> Response:
650
+ body: CompactBody = ctx.body()
651
+ hub = await _hub(ctx)
652
+ try:
653
+ result = await hub.session.compact(body.instructions)
654
+ except SummarizationError as exc:
655
+ raise conflict(f"上下文压缩失败: {exc}") from exc
656
+ return json_response(compaction_result_to_wire(result))
657
+
658
+
659
+ async def plan_session(ctx: RequestContext) -> Response:
660
+ """规划模式的进入、批准与退出。
661
+
662
+ ``approve`` 是客户端的一次显式动作,与模型无关:协议层不提供"模型自己批准"的
663
+ 路径。计划正文在 ``get_session`` 的 ``planMode`` 字段里。
664
+ """
665
+ body: PlanBody = ctx.body()
666
+ hub = await _hub(ctx)
667
+ session = hub.session
668
+ if session.plan_mode is None:
669
+ raise conflict("本次运行没有装配规划模式")
670
+ try:
671
+ if body.action == "enter":
672
+ state = await session.enter_plan_mode(body.goal or "")
673
+ elif body.action == "approve":
674
+ state = await session.approve_plan()
675
+ else:
676
+ state = await session.leave_plan_mode()
677
+ except RuntimeError as exc:
678
+ raise conflict(str(exc)) from exc
679
+ return json_response({"planMode": state.to_wire()})
680
+
681
+
682
+ # ---------------------------------------------------------------- 检查点
683
+
684
+
685
+ def _require_checkpoints(hub: SessionHub) -> None:
686
+ if hub.session.checkpoints is None:
687
+ raise conflict("本次运行没有启用检查点(--no-checkpoint 或没有 git)")
688
+
689
+
690
+ def _require_idle(hub: SessionHub) -> None:
691
+ if hub.is_busy:
692
+ raise conflict("会话正在运行,先 abort 再做撤销或重做")
693
+
694
+
695
+ async def undo_session(ctx: RequestContext) -> Response:
696
+ hub = await _hub(ctx)
697
+ _require_checkpoints(hub)
698
+ _require_idle(hub)
699
+ assert hub.session.checkpoints is not None
700
+ try:
701
+ result = await hub.session.checkpoints.undo()
702
+ except (CheckpointError, GitError) as exc:
703
+ raise conflict(str(exc)) from exc
704
+ return json_response(undo_wire(result))
705
+
706
+
707
+ async def redo_session(ctx: RequestContext) -> Response:
708
+ hub = await _hub(ctx)
709
+ _require_checkpoints(hub)
710
+ _require_idle(hub)
711
+ assert hub.session.checkpoints is not None
712
+ try:
713
+ result = await hub.session.checkpoints.redo()
714
+ except (CheckpointError, GitError) as exc:
715
+ raise conflict(str(exc)) from exc
716
+ return json_response(undo_wire(result))
717
+
718
+
719
+ async def get_diff(ctx: RequestContext) -> Response:
720
+ hub = await _hub(ctx)
721
+ _require_checkpoints(hub)
722
+ assert hub.session.checkpoints is not None
723
+ try:
724
+ diff = await hub.session.checkpoints.diff()
725
+ except (CheckpointError, GitError) as exc:
726
+ raise conflict(str(exc)) from exc
727
+ return json_response(diff_wire(diff))
728
+
729
+
730
+ # ------------------------------------------------------------ 批准与提问
731
+
732
+
733
+ async def pending_requests(ctx: RequestContext) -> Response:
734
+ hub = await _hub(ctx)
735
+ return json_response(
736
+ {"permissions": hub.pending_permissions(), "questions": hub.pending_questions()}
737
+ )
738
+
739
+
740
+ async def answer_permission(ctx: RequestContext) -> Response:
741
+ body: PermissionAnswerBody = ctx.body()
742
+ if body.scope not in APPROVAL_SCOPES:
743
+ raise bad_request(f"未知的 scope: {body.scope}")
744
+ hub = await _hub(ctx)
745
+ result = hub.answer_permission(ctx.param("requestId"), body.scope)
746
+ return json_response(result)
747
+
748
+
749
+ async def answer_question(ctx: RequestContext) -> Response:
750
+ body: QuestionAnswerBody = ctx.body()
751
+ hub = await _hub(ctx)
752
+ result = hub.answer_question(ctx.param("requestId"), body.selected or (), body.custom or "")
753
+ return json_response(result)
754
+
755
+
756
+ # -------------------------------------------------------------------- 文件
757
+
758
+
759
+ async def read_file(ctx: RequestContext) -> Response:
760
+ """读取工作区内的文本文件。
761
+
762
+ 路径必须落在工作区里:一个可以读任意绝对路径的 HTTP 接口等于把整台机器
763
+ 交给任何拿到 Token 的客户端。符号链接按真实路径判断。
764
+ """
765
+ raw_path = query_str(ctx.query, "path")
766
+ if raw_path is None:
767
+ raise bad_request("缺少查询参数 path")
768
+ absolute = _within_workspace(ctx.service.cwd, raw_path)
769
+ if not os.path.isfile(absolute):
770
+ raise not_found(f"文件不存在: {raw_path}")
771
+ offset = query_int(ctx.query, "offset")
772
+ limit = query_int(ctx.query, "limit")
773
+ if offset is not None and offset < 1:
774
+ raise bad_request("查询参数 offset 从 1 开始")
775
+ if limit is not None and limit < 1:
776
+ raise bad_request("查询参数 limit 必须是正整数")
777
+
778
+ size = os.path.getsize(absolute)
779
+ if size > FILE_MAX_READ_BYTES:
780
+ raise ApiError(
781
+ 413,
782
+ "file_too_large",
783
+ f"文件 {size} 字节,超过 /files 的 {FILE_MAX_READ_BYTES} 字节上限;"
784
+ "用 bash 或本地工具查看",
785
+ )
786
+ with open(absolute, encoding="utf-8", errors="replace") as handle:
787
+ text = handle.read()
788
+ lines = text.split("\n")
789
+ total_lines = len(lines)
790
+ start = (offset - 1) if offset is not None else 0
791
+ if start >= total_lines and total_lines > 0:
792
+ raise bad_request(f"offset {offset} 超出文件行数(共 {total_lines} 行)")
793
+ end = min(start + limit, total_lines) if limit is not None else total_lines
794
+ selected = "\n".join(lines[start:end])
795
+ truncation = truncate_head(selected, max_lines=FILE_MAX_LINES, max_bytes=FILE_MAX_BYTES)
796
+ body: dict[str, JsonValue] = {
797
+ "path": to_posix(os.path.relpath(absolute, ctx.service.cwd)),
798
+ "absolutePath": absolute,
799
+ "content": truncation.content,
800
+ "size": size,
801
+ "totalLines": total_lines,
802
+ "truncated": truncation.truncated,
803
+ "truncatedBy": truncation.truncated_by,
804
+ "limitBytes": FILE_MAX_BYTES,
805
+ "limitLines": FILE_MAX_LINES,
806
+ }
807
+ if truncation.truncated:
808
+ body["notice"] = (
809
+ f"内容已截断(上限 {format_size(FILE_MAX_BYTES)} / {FILE_MAX_LINES} 行);"
810
+ "用 offset 与 limit 继续读"
811
+ )
812
+ return json_response(body)
813
+
814
+
815
+ async def search_files(ctx: RequestContext) -> Response:
816
+ """内容搜索。与 ``grep`` 工具共用 :func:`search_contents`。"""
817
+ pattern = query_str(ctx.query, "pattern")
818
+ if pattern is None:
819
+ raise bad_request("缺少查询参数 pattern")
820
+ search_root = _within_workspace(ctx.service.cwd, query_str(ctx.query, "path") or ".")
821
+ if not os.path.exists(search_root):
822
+ raise not_found(f"路径不存在: {query_str(ctx.query, 'path')}")
823
+ limit = query_int(ctx.query, "limit", 100)
824
+ assert limit is not None
825
+ context = query_int(ctx.query, "context", 0)
826
+ assert context is not None
827
+ outcome = await search_contents(
828
+ LocalFileOperations(),
829
+ search_root,
830
+ pattern=pattern,
831
+ glob=query_str(ctx.query, "glob"),
832
+ ignore_case=query_bool(ctx.query, "ignoreCase"),
833
+ literal=query_bool(ctx.query, "literal"),
834
+ context=max(0, context),
835
+ limit=max(1, limit),
836
+ )
837
+ return json_response(
838
+ {
839
+ "matches": [
840
+ {
841
+ "path": hit.path,
842
+ "line": hit.line,
843
+ "text": hit.text,
844
+ "context": hit.context,
845
+ }
846
+ for hit in outcome.hits
847
+ ],
848
+ "matchCount": outcome.matches,
849
+ "limitReached": outcome.limit_reached,
850
+ "linesTruncated": outcome.lines_truncated,
851
+ }
852
+ )
853
+
854
+
855
+ async def find_files(ctx: RequestContext) -> Response:
856
+ """按 glob 找文件。与 ``find`` 工具共用 :func:`find_paths`。"""
857
+ pattern = query_str(ctx.query, "pattern")
858
+ if pattern is None:
859
+ raise bad_request("缺少查询参数 pattern")
860
+ search_root = _within_workspace(ctx.service.cwd, query_str(ctx.query, "path") or ".")
861
+ if not os.path.exists(search_root):
862
+ raise not_found(f"路径不存在: {query_str(ctx.query, 'path')}")
863
+ limit = query_int(ctx.query, "limit", 1000)
864
+ assert limit is not None
865
+ outcome = await find_paths(
866
+ LocalFileOperations(), search_root, pattern=pattern, limit=max(1, limit)
867
+ )
868
+ return json_response({"files": list(outcome.paths), "limitReached": outcome.limit_reached})
869
+
870
+
871
+ # -------------------------------------------------------------------- MCP
872
+
873
+
874
+ async def mcp_status(ctx: RequestContext) -> Response:
875
+ runtime = ctx.service.mcp
876
+ if runtime is None:
877
+ return json_response({"available": False, "servers": []})
878
+ return json_response(
879
+ {"available": True, "servers": [mcp_status_wire(item) for item in runtime.statuses()]}
880
+ )
881
+
882
+
883
+ async def enable_mcp(ctx: RequestContext) -> Response:
884
+ runtime = _require_mcp(ctx)
885
+ status = await runtime.enable(ctx.param("name"))
886
+ return json_response(mcp_status_wire(status))
887
+
888
+
889
+ async def disable_mcp(ctx: RequestContext) -> Response:
890
+ runtime = _require_mcp(ctx)
891
+ status = await runtime.disable(ctx.param("name"))
892
+ return json_response(mcp_status_wire(status))
893
+
894
+
895
+ def _require_mcp(ctx: RequestContext) -> McpRuntime:
896
+ runtime = ctx.service.mcp
897
+ if runtime is None:
898
+ raise conflict("本次运行没有连接任何 MCP 服务器")
899
+ return runtime
900
+
901
+
902
+ # ------------------------------------------------------------------ 工具
903
+
904
+
905
+ def state_wire(hub: SessionHub) -> dict[str, JsonValue]:
906
+ """会话状态。字段与 RPC 的 ``get_state`` 一致,客户端两处共用同一套解析。"""
907
+ session = hub.session
908
+ manager = session.session
909
+ status = session.context_status()
910
+ state: dict[str, JsonValue] = {
911
+ "sessionId": manager.get_session_id(),
912
+ "model": model_to_wire(session.model),
913
+ "thinkingLevel": session.thinking_level,
914
+ "isStreaming": hub.is_busy,
915
+ "isCompacting": session.is_compacting,
916
+ "steeringMode": session.agent.steering_mode,
917
+ "followUpMode": session.agent.follow_up_mode,
918
+ "messageCount": len(session.agent.state.messages),
919
+ "pendingMessageCount": len(session.get_steering_messages())
920
+ + len(session.get_follow_up_messages()),
921
+ }
922
+ state.update(status_wire_parts(status))
923
+ plan = plan_wire(status)
924
+ if plan is not None:
925
+ state["plan"] = plan
926
+ plan_mode = plan_mode_wire(status)
927
+ if plan_mode is not None:
928
+ state["planMode"] = plan_mode
929
+ if session.checkpoints is not None:
930
+ state["checkpoint"] = checkpoint_wire(session.checkpoints)
931
+ session_file = manager.get_session_file()
932
+ if session_file is not None:
933
+ state["sessionFile"] = session_file
934
+ name = manager.get_session_name()
935
+ if name is not None:
936
+ state["sessionName"] = name
937
+ return state
938
+
939
+
940
+ async def _hub(ctx: RequestContext) -> SessionHub:
941
+ """按路径参数打开会话。所有 ``/sessions/{id}/...`` 路由共用。"""
942
+ return await ctx.service.registry.open(ctx.param("sessionId"))
943
+
944
+
945
+ def _since(ctx: RequestContext) -> int | None:
946
+ """事件流的起点:``?since=N`` 优先,其次 ``Last-Event-ID`` 头。"""
947
+ since = query_int(ctx.query, "since")
948
+ if since is not None:
949
+ return since
950
+ header = ctx.headers.get("last-event-id")
951
+ if header is None:
952
+ return None
953
+ try:
954
+ return int(header)
955
+ except ValueError:
956
+ raise bad_request(f"Last-Event-ID 必须是整数,收到 {header!r}") from None
957
+
958
+
959
+ def _within_workspace(cwd: str, path: str) -> str:
960
+ """把相对路径解析到工作区内,越界就拒绝。
961
+
962
+ ``realpath`` 两边都要做:工作区里的一条符号链接可以指向 ``/etc``,只比较
963
+ 字面路径会把这种逃逸放过去。
964
+ """
965
+ root = os.path.realpath(cwd)
966
+ candidate = path if os.path.isabs(path) else os.path.join(root, path)
967
+ resolved = os.path.realpath(candidate)
968
+ if resolved != root and not resolved.startswith(root + os.sep):
969
+ raise ApiError(403, "forbidden_path", f"路径在工作区之外: {path}")
970
+ return resolved
971
+
972
+
973
+ def _json(value: Mapping[str, JsonValue]) -> str:
974
+ """一帧 SSE 的数据体。``ensure_ascii=False``:中文按原文传输。"""
975
+ return json.dumps(dict(value), ensure_ascii=False)