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,354 @@
1
+ """会话注册表:一个进程里活着的会话、磁盘上的会话文件、以及两者之间的打开。
2
+
3
+ ## 两类会话,一个 id 空间
4
+
5
+ ``list`` 读磁盘,``open`` 把磁盘上的会话变成活着的 :class:`SessionHub`。一个会话
6
+ 文件同时只能被一个进程持有(``SessionManager`` 在打开时取跨进程锁),所以"打开
7
+ 失败"是一个需要如实告诉客户端的错误:另一个 braid 进程正在写它。
8
+
9
+ ## 为什么列表要读整份文件
10
+
11
+ 标题、消息数、最后活动时间都不在会话头里,它们是后续条目。只读第一行会让列表
12
+ 少掉一半字段,而"读全部 JSONL"没有别的正确做法——自己按行切再挑字段,等于再写
13
+ 一个会话文件解析器。文件规模是单个对话的量级,读一次可以接受;按
14
+ ``(路径, mtime, size)`` 缓存之后,重复调用不再重复解析。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import asyncio
20
+ import contextlib
21
+ import os
22
+ import shutil
23
+ from collections.abc import Mapping
24
+ from dataclasses import dataclass, field
25
+
26
+ from braid_ai.types import AssistantMessage, JsonValue, UserMessage
27
+ from braid_ai.utils.clock import Clock, SystemClock
28
+ from braid_coding_agent.assembly import Channels, SessionAssembler
29
+ from braid_coding_agent.session import SessionLockedError, SessionManager
30
+ from braid_coding_agent.session.entries import SessionMessageEntry
31
+ from braid_coding_agent.session.manager import load_entries_from_file
32
+
33
+ from .errors import ApiError, bad_request, conflict, not_found
34
+ from .hub import SessionHub
35
+
36
+ __all__ = ["SessionRegistry", "SessionSummary"]
37
+
38
+
39
+ @dataclass(slots=True, frozen=True)
40
+ class SessionSummary:
41
+ """会话列表里的一项。字段取自会话头与后续条目。"""
42
+
43
+ id: str
44
+ name: str | None
45
+ cwd: str
46
+ created_at: str
47
+ updated_at: str
48
+ message_count: int
49
+ parent_session: str | None
50
+ live: bool
51
+ path: str | None
52
+
53
+ def to_wire(self) -> dict[str, JsonValue]:
54
+ return {
55
+ "id": self.id,
56
+ "name": self.name,
57
+ "cwd": self.cwd,
58
+ "createdAt": self.created_at,
59
+ "updatedAt": self.updated_at,
60
+ "messageCount": self.message_count,
61
+ "parentSession": self.parent_session,
62
+ "live": self.live,
63
+ "path": self.path,
64
+ }
65
+
66
+
67
+ @dataclass(slots=True)
68
+ class _FileFacts:
69
+ """一份会话文件的解析结果,按 ``(path, mtime, size)`` 缓存。"""
70
+
71
+ mtime_ns: int
72
+ size: int
73
+ summary: SessionSummary
74
+
75
+
76
+ @dataclass(slots=True)
77
+ class SessionRegistry:
78
+ """会话的创建、打开、列举、删除。
79
+
80
+ :param assembler: 装配器。每个会话都从它构造,与 CLI 共用同一套工具与权限。
81
+ :param session_dir: 会话目录。``None`` 表示只保留内存会话(``--no-session``)。
82
+ :param cwd: 工作目录。所有会话共用它——服务端的一个进程对应一个工作区。
83
+ """
84
+
85
+ assembler: SessionAssembler
86
+ cwd: str
87
+ session_dir: str | None
88
+ clock: Clock = field(default_factory=SystemClock)
89
+ _live: dict[str, SessionHub] = field(default_factory=dict[str, SessionHub])
90
+ _files: dict[str, _FileFacts] = field(default_factory=dict[str, _FileFacts])
91
+ _lock: asyncio.Lock = field(default_factory=asyncio.Lock)
92
+
93
+ # ------------------------------------------------------------------ 创建
94
+
95
+ async def create(self, *, name: str | None = None, parent: str | None = None) -> SessionHub:
96
+ """新建一个空会话。
97
+
98
+ ``parent`` 是会话 id,而会话头里的 ``parentSession`` 记的是文件路径
99
+ (``Manager.fork`` 也这么写)。这里先把 id 换成路径,客户端下次读到的
100
+ ``parentSession`` 才能直接打开。
101
+ """
102
+ parent_path = self.path_of(parent) if parent is not None else None
103
+ if self.session_dir is None:
104
+ manager = SessionManager.in_memory(
105
+ self.cwd, parent_session=parent_path, clock=self.clock
106
+ )
107
+ else:
108
+ manager = SessionManager.create(
109
+ self.cwd, self.session_dir, parent_session=parent_path, clock=self.clock
110
+ )
111
+ hub = self._build(manager)
112
+ if name:
113
+ manager.append_session_info(name)
114
+ return hub
115
+
116
+ async def open(self, session_id: str) -> SessionHub:
117
+ """打开(或返回已经打开的)会话。
118
+
119
+ :raises ApiError: 404 会话不存在;409 另一个进程正持有这个会话文件。
120
+ """
121
+ existing = self._live.get(session_id)
122
+ if existing is not None:
123
+ return existing
124
+ async with self._lock:
125
+ existing = self._live.get(session_id)
126
+ if existing is not None:
127
+ return existing
128
+ path = self.path_of(session_id)
129
+ try:
130
+ manager = SessionManager.open(path, clock=self.clock)
131
+ except SessionLockedError as exc:
132
+ raise conflict(str(exc), sessionId=session_id) from exc
133
+ except (OSError, ValueError) as exc:
134
+ raise ApiError(500, "session_unreadable", f"无法打开会话 {path}: {exc}") from exc
135
+ return self._build(manager)
136
+
137
+ def _build(self, manager: SessionManager) -> SessionHub:
138
+ """把会话树装成 AgentSession 并登记。
139
+
140
+ 每个会话一份批准通道:HTTP 服务端要在事件流里标明"这是哪个会话的请求",
141
+ 共用一个通道会让请求失去归属。
142
+ """
143
+ channels = Channels()
144
+ session = self.assembler.build(manager, compaction=True, channels=channels)
145
+ hub = SessionHub(session)
146
+ channels.approval = hub.request_approval
147
+ channels.question = hub.request_question
148
+ hub.start()
149
+ self._live[hub.session_id] = hub
150
+ return hub
151
+
152
+ async def fork(self, session_id: str, entry_id: str | None = None) -> SessionHub:
153
+ """从指定条目(默认当前叶子)分叉出一个新会话。"""
154
+ hub = await self.open(session_id)
155
+ manager = hub.session.session
156
+ target = entry_id if entry_id is not None else manager.leaf_id
157
+ if target is None:
158
+ raise bad_request("当前会话还没有任何条目,无法分叉")
159
+ try:
160
+ forked = manager.fork(target)
161
+ except ValueError as exc:
162
+ raise not_found(str(exc)) from exc
163
+ return self._build(forked)
164
+
165
+ # ------------------------------------------------------------------ 查询
166
+
167
+ def live_ids(self) -> list[str]:
168
+ """当前活着的会话 id。``/health`` 用它报数量。"""
169
+ return list(self._live)
170
+
171
+ def path_of(self, session_id: str) -> str:
172
+ """会话 id → 文件路径。找不到就是 404,不猜默认文件名。"""
173
+ if self.session_dir is None:
174
+ raise not_found(f"会话 {session_id} 不存在(服务端没有启用会话目录)")
175
+ self._refresh_files()
176
+ for facts in self._files.values():
177
+ if facts.summary.id == session_id and facts.summary.path is not None:
178
+ return facts.summary.path
179
+ raise not_found(f"会话 {session_id} 不存在")
180
+
181
+ def summary_of(self, session_id: str) -> SessionSummary:
182
+ """一个会话的列表信息。活着的会话优先,其次读磁盘。"""
183
+ hub = self._live.get(session_id)
184
+ if hub is not None:
185
+ return self._summary_for_live(hub)
186
+ if self.session_dir is None:
187
+ raise not_found(f"会话 {session_id} 不存在")
188
+ self._refresh_files()
189
+ for facts in self._files.values():
190
+ if facts.summary.id == session_id:
191
+ return facts.summary
192
+ raise not_found(f"会话 {session_id} 不存在")
193
+
194
+ def list(self, *, limit: int = 50) -> list[SessionSummary]:
195
+ """磁盘与内存会话合并,按最后活动时间倒序。"""
196
+ merged: dict[str, SessionSummary] = {}
197
+ if self.session_dir is not None:
198
+ self._refresh_files()
199
+ for facts in self._files.values():
200
+ merged[facts.summary.id] = facts.summary
201
+ for session_id, hub in self._live.items():
202
+ merged[session_id] = self._summary_for_live(hub)
203
+ ordered = sorted(merged.values(), key=lambda item: item.updated_at, reverse=True)
204
+ return ordered[: max(1, limit)]
205
+
206
+ def _summary_for_live(self, hub: SessionHub) -> SessionSummary:
207
+ """活着的会话:状态直接问对象,不必再读文件。
208
+
209
+ ``messageCount`` 只数用户与助手消息,与磁盘摘要口径一致:系统提示词不是
210
+ "对话里说了几句"。
211
+ """
212
+ manager = hub.session.session
213
+ header = manager.get_header()
214
+ entries = manager.get_entries()
215
+ messages = [
216
+ entry
217
+ for entry in entries
218
+ if isinstance(entry, SessionMessageEntry)
219
+ and isinstance(entry.message, (UserMessage, AssistantMessage))
220
+ ]
221
+ return SessionSummary(
222
+ id=manager.get_session_id(),
223
+ name=manager.get_session_name(),
224
+ cwd=manager.get_cwd(),
225
+ created_at=header.timestamp if header is not None else "",
226
+ updated_at=entries[-1].timestamp if entries else (header.timestamp if header else ""),
227
+ message_count=len(messages),
228
+ parent_session=header.parent_session if header is not None else None,
229
+ live=True,
230
+ path=manager.get_session_file(),
231
+ )
232
+
233
+ def _refresh_files(self) -> None:
234
+ """扫描会话目录,按 mtime/size 复用已解析的结果。"""
235
+ directory = self.session_dir
236
+ if directory is None or not os.path.isdir(directory):
237
+ return
238
+ seen: set[str] = set()
239
+ for name in os.listdir(directory):
240
+ if not name.endswith(".jsonl"):
241
+ continue
242
+ path = os.path.join(directory, name)
243
+ seen.add(path)
244
+ try:
245
+ stat = os.stat(path)
246
+ except OSError:
247
+ continue
248
+ cached = self._files.get(path)
249
+ unchanged = (
250
+ cached is not None
251
+ and cached.mtime_ns == stat.st_mtime_ns
252
+ and cached.size == stat.st_size
253
+ )
254
+ if unchanged:
255
+ continue
256
+ summary = _read_summary(path)
257
+ if summary is None:
258
+ self._files.pop(path, None)
259
+ continue
260
+ self._files[path] = _FileFacts(
261
+ mtime_ns=stat.st_mtime_ns, size=stat.st_size, summary=summary
262
+ )
263
+ for path in list(self._files):
264
+ if path not in seen:
265
+ del self._files[path]
266
+
267
+ # ------------------------------------------------------------------ 删除
268
+
269
+ async def delete(self, session_id: str) -> None:
270
+ """删除一个会话:先释放(或取得)文件锁,再删会话文件与快照目录。
271
+
272
+ 没有活着的会话时也要走一次 ``open``:这样"另一个进程正写着它"会变成
273
+ 一条 409,而不是把一个正在被追加的文件从磁盘上抽走。
274
+ """
275
+ hub = self._live.get(session_id)
276
+ path: str
277
+ if hub is not None:
278
+ if hub.is_busy:
279
+ raise conflict("会话正在运行,先 abort 再删除", sessionId=session_id)
280
+ path = hub.session.session.get_session_file() or ""
281
+ await hub.close()
282
+ del self._live[session_id]
283
+ else:
284
+ path = self.path_of(session_id)
285
+ try:
286
+ manager = SessionManager.open(path, clock=self.clock)
287
+ except SessionLockedError as exc:
288
+ raise conflict(str(exc), sessionId=session_id) from exc
289
+ manager.release_lock()
290
+ if path:
291
+ _remove_file(path)
292
+ _remove_file(f"{path}.lock")
293
+ snapshots = os.path.join(os.path.dirname(path), session_id, "snapshots")
294
+ shutil.rmtree(snapshots, ignore_errors=True)
295
+ self._files.pop(path, None)
296
+
297
+ # ------------------------------------------------------------------ 收尾
298
+
299
+ async def close(self) -> None:
300
+ """关闭全部活着的会话。逐个释放,一个失败不挡后面。"""
301
+ hubs = list(self._live.values())
302
+ self._live.clear()
303
+ for hub in hubs:
304
+ await hub.close()
305
+
306
+
307
+ def _read_summary(path: str) -> SessionSummary | None:
308
+ """读一份会话文件,算出列表需要的字段。坏文件跳过,不让一个坏文件挡住列表。"""
309
+ try:
310
+ entries = load_entries_from_file(path)
311
+ except (OSError, ValueError):
312
+ return None
313
+ if not entries:
314
+ return None
315
+ header = entries[0]
316
+ session_id = header.get("id")
317
+ cwd = header.get("cwd")
318
+ created = header.get("timestamp")
319
+ if not isinstance(session_id, str) or not isinstance(cwd, str):
320
+ return None
321
+ name: str | None = None
322
+ message_count = 0
323
+ updated = created if isinstance(created, str) else ""
324
+ parent = header.get("parentSession")
325
+ for entry in entries[1:]:
326
+ timestamp = entry.get("timestamp")
327
+ if isinstance(timestamp, str):
328
+ updated = timestamp
329
+ kind = entry.get("type")
330
+ if kind == "message":
331
+ message = entry.get("message")
332
+ role = message.get("role") if isinstance(message, Mapping) else None
333
+ if role in ("user", "assistant"):
334
+ message_count += 1
335
+ elif kind == "session_info":
336
+ raw_name = entry.get("name")
337
+ name = raw_name.strip() if isinstance(raw_name, str) and raw_name.strip() else None
338
+ return SessionSummary(
339
+ id=session_id,
340
+ name=name,
341
+ cwd=cwd,
342
+ created_at=created if isinstance(created, str) else "",
343
+ updated_at=updated,
344
+ message_count=message_count,
345
+ parent_session=parent if isinstance(parent, str) else None,
346
+ live=False,
347
+ path=path,
348
+ )
349
+
350
+
351
+ def _remove_file(path: str) -> None:
352
+ """删一个文件。不存在就当作已经删掉了。"""
353
+ with contextlib.suppress(FileNotFoundError):
354
+ os.unlink(path)
@@ -0,0 +1,275 @@
1
+ """路由表与请求上下文。
2
+
3
+ 路由是显式的数据,不是装饰器在导入期收集的副作用:一份路由表同时喂给
4
+ HTTP 适配器、OpenAPI 文档与测试,三处读同一份定义。
5
+
6
+ ## 路径参数
7
+
8
+ 模板写成 ``/sessions/{sessionId}/messages``,匹配时按 ``{name}`` 切段。只支持
9
+ 整段参数,不支持段内通配——本服务的资源 id 都是单个路径段,段的内部结构交给
10
+ 服务端校验。
11
+
12
+ ## 查询参数
13
+
14
+ ``query_int`` / ``query_bool`` / ``query_str`` 做类型转换,转不动就是 400。
15
+ 让处理函数自己 ``int(...)`` 会在异常文本里漏出 Python 的类型名,客户端拿它
16
+ 没法判断这是不是自己的错。
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ from collections.abc import Awaitable, Callable, Iterator, Mapping
23
+ from dataclasses import dataclass, field
24
+ from typing import TYPE_CHECKING, Any
25
+
26
+ from braid_ai.types import JsonValue
27
+
28
+ from .errors import ApiError, bad_request
29
+
30
+ if TYPE_CHECKING:
31
+ from .service import Service
32
+
33
+ __all__ = [
34
+ "Frame",
35
+ "HttpRequest",
36
+ "QueryParam",
37
+ "RequestContext",
38
+ "Response",
39
+ "Route",
40
+ "Router",
41
+ "SseStream",
42
+ "json_response",
43
+ "query_bool",
44
+ "query_int",
45
+ "query_str",
46
+ ]
47
+
48
+
49
+ @dataclass(slots=True, frozen=True)
50
+ class HttpRequest:
51
+ """一条已经读进内存的 HTTP 请求。请求体大小由适配器先设上限。"""
52
+
53
+ method: str
54
+ path: str
55
+ query: Mapping[str, str]
56
+ headers: Mapping[str, str]
57
+ body: bytes
58
+
59
+
60
+ @dataclass(slots=True)
61
+ class Response:
62
+ """JSON 响应。``body`` 为 ``None`` 时不写响应体(204)。"""
63
+
64
+ status: int = 200
65
+ body: Any = None
66
+ headers: dict[str, str] = field(default_factory=dict[str, str])
67
+
68
+
69
+ @dataclass(slots=True, frozen=True)
70
+ class Frame:
71
+ """一帧 SSE。``event`` 为 ``None`` 时写成注释行(心跳),客户端不会看到事件。"""
72
+
73
+ event: str | None
74
+ data: str = ""
75
+ id: str | None = None
76
+
77
+
78
+ @dataclass(slots=True)
79
+ class SseStream:
80
+ """SSE 响应:适配器负责分帧与心跳,处理函数只产出帧。
81
+
82
+ ``frames`` 在请求线程里迭代;``on_close`` 在同一线程的 ``finally`` 里调用,
83
+ 用来把订阅者从会话上摘掉。它必须是线程安全的(通常是
84
+ ``loop.call_soon_threadsafe`` 的包装)。
85
+ """
86
+
87
+ frames: Iterator[Frame]
88
+ headers: dict[str, str] = field(default_factory=dict[str, str])
89
+ on_close: Callable[[], None] | None = None
90
+
91
+
92
+ type Handler = Callable[[RequestContext], Awaitable[Response | SseStream]]
93
+ type Transport = Response | SseStream
94
+
95
+
96
+ def json_response(body: Any, status: int = 200) -> Response:
97
+ """JSON 响应。所有 2xx 的业务返回都走它。"""
98
+ return Response(status=status, body=body)
99
+
100
+
101
+ @dataclass(slots=True, frozen=True)
102
+ class QueryParam:
103
+ """一条查询参数声明。只用于生成 OpenAPI;实际读取由处理函数完成。"""
104
+
105
+ name: str
106
+ description: str
107
+ schema: dict[str, Any] = field(default_factory=lambda: {"type": "string"})
108
+ required: bool = False
109
+
110
+
111
+ @dataclass(slots=True, frozen=True)
112
+ class Route:
113
+ """一条路由。
114
+
115
+ :param body: 请求体的 dataclass 类型。``None`` 表示这条路由不收请求体。
116
+ 它只用于生成 OpenAPI 文档;解码由处理函数调用 :meth:`RequestContext.body`
117
+ 完成,那一步才带字段级错误信息。
118
+ :param summary: 一句话说明,进 OpenAPI。
119
+ :param response: 成功响应的 Schema,进 OpenAPI。
120
+ :param query: 查询参数声明,进 OpenAPI。
121
+ """
122
+
123
+ method: str
124
+ path: str
125
+ handler: Handler
126
+ summary: str
127
+ body: type | None = None
128
+ response: dict[str, Any] | None = None
129
+ status: int = 200
130
+ tags: tuple[str, ...] = ()
131
+ query: tuple[QueryParam, ...] = ()
132
+ sse: bool = False
133
+ #: 处理函数在事件循环上的最长等待秒数。``wait=true`` 的发送与压缩要放宽。
134
+ timeout: float = 60.0
135
+
136
+
137
+ class Router:
138
+ """路由集合。按"路径段数 + 字面量优先"匹配,避免 ``/sessions/{id}`` 抢走
139
+ ``/sessions/{id}/messages``。"""
140
+
141
+ def __init__(self) -> None:
142
+ self._routes: list[Route] = []
143
+
144
+ @property
145
+ def routes(self) -> list[Route]:
146
+ """全部路由,按注册顺序。OpenAPI 文档与测试都读它。"""
147
+ return list(self._routes)
148
+
149
+ def add(self, route: Route) -> None:
150
+ """注册一条路由。同方法同模板重复注册直接失败——那是代码缺陷。"""
151
+ for existing in self._routes:
152
+ if existing.method == route.method and existing.path == route.path:
153
+ raise ValueError(f"重复路由: {route.method} {route.path}")
154
+ self._routes.append(route)
155
+
156
+ def match(self, method: str, path: str) -> tuple[Route, dict[str, str]] | None:
157
+ """找到路由与路径参数。路径先做一次 ``rstrip('/')`` 归一化。"""
158
+ normalized = path.rstrip("/") or "/"
159
+ best: tuple[Route, dict[str, str]] | None = None
160
+ best_score = -1
161
+ for route in self._routes:
162
+ if route.method != method:
163
+ continue
164
+ params = _match_path(route.path, normalized)
165
+ if params is None:
166
+ continue
167
+ score = _specificity(route.path)
168
+ if score > best_score:
169
+ best = (route, params)
170
+ best_score = score
171
+ return best
172
+
173
+ def allowed_methods(self, path: str) -> list[str]:
174
+ """这条路径上还有哪些方法(用于 405 响应里的 ``Allow`` 头)。"""
175
+ normalized = path.rstrip("/") or "/"
176
+ return [
177
+ route.method
178
+ for route in self._routes
179
+ if _match_path(route.path, normalized) is not None
180
+ ]
181
+
182
+
183
+ def _match_path(template: str, path: str) -> dict[str, str] | None:
184
+ """按段匹配。字面量段必须相等,``{name}`` 段吃掉一段非空路径。"""
185
+ template_parts = [part for part in template.strip("/").split("/") if part]
186
+ path_parts = [part for part in path.strip("/").split("/") if part]
187
+ if len(template_parts) != len(path_parts):
188
+ return None
189
+ params: dict[str, str] = {}
190
+ for expected, actual in zip(template_parts, path_parts, strict=True):
191
+ if expected.startswith("{") and expected.endswith("}"):
192
+ params[expected[1:-1]] = actual
193
+ elif expected != actual:
194
+ return None
195
+ return params
196
+
197
+
198
+ def _specificity(template: str) -> int:
199
+ """字面量段越多越具体。``/sessions/{id}/messages`` 因此压过 ``/sessions/{id}/{x}``。"""
200
+ return sum(1 for part in template.strip("/").split("/") if not part.startswith("{"))
201
+
202
+
203
+ @dataclass(slots=True)
204
+ class RequestContext:
205
+ """一次路由调用需要的全部输入。
206
+
207
+ ``body()`` 延迟解码:GET 路由不收请求体,解码它只会把一条正常的查询变成 400。
208
+ """
209
+
210
+ request: HttpRequest
211
+ params: dict[str, str]
212
+ service: Service
213
+ route: Route
214
+ _decoded: Any = None
215
+ _decoded_done: bool = False
216
+
217
+ @property
218
+ def query(self) -> Mapping[str, str]:
219
+ return self.request.query
220
+
221
+ @property
222
+ def headers(self) -> Mapping[str, str]:
223
+ return self.request.headers
224
+
225
+ def param(self, name: str) -> str:
226
+ """路径参数。模板与匹配器保证它存在。"""
227
+ value = self.params.get(name)
228
+ if value is None:
229
+ raise ApiError(500, "internal", f"路由缺少路径参数 {name}")
230
+ return value
231
+
232
+ def body(self) -> Any:
233
+ """按路由声明的 dataclass 解码请求体,结果缓存。"""
234
+ if self._decoded_done:
235
+ return self._decoded
236
+ payload: JsonValue | None = None
237
+ if self.request.body:
238
+ try:
239
+ payload = json.loads(self.request.body)
240
+ except json.JSONDecodeError as exc:
241
+ raise bad_request(f"请求体不是合法 JSON: {exc.msg}") from None
242
+ decoded = None if self.route.body is None else self.service.decode(self.route.body, payload)
243
+ self._decoded = decoded
244
+ self._decoded_done = True
245
+ return decoded
246
+
247
+
248
+ def query_int(query: Mapping[str, str], name: str, default: int | None = None) -> int | None:
249
+ """读一个整数查询参数。缺省返回 ``default``,给了却不是整数就 400。"""
250
+ raw = query.get(name)
251
+ if raw is None or raw == "":
252
+ return default
253
+ try:
254
+ return int(raw)
255
+ except ValueError:
256
+ raise bad_request(f"查询参数 {name} 必须是整数,收到 {raw!r}") from None
257
+
258
+
259
+ def query_bool(query: Mapping[str, str], name: str, default: bool = False) -> bool:
260
+ """读一个布尔查询参数,接受 ``true/1/yes`` 与 ``false/0/no``。"""
261
+ raw = query.get(name)
262
+ if raw is None or raw == "":
263
+ return default
264
+ lowered = raw.lower()
265
+ if lowered in ("true", "1", "yes"):
266
+ return True
267
+ if lowered in ("false", "0", "no"):
268
+ return False
269
+ raise bad_request(f"查询参数 {name} 必须是布尔值,收到 {raw!r}")
270
+
271
+
272
+ def query_str(query: Mapping[str, str], name: str, default: str | None = None) -> str | None:
273
+ """读一个字符串查询参数。空串按缺省处理。"""
274
+ raw = query.get(name)
275
+ return default if raw is None or raw == "" else raw