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,480 @@
1
+ """JSON 模式的事件序列化:``SessionEvent`` → wire dict。
2
+
3
+ JSON 与 RPC 共用同一套事件形状,
4
+ 这里只做形状转换,不碰 I/O:写不写 stdout、什么时候 flush,是
5
+ :mod:`braid_coding_agent.modes.print_mode` 的事。
6
+
7
+ ## 为什么只有 ``message_update`` 被改写
8
+
9
+ SDK 事件为**进程内**消费者保留了两个体积随流增长的字段:
10
+
11
+ - ``message_update.message``:截至目前的完整消息快照;
12
+ - 每个 provider 事件的 ``partial``:同样的累积快照。
13
+
14
+ 进程内 UI 直接持有引用,读快照零成本;可 stdout 一旦原样转发,每个 delta
15
+ 都要携带一份越来越大的消息,流的体积随轮数平方增长。协议因此在边界上裁掉
16
+ 这两处,只保留体积恒定的部分:
17
+
18
+ - 顶层 ``usage``:最新累计用量,字段数固定;
19
+ - delta 事件本体(``contentIndex``/``delta``/``content``):增量;
20
+ - ``toolcall_start`` 特判:它没有 delta 内容可看,从 ``partial`` 里把
21
+ ``id`` 与 ``toolName`` 摘到顶层,消费方才能在流里关联工具生命周期。
22
+
23
+ 消费方按契约重建:缓冲 ``delta`` 做活显示,用 ``text_end``/``thinking_end``/
24
+ ``toolcall_end`` 的权威内容覆盖,最终以 ``message_end.message`` 为准。
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import Any
30
+
31
+ from braid_agent.tools import AgentToolResult
32
+ from braid_agent.types import (
33
+ AgentEndEvent,
34
+ AgentStartEvent,
35
+ LoopGuardTriggeredEvent,
36
+ MessageEndEvent,
37
+ MessageStartEvent,
38
+ MessageUpdateEvent,
39
+ ToolExecutionEndEvent,
40
+ ToolExecutionStartEvent,
41
+ ToolExecutionUpdateEvent,
42
+ TurnEndEvent,
43
+ TurnStartEvent,
44
+ )
45
+ from braid_ai.types import (
46
+ AssistantMessage,
47
+ DoneEvent,
48
+ ErrorEvent,
49
+ Model,
50
+ StartEvent,
51
+ SystemMessage,
52
+ TextDeltaEvent,
53
+ TextEndEvent,
54
+ TextStartEvent,
55
+ ThinkingDeltaEvent,
56
+ ThinkingEndEvent,
57
+ ThinkingStartEvent,
58
+ ToolCall,
59
+ ToolCallDeltaEvent,
60
+ ToolCallEndEvent,
61
+ ToolCallStartEvent,
62
+ ToolResultMessage,
63
+ UserMessage,
64
+ )
65
+ from braid_ai.wire import content_to_wire, message_to_wire, usage_to_wire
66
+ from braid_coding_agent.compaction.summarize import CompactionResult
67
+ from braid_coding_agent.session.agent_session import (
68
+ AgentEndWithRetryEvent,
69
+ AgentSettledEvent,
70
+ AutoRetryEndEvent,
71
+ AutoRetryStartEvent,
72
+ CompactionEndEvent,
73
+ CompactionStartEvent,
74
+ CompletionEvidenceEvent,
75
+ ContextWarningEvent,
76
+ ExtensionErrorEvent,
77
+ ModelChangedEvent,
78
+ PlanModeEvent,
79
+ PlanUpdateEvent,
80
+ QueueUpdateEvent,
81
+ SessionEvent,
82
+ SessionManager,
83
+ SummarizationRetryAttemptStartEvent,
84
+ SummarizationRetryFinishedEvent,
85
+ SummarizationRetryScheduledEvent,
86
+ ThinkingLevelChangedEvent,
87
+ ToolResultCleanupEvent,
88
+ )
89
+ from braid_coding_agent.session.entries import agent_message_to_wire
90
+ from braid_coding_agent.session.plan import plan_to_wire
91
+ from braid_coding_agent.session.status import usage_wire
92
+
93
+ __all__ = [
94
+ "compaction_result_to_wire",
95
+ "model_to_wire",
96
+ "session_event_to_wire",
97
+ "session_header_to_wire",
98
+ "transcript_message_to_wire",
99
+ ]
100
+
101
+
102
+ def model_to_wire(model: Model) -> dict[str, Any]:
103
+ """模型目录项 → wire。字段名与模型对象的 JSON 序列化结果一致。
104
+
105
+ RPC 的 ``get_state``、``set_model`` 与 HTTP 的 ``/models``、``/state`` 共用
106
+ 这一个形状:客户端只需要认识一种模型描述。
107
+ """
108
+ return {
109
+ "id": model.id,
110
+ "name": model.name,
111
+ "api": model.api,
112
+ "provider": model.provider,
113
+ "baseUrl": model.base_url,
114
+ "reasoning": model.reasoning,
115
+ "input": list(model.input),
116
+ "cost": {
117
+ "input": model.cost.input,
118
+ "output": model.cost.output,
119
+ "cacheRead": model.cost.cache_read,
120
+ "cacheWrite": model.cost.cache_write,
121
+ },
122
+ "contextWindow": model.context_window,
123
+ "maxTokens": model.max_tokens,
124
+ "thinkingLevels": list(model.thinking_levels),
125
+ }
126
+
127
+
128
+ def session_header_to_wire(manager: SessionManager) -> dict[str, Any] | None:
129
+ """JSON 模式的第一行:会话头;没有头(旧文件缺失、异常装配)时一行都不发。
130
+
131
+ 头字段的形状与会话文件第一行完全一致(``getHeader()`` 取的就是内存里
132
+ ``fileEntries`` 的第一条),消费方可以用同一个解析器读两种流。内存会话
133
+ (``--no-session``)同样有头,头只是不落盘。
134
+ """
135
+ header = manager.get_header()
136
+ if header is None:
137
+ return None
138
+ wire: dict[str, Any] = {
139
+ "type": "session",
140
+ "id": header.id,
141
+ "timestamp": header.timestamp,
142
+ "cwd": header.cwd,
143
+ }
144
+ if header.version is not None:
145
+ wire["version"] = header.version
146
+ if header.parent_session is not None:
147
+ wire["parentSession"] = header.parent_session
148
+ wire.update(header.extra)
149
+ return wire
150
+
151
+
152
+ def session_event_to_wire(event: SessionEvent) -> dict[str, Any]:
153
+ """一条会话事件 → 一个 wire dict(调用方负责 ``json.dumps`` 与换行)。
154
+
155
+ :raises ValueError: ``message_update`` 的消息不是助手消息、assistant 事件缺
156
+ ``partial``,或 ``toolcall_start`` 对应的内容块不是工具调用。序列化层
157
+ 遇到结构不合法的事件就地失败,不输出形状错的一行。
158
+ """
159
+ match event:
160
+ case AgentStartEvent():
161
+ return {"type": "agent_start"}
162
+ case AgentEndWithRetryEvent():
163
+ # 会话层发出的 agent_end 总是带 willRetry:低层 run 结束不等于会话
164
+ # 空闲,紧随其后可能有一次自动重试。
165
+ return {
166
+ "type": "agent_end",
167
+ "messages": [transcript_message_to_wire(m) for m in event.messages],
168
+ "willRetry": event.will_retry,
169
+ }
170
+ case AgentEndEvent():
171
+ # 直连 Agent(不经会话)的事件没有重试语义,不带 willRetry。
172
+ return {
173
+ "type": "agent_end",
174
+ "messages": [transcript_message_to_wire(m) for m in event.messages],
175
+ }
176
+ case AutoRetryStartEvent():
177
+ return {
178
+ "type": "auto_retry_start",
179
+ "attempt": event.attempt,
180
+ "maxAttempts": event.max_attempts,
181
+ "delayMs": event.delay_ms,
182
+ "errorMessage": event.error_message,
183
+ }
184
+ case AutoRetryEndEvent():
185
+ wire: dict[str, Any] = {
186
+ "type": "auto_retry_end",
187
+ "success": event.success,
188
+ "attempt": event.attempt,
189
+ }
190
+ if event.final_error is not None:
191
+ wire["finalError"] = event.final_error
192
+ return wire
193
+ case CompactionStartEvent():
194
+ return {"type": "compaction_start", "reason": event.reason}
195
+ case CompactionEndEvent():
196
+ wire = {
197
+ "type": "compaction_end",
198
+ "reason": event.reason,
199
+ "aborted": event.aborted,
200
+ "willRetry": event.will_retry,
201
+ }
202
+ if event.result is not None:
203
+ wire["result"] = compaction_result_to_wire(event.result)
204
+ if event.error_message is not None:
205
+ wire["errorMessage"] = event.error_message
206
+ return wire
207
+ case SummarizationRetryScheduledEvent():
208
+ return {
209
+ "type": "summarization_retry_scheduled",
210
+ "attempt": event.attempt,
211
+ "maxAttempts": event.max_attempts,
212
+ "delayMs": event.delay_ms,
213
+ "errorMessage": event.error_message,
214
+ }
215
+ case SummarizationRetryAttemptStartEvent():
216
+ wire = {
217
+ "type": "summarization_retry_attempt_start",
218
+ "source": event.source,
219
+ }
220
+ if event.reason is not None:
221
+ wire["reason"] = event.reason
222
+ return wire
223
+ case SummarizationRetryFinishedEvent():
224
+ return {"type": "summarization_retry_finished"}
225
+ case AgentSettledEvent():
226
+ settled: dict[str, Any] = {"type": "agent_settled", "aborted": event.aborted}
227
+ if event.usage is not None:
228
+ settled["usage"] = usage_wire(event.usage)
229
+ return settled
230
+ case ContextWarningEvent():
231
+ return {
232
+ "type": "context_warning",
233
+ "contextWindow": event.context_window,
234
+ "tokens": event.tokens,
235
+ "threshold": event.threshold,
236
+ "remainingTokens": event.remaining_tokens,
237
+ "remainingPercent": round(event.remaining_percent, 2),
238
+ }
239
+ case ToolResultCleanupEvent():
240
+ return {
241
+ "type": "tool_result_cleanup",
242
+ "cleared": event.cleared,
243
+ "charsBefore": event.chars_before,
244
+ "charsAfter": event.chars_after,
245
+ "tokens": event.tokens,
246
+ "contextWindow": event.context_window,
247
+ }
248
+ case TurnStartEvent():
249
+ return {"type": "turn_start"}
250
+ case TurnEndEvent():
251
+ return {
252
+ "type": "turn_end",
253
+ "message": transcript_message_to_wire(event.message),
254
+ "toolResults": [transcript_message_to_wire(r) for r in event.tool_results],
255
+ }
256
+ case MessageStartEvent():
257
+ return {"type": "message_start", "message": transcript_message_to_wire(event.message)}
258
+ case MessageEndEvent():
259
+ return {"type": "message_end", "message": transcript_message_to_wire(event.message)}
260
+ case MessageUpdateEvent():
261
+ if not isinstance(event.message, AssistantMessage):
262
+ raise ValueError("message_update message is not an assistant message")
263
+ return {
264
+ "type": "message_update",
265
+ "usage": usage_to_wire(event.message.usage),
266
+ "assistantMessageEvent": _assistant_event_to_wire(event),
267
+ }
268
+ case ToolExecutionStartEvent():
269
+ return {
270
+ "type": "tool_execution_start",
271
+ "toolCallId": event.tool_call_id,
272
+ "toolName": event.tool_name,
273
+ "args": event.args,
274
+ }
275
+ case ToolExecutionUpdateEvent():
276
+ return {
277
+ "type": "tool_execution_update",
278
+ "toolCallId": event.tool_call_id,
279
+ "toolName": event.tool_name,
280
+ "args": event.args,
281
+ "partialResult": _tool_result_to_wire(event.partial_result),
282
+ }
283
+ case ToolExecutionEndEvent():
284
+ wire: dict[str, Any] = {
285
+ "type": "tool_execution_end",
286
+ "toolCallId": event.tool_call_id,
287
+ "toolName": event.tool_name,
288
+ "result": _tool_result_to_wire(event.result),
289
+ "isError": event.is_error,
290
+ }
291
+ if event.duration_ms is not None:
292
+ wire["durationMs"] = event.duration_ms
293
+ return wire
294
+ case QueueUpdateEvent():
295
+ return {
296
+ "type": "queue_update",
297
+ "steering": list(event.steering),
298
+ "followUp": list(event.follow_up),
299
+ }
300
+ case PlanUpdateEvent():
301
+ return {"type": "plan_update", "plan": plan_to_wire(event.state)}
302
+ case PlanModeEvent():
303
+ # ``reason`` 与完整状态一起给出:客户端既要画模式指示,也要在审批之前
304
+ # 把计划正文渲染出来(``state.plan``)。
305
+ return {
306
+ "type": "plan_mode",
307
+ "reason": event.reason,
308
+ "planMode": event.state.to_wire(),
309
+ }
310
+ case ExtensionErrorEvent():
311
+ # 错误被隔离了,但订阅方要能看见:一条静默的失败等于没有这条规则。
312
+ return {
313
+ "type": "extension_error",
314
+ "extension": event.extension,
315
+ "event": event.event,
316
+ "error": event.error,
317
+ }
318
+ case ModelChangedEvent():
319
+ return {
320
+ "type": "model_changed",
321
+ "model": f"{event.model.provider}/{event.model.id}",
322
+ "previous": (
323
+ f"{event.previous.provider}/{event.previous.id}"
324
+ if event.previous is not None
325
+ else None
326
+ ),
327
+ }
328
+ case ThinkingLevelChangedEvent():
329
+ return {"type": "thinking_level_changed", "level": event.level}
330
+ case LoopGuardTriggeredEvent():
331
+ # 护栏事件的字段可选:``max_turns`` 没有工具名,``repeated_tool_call``
332
+ # 没有上限(上限是配置里的重复次数,已在 repeats 里体现)。空字段省略,
333
+ # 消费方按"缺省即不适用"读。
334
+ wire = {"type": "loop_guard_triggered", "guard": event.guard, "message": event.message}
335
+ if event.limit is not None:
336
+ wire["limit"] = event.limit
337
+ if event.used is not None:
338
+ wire["used"] = event.used
339
+ if event.tool_name is not None:
340
+ wire["toolName"] = event.tool_name
341
+ if event.repeats is not None:
342
+ wire["repeats"] = event.repeats
343
+ return wire
344
+ case CompletionEvidenceEvent():
345
+ return {
346
+ "type": "completion_evidence",
347
+ "modifiedPaths": list(event.modified_paths),
348
+ "verificationCommands": list(event.verification_commands),
349
+ "reminderSent": event.reminder_sent,
350
+ "unverified": event.unverified,
351
+ }
352
+ raise ValueError(f"未知的会话事件类型: {type(event).__name__}")
353
+
354
+
355
+ def transcript_message_to_wire(message: object) -> Any:
356
+ """转录消息 → wire。四种 LLM 角色交给 ``braid_ai.wire``,custom 走存储层映射。
357
+
358
+ RPC 的 ``get_messages`` 用同一个入口:一条消息在事件流、RPC 响应与会话文件里
359
+ 必须是同一种形状,否则客户端要写三套解析器。
360
+ """
361
+ if isinstance(message, (UserMessage, AssistantMessage, ToolResultMessage, SystemMessage)):
362
+ return message_to_wire(message)
363
+ return agent_message_to_wire(message) # type: ignore[arg-type]
364
+
365
+
366
+ def _assistant_event_to_wire(event: MessageUpdateEvent) -> dict[str, Any]:
367
+ """provider 事件 → wire:剥 ``partial``;``toolcall_start`` 摘出 ``id``/``toolName``。"""
368
+ if not isinstance(event.message, AssistantMessage):
369
+ raise ValueError("message_update message is not an assistant message")
370
+ inner = event.assistant_message_event
371
+ match inner:
372
+ case StartEvent():
373
+ return {"type": "start"}
374
+ case TextStartEvent():
375
+ return {"type": "text_start", "contentIndex": inner.content_index}
376
+ case TextDeltaEvent():
377
+ return {"type": "text_delta", "contentIndex": inner.content_index, "delta": inner.delta}
378
+ case TextEndEvent():
379
+ return {
380
+ "type": "text_end",
381
+ "contentIndex": inner.content_index,
382
+ "content": inner.content,
383
+ }
384
+ case ThinkingStartEvent():
385
+ return {"type": "thinking_start", "contentIndex": inner.content_index}
386
+ case ThinkingDeltaEvent():
387
+ return {
388
+ "type": "thinking_delta",
389
+ "contentIndex": inner.content_index,
390
+ "delta": inner.delta,
391
+ }
392
+ case ThinkingEndEvent():
393
+ return {
394
+ "type": "thinking_end",
395
+ "contentIndex": inner.content_index,
396
+ "content": inner.content,
397
+ }
398
+ case ToolCallStartEvent():
399
+ tool_call = inner.partial.content[inner.content_index]
400
+ if not isinstance(tool_call, ToolCall):
401
+ raise ValueError(
402
+ f"toolcall_start content at index {inner.content_index} is not a tool call"
403
+ )
404
+ return {
405
+ "type": "toolcall_start",
406
+ "contentIndex": inner.content_index,
407
+ "id": tool_call.id,
408
+ "toolName": tool_call.name,
409
+ }
410
+ case ToolCallDeltaEvent():
411
+ return {
412
+ "type": "toolcall_delta",
413
+ "contentIndex": inner.content_index,
414
+ "delta": inner.delta,
415
+ }
416
+ case ToolCallEndEvent():
417
+ return {
418
+ "type": "toolcall_end",
419
+ "contentIndex": inner.content_index,
420
+ "toolCall": _tool_call_to_wire(inner.tool_call),
421
+ }
422
+ case DoneEvent():
423
+ return {
424
+ "type": "done",
425
+ "reason": inner.reason,
426
+ "message": transcript_message_to_wire(inner.message),
427
+ }
428
+ case ErrorEvent():
429
+ return {
430
+ "type": "error",
431
+ "reason": inner.reason,
432
+ "error": transcript_message_to_wire(inner.error),
433
+ }
434
+ raise ValueError(f"未知的 assistant 事件类型: {type(inner).__name__}")
435
+
436
+
437
+ def _tool_call_to_wire(tool_call: ToolCall) -> dict[str, Any]:
438
+ """单个 ToolCall 块 → wire,与它在助手消息里的序列化形状一致。
439
+
440
+ ``braid_ai.wire`` 只暴露"整条消息"的序列化,没有单块入口;借一条只含该块的
441
+ 助手消息走同一条路径,保证 JSON 模式与会话文件对同一调用的编码永远一致。
442
+ """
443
+ wire = message_to_wire(AssistantMessage(timestamp=0, content=[tool_call], stop_reason="stop"))
444
+ blocks = wire["content"]
445
+ assert isinstance(blocks, list) and len(blocks) == 1
446
+ block = blocks[0]
447
+ assert isinstance(block, dict)
448
+ return block
449
+
450
+
451
+ def compaction_result_to_wire(result: CompactionResult) -> dict[str, Any]:
452
+ """``CompactionResult`` → wire(``compaction_end.result``)。"""
453
+ wire: dict[str, Any] = {
454
+ "summary": result.summary,
455
+ "firstKeptEntryId": result.first_kept_entry_id,
456
+ "tokensBefore": result.tokens_before,
457
+ }
458
+ if result.estimated_tokens_after is not None:
459
+ wire["estimatedTokensAfter"] = result.estimated_tokens_after
460
+ if result.usage is not None:
461
+ wire["usage"] = usage_to_wire(result.usage)
462
+ if result.details is not None:
463
+ wire["details"] = result.details
464
+ return wire
465
+
466
+
467
+ def _tool_result_to_wire(result: AgentToolResult) -> dict[str, Any]:
468
+ """``AgentToolResult`` → wire:模型可见内容 + 给 UI 的细节。
469
+
470
+ ``isError`` 在事件顶层(``tool_execution_end.isError``),不重复放进 result。
471
+ """
472
+ wire: dict[str, Any] = {
473
+ "content": content_to_wire(result.content),
474
+ "details": result.details if result.details is not None else {},
475
+ }
476
+ if result.structured_content is not None:
477
+ wire["structuredContent"] = result.structured_content
478
+ if result.usage is not None:
479
+ wire["usage"] = usage_to_wire(result.usage)
480
+ return wire
@@ -0,0 +1,217 @@
1
+ """进程收尾:终止信号与三种模式共用的关闭序列。
2
+
3
+ 关闭序列:注册 ``SIGTERM``(非 Windows 再加 ``SIGHUP``)→ 杀掉 detach 的子进程
4
+ → ``dispose`` 运行时 → flush stdout → 以 143 / 129 退出。把"信号"与"关闭序列"
5
+ 抽成一个模块,三种模式只决定"信号到达之后怎么打断自己的主循环"。
6
+
7
+ ## 退出码
8
+
9
+ ``128 + 信号编号``:``SIGTERM``(15) → 143,``SIGHUP``(1) → 129。这是 shell 与
10
+ 进程管理器共同认的约定。管道读端关闭时同样是 ``128 + 信号编号``,
11
+ 只不过那是 ``SIGPIPE``(13) → 141:写已经没人读的流,本质上就是被那个信号打断的。
12
+
13
+ ## 为什么不做"信号里直接动作"
14
+
15
+ ``loop.add_signal_handler`` 的回调排在事件循环里执行,不能 ``await``。所以回调只
16
+ 记录信号编号并唤醒等待者;真正的取消与落盘由各自的模式在主循环里完成——
17
+ ``dispose()`` 会 abort 当前 run 并等它空闲,转录里那条 ``aborted`` 助手消息因此
18
+ 能写完,客户端也还能收到 ``agent_settled``。
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import asyncio
24
+ import logging
25
+ import os
26
+ import signal
27
+ import sys
28
+ import threading
29
+ from collections.abc import Awaitable, Callable
30
+ from typing import TYPE_CHECKING, Final, NoReturn, TextIO
31
+
32
+ if TYPE_CHECKING:
33
+ from braid_coding_agent.session.agent_session import AgentSession
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ __all__ = [
38
+ "BROKEN_PIPE_EXIT_CODE",
39
+ "TERMINATION_SIGNALS",
40
+ "TerminationHandler",
41
+ "exit_code_for",
42
+ "exit_process",
43
+ "shutdown_session",
44
+ "silence_broken_pipe",
45
+ ]
46
+
47
+
48
+ def _termination_signals() -> tuple[int, ...]:
49
+ """要收尾的终止信号。Windows 没有 ``SIGHUP``,只处理 ``SIGTERM``。"""
50
+ numbers = [signal.SIGTERM]
51
+ hup = getattr(signal, "SIGHUP", None)
52
+ if hup is not None:
53
+ numbers.append(hup)
54
+ return tuple(numbers)
55
+
56
+
57
+ #: 需要走收尾流程的终止信号。
58
+ TERMINATION_SIGNALS: Final[tuple[int, ...]] = _termination_signals()
59
+
60
+
61
+ def exit_code_for(signum: int) -> int:
62
+ """信号驱动的退出码:``128 + 信号编号``(``SIGTERM`` → 143、``SIGHUP`` → 129)。"""
63
+ return 128 + signum
64
+
65
+
66
+ #: 管道读端关闭时的退出码:``128 + SIGPIPE``。Windows 没有 ``SIGPIPE``,按编号 13 算。
67
+ BROKEN_PIPE_EXIT_CODE: Final[int] = 128 + getattr(signal, "SIGPIPE", 13)
68
+
69
+
70
+ def silence_broken_pipe(stream: TextIO) -> None:
71
+ """把已经断开的输出流指到 ``/dev/null``,让剩下的写入落在空设备上。
72
+
73
+ Python 启动时把 ``SIGPIPE`` 设成忽略,写没人读的管道因此变成
74
+ ``BrokenPipeError``。异常本身可以捕获,麻烦在解释器退出时还会再刷一次缓冲:
75
+ 那一次发生在 ``sys.excepthook`` 之后,只能看到 ``Exception ignored`` 和一串
76
+ 追踪,退出码也被改写成 120。换掉文件描述符之后进程安静退出,退出码仍是调用方
77
+ 指定的那个(141)。做法取自 Python 文档 ``signal`` 模块里关于 ``SIGPIPE`` 的说明。
78
+ """
79
+ devnull = os.open(os.devnull, os.O_WRONLY)
80
+ os.dup2(devnull, stream.fileno())
81
+ os.close(devnull)
82
+
83
+
84
+ class TerminationHandler:
85
+ """把 ``SIGTERM`` / ``SIGHUP`` 变成一次可等待的退出请求。
86
+
87
+ 用法有两种:print 与 RPC 用 :meth:`wait` 跟主循环赛跑;REPL 起一个伴随任务
88
+ 等它,醒来后打断正在等待的输入。两种用法都靠同一个事实:信号到达时先记下
89
+ 编号,再唤醒等待者。
90
+
91
+ 装不上处理器(Windows、非主线程、事件循环不支持)时 :attr:`installed` 为假,
92
+ 调用方必须自己判断——静默地"以为装了信号处理器"会让进程在收到 SIGTERM 时
93
+ 直接消失。
94
+ """
95
+
96
+ def __init__(self) -> None:
97
+ self._signum: int | None = None
98
+ self._future: asyncio.Future[int] | None = None
99
+ self._installed: list[int] = []
100
+ self._loop: asyncio.AbstractEventLoop | None = None
101
+
102
+ @property
103
+ def installed(self) -> bool:
104
+ """是否真的装上了至少一个处理器。"""
105
+ return bool(self._installed)
106
+
107
+ @property
108
+ def signum(self) -> int | None:
109
+ """已经收到的终止信号编号;没有收到时为 ``None``。"""
110
+ return self._signum
111
+
112
+ @property
113
+ def exit_code(self) -> int:
114
+ """这次退出该用的码:没有信号时是 0。"""
115
+ return 0 if self._signum is None else exit_code_for(self._signum)
116
+
117
+ @property
118
+ def signal_name(self) -> str | None:
119
+ """信号名字,供日志与测试断言用。"""
120
+ if self._signum is None:
121
+ return None
122
+ return signal.Signals(self._signum).name
123
+
124
+ def install(self) -> None:
125
+ """注册处理器。装不上时保持未安装状态,不抛异常。"""
126
+ if self._installed:
127
+ return
128
+ if threading.current_thread() is not threading.main_thread():
129
+ logger.debug("非主线程,跳过终止信号处理器")
130
+ return
131
+ loop = asyncio.get_running_loop()
132
+ for signum in TERMINATION_SIGNALS:
133
+ try:
134
+ loop.add_signal_handler(signum, self._on_signal, signum)
135
+ except (NotImplementedError, RuntimeError, ValueError):
136
+ # Windows 的 Proactor 循环、已被别的库占用的循环都走这条分支。
137
+ logger.debug("事件循环不接受信号 %s 的处理器", signum)
138
+ continue
139
+ self._installed.append(signum)
140
+ self._loop = loop if self._installed else None
141
+
142
+ def close(self) -> None:
143
+ """摘掉处理器。进程即将退出时也该调用:测试里同一个循环会被复用。"""
144
+ loop = self._loop
145
+ self._loop = None
146
+ installed, self._installed = self._installed, []
147
+ if loop is None:
148
+ return
149
+ for signum in installed:
150
+ try:
151
+ loop.remove_signal_handler(signum)
152
+ except (NotImplementedError, RuntimeError, ValueError):
153
+ continue
154
+
155
+ async def wait(self) -> int:
156
+ """等到第一个终止信号,返回它的编号。
157
+
158
+ 只应在 :attr:`installed` 为真时等待:没装处理器就永远等不到。
159
+ """
160
+ if self._signum is not None:
161
+ return self._signum
162
+ if self._future is None:
163
+ self._future = asyncio.get_running_loop().create_future()
164
+ return await self._future
165
+
166
+ def _on_signal(self, signum: int) -> None:
167
+ if self._signum is None:
168
+ self._signum = signum
169
+ logger.info("收到 %s,开始收尾", self.signal_name)
170
+ if self._future is not None and not self._future.done():
171
+ self._future.set_result(signum)
172
+
173
+
174
+ async def shutdown_session(
175
+ session: AgentSession,
176
+ *,
177
+ unsubscribe: Callable[[], None] | None = None,
178
+ drain: Callable[[], Awaitable[None]] | None = None,
179
+ flush: Callable[[], None] | None = None,
180
+ ) -> None:
181
+ """三种模式共用的收尾序列:取消在跑的 run → 等后台任务 → 退订 → 刷输出。
182
+
183
+ ``dispose()`` 自己会 abort 在跑的 run 并等它空闲,那条 ``aborted`` 助手消息就是
184
+ 在这里写进会话文件的;跳过它,会话的最后一行就会是"半条 run"。
185
+
186
+ 退订排在 ``dispose`` **之后**是刻意的:收尾期间产生的 ``message_end`` /
187
+ ``turn_end`` / ``agent_settled`` 正是客户端等的那几条,先退订等于把它们丢掉。
188
+ 会话自己在 ``dispose`` 里也会清空监听器,所以这里的退订只对"早就该走"的
189
+ 订阅者有意义。
190
+
191
+ :param unsubscribe: 解除会话事件订阅。
192
+ :param drain: 模式自己的后台任务(RPC 的 run 任务)收尾。
193
+ :param flush: 输出流刷新。stdout 是协议通道,退出前不刷等于丢记录。
194
+ """
195
+ await session.dispose()
196
+ if drain is not None:
197
+ await drain()
198
+ if unsubscribe is not None:
199
+ unsubscribe()
200
+ if flush is not None:
201
+ flush()
202
+
203
+
204
+ def exit_process(code: int) -> NoReturn:
205
+ """收尾做完之后立刻结束进程,返回码交给调用它的进程管理器。
206
+
207
+ 只有 RPC 与 REPL 的信号退出用它。两者都阻塞在一个没有取消句柄的读上
208
+ (REPL 停在 ``prompt_toolkit`` 的读键或管道 ``readline``,RPC 停在守护读线程
209
+ 的 ``read1``),而且 RPC 那个守护线程还握着 ``sys.stdin`` 的缓冲锁——解释器
210
+ 收尾会撞上它并以 ``SIGABRT`` 结束。
211
+
212
+ 刷流出之后再 ``os._exit``:``asyncio.run`` 收尾还要 join 默认线程池,而那个
213
+ 线程可能正阻塞着——退出码不能等它。
214
+ """
215
+ sys.stdout.flush()
216
+ sys.stderr.flush()
217
+ os._exit(code)