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
+ """扩展的注册面与事件类型:内核不认识扩展,扩展只认识这个对象。
2
+
3
+ 分发与错误隔离在 :mod:`.runner`。
4
+
5
+ ## 三个扩展点,回答三个不同的问题
6
+
7
+ | 扩展点 | 形状 | 谁拥有结果 |
8
+ |---|---|---|
9
+ | 观察 | ``on("agent_end", ...)`` | 没人要结果,返回值被忽略 |
10
+ | 钩子 | ``on("before_tool_call", ...)`` | 返回值**参与决策**:阻断、改写、替换 |
11
+ | 注册 | ``register_tool`` / ``register_command`` | 名字进注册表,之后按名查找 |
12
+
13
+ 三者不能合并成一个 ``hook`` 概念:观察型回调可以并发、可以丢;改写型回调必须串行、
14
+ 必须能说出"我改了哪个字段";注册型回调根本不发生在运行期,它发生在装载期。
15
+
16
+ ## 为什么不做"继承 AgentSession 覆写方法"
17
+
18
+ 继承把内核和扩展焊死:扩展要覆写 ``prompt`` 就得复制一份编排逻辑,内核改一次
19
+ 它就得跟一次;两个扩展都要覆写时,Python 的方法解析顺序会替用户决定谁生效。
20
+ 注册 + 钩子把这件事变成数据:谁先注册谁先跑,顺序可读、可断言、可卸载。
21
+
22
+ ## 「扩展不能直接改 ``Agent.state``」
23
+
24
+ 本模块**没有**任何暴露 ``Agent`` 或 ``AgentSession`` 的方法。扩展能做的事都在
25
+ :class:`ExtensionAPI` 上:注册工具/命令、订阅事件、往会话里追加一条不进模型上下文
26
+ 的条目(:meth:`ExtensionAPI.append_entry`)。改转录、改工具集、改提示词都必须
27
+ 经由钩子的返回值回到内核,由内核决定要不要接受——这样"扩展做的事"永远是
28
+ 可审计的输入,而不是一个已经发生的副作用。
29
+
30
+ ## 只建模 7 个事件
31
+
32
+ 只保留 ``before_agent_start``、``context``、``before_tool_call``、
33
+ ``after_tool_call``、``session_before_compact``、``agent_end``、``session_shutdown``。
34
+ 其余事件各自依赖本仓库还没有的东西(provider 请求体、TUI、资源装载),
35
+ 写出"永远不会有实例的事件类型"只会让 README 比代码长。
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import re
41
+ from collections.abc import Awaitable, Callable, Sequence
42
+ from dataclasses import dataclass, field
43
+ from typing import TYPE_CHECKING, Any, ClassVar, Literal, Protocol, runtime_checkable
44
+
45
+ from braid_agent.tools import AgentTool
46
+ from braid_agent.types import AgentMessage
47
+ from braid_ai.types import ImageContent, JsonValue, TextContent, Usage
48
+ from braid_coding_agent.session.entries import CustomMessage, SessionEntry
49
+
50
+ if TYPE_CHECKING:
51
+ from braid_coding_agent.compaction.prepare import CompactionPreparation
52
+ from braid_coding_agent.compaction.summarize import CompactionResult
53
+
54
+ #: 可注册的事件名。取值就是分发时用的键,也是报错文本里的 ``event`` 字段。
55
+ type ExtensionEventName = Literal[
56
+ "before_agent_start",
57
+ "context",
58
+ "before_tool_call",
59
+ "after_tool_call",
60
+ "session_before_compact",
61
+ "agent_end",
62
+ "session_shutdown",
63
+ ]
64
+
65
+ #: 事件处理器。同步/异步均可;返回值按事件各自的语义解释(观察型忽略)。
66
+ #:
67
+ #: 用 ``Any`` 是刻意的:注册表是**异构**的(同一个 dict 里装七种签名),
68
+ #: 用 ``object`` 会让每个调用点都要 cast,用协议族又得为七个事件各写一个 Protocol
69
+ #: 再写一层重载。代价是这里丢掉了类型检查,收益是分发循环只有一份。
70
+ type ExtensionHandler = Callable[[Any], Awaitable[Any] | Any]
71
+
72
+ #: 命令处理器:收到参数原文(第一个空格之后的部分),做的动作由扩展决定。
73
+ type CommandHandler = Callable[[str], Awaitable[None] | None]
74
+
75
+ #: 往会话里追加一条自定义条目(不进模型上下文)。返回条目 id。
76
+ type AppendEntryAction = Callable[[str, JsonValue | None], str]
77
+
78
+
79
+ # ---------------------------------------------------------------------- 事件
80
+
81
+
82
+ @dataclass(slots=True, kw_only=True)
83
+ class BeforeAgentStartEvent:
84
+ """一次 run 开始之前。扩展可以改提示词分节、追加一条消息。
85
+
86
+ ``sections`` 是**当前**分节(已带标签,与转录里那条系统消息同形),
87
+ ``system_prompt`` 是把它重放成一段文本的结果——给只读的处理器看,
88
+ 改这份副本不会影响任何东西。
89
+ """
90
+
91
+ #: 触发这次 run 的原文。``message_type="custom"`` 时为空(由扩展消息触发)。
92
+ prompt: str | None = None
93
+ system_prompt: str = ""
94
+ sections: dict[str, str] = field(default_factory=dict[str, str])
95
+ message_type: Literal["user", "custom"] = "user"
96
+
97
+ type: ClassVar[Literal["before_agent_start"]] = "before_agent_start"
98
+
99
+
100
+ @dataclass(slots=True)
101
+ class BeforeAgentStartPatch:
102
+ """单个 ``before_agent_start`` 处理器想做的改动。
103
+
104
+ ``sections`` 是**逐节补丁**:写字符串表示替换该节,写 ``None`` 表示删除。
105
+ 后加载的扩展看到前面改过的结果,所以"两个扩展改同一节"由加载顺序决定。
106
+ ``message`` 会被追加到转录(在用户消息之前),进模型上下文。
107
+
108
+ 与 :class:`BeforeAgentStartResult` 分成两个类型,是因为它们回答两个不同的问题:
109
+ 处理器说的是"我要改哪几节",分发器说的是"合并之后提示词是什么"。用同一个类
110
+ 装两件事,读代码的人永远分不清手上这份是补丁还是全量。
111
+ """
112
+
113
+ sections: dict[str, str | None] | None = None
114
+ message: CustomMessage | None = None
115
+
116
+
117
+ @dataclass(slots=True)
118
+ class BeforeAgentStartResult:
119
+ """全部分发结束后的提示词与待追加消息(由 :mod:`.runner` 产出)。"""
120
+
121
+ #: 合并之后的全部分节(已带标签)。会话直接拿它去算转录增量。
122
+ sections: dict[str, str] = field(default_factory=dict[str, str])
123
+ #: 处理器追加的消息,按加载顺序。它们在用户消息之前进转录。
124
+ messages: list[AgentMessage] = field(default_factory=list[AgentMessage])
125
+
126
+
127
+ @dataclass(slots=True, kw_only=True)
128
+ class ContextEvent:
129
+ """一次模型请求之前,扩展看到的对话。
130
+
131
+ ``messages`` 里**没有系统消息**:提示词与工具声明属于内核,处理器改不到它们,
132
+ 也不需要小心保留它们(返回后内核会把系统消息放回去)。
133
+ """
134
+
135
+ messages: list[AgentMessage] = field(default_factory=list[AgentMessage])
136
+
137
+ type: ClassVar[Literal["context"]] = "context"
138
+
139
+
140
+ @dataclass(slots=True)
141
+ class ContextResult:
142
+ """``context`` 的返回值。``None`` 或 ``messages=None`` 表示不改。"""
143
+
144
+ messages: list[AgentMessage] | None = None
145
+
146
+
147
+ @dataclass(slots=True, kw_only=True)
148
+ class ToolCallEvent:
149
+ """一次工具调用已通过参数校验、即将执行。
150
+
151
+ ``args`` 是**已修补、已校验**的副本(模型原文在助手消息里)。钩子决定放不放行:
152
+ 返回 :class:`~braid_agent.types.BeforeToolCallResult` 表达"阻断/终止",返回 ``None``
153
+ 表示放行。
154
+ """
155
+
156
+ tool_name: str
157
+ tool_call_id: str
158
+ args: dict[str, JsonValue] = field(default_factory=dict[str, JsonValue])
159
+
160
+ type: ClassVar[Literal["before_tool_call"]] = "before_tool_call"
161
+
162
+
163
+ @dataclass(slots=True, kw_only=True)
164
+ class ToolResultEvent:
165
+ """一次工具执行完成、结果还没进转录。
166
+
167
+ ``content`` / ``details`` / ``structured_content`` / ``is_error`` 是**当前**的值:
168
+ 前一个处理器改过的话,后一个看到的是改过的。返回
169
+ :class:`~braid_agent.types.AfterToolCallResult` 做字段级覆盖;``None`` 表示不改。
170
+ """
171
+
172
+ tool_name: str
173
+ tool_call_id: str
174
+ args: dict[str, JsonValue] = field(default_factory=dict[str, JsonValue])
175
+ content: list[TextContent | ImageContent] = field(
176
+ default_factory=list[TextContent | ImageContent]
177
+ )
178
+ details: JsonValue = None
179
+ structured_content: JsonValue = None
180
+ is_error: bool = False
181
+ usage: Usage | None = None
182
+
183
+ type: ClassVar[Literal["after_tool_call"]] = "after_tool_call"
184
+
185
+
186
+ @dataclass(slots=True, kw_only=True)
187
+ class SessionBeforeCompactEvent:
188
+ """压缩即将开始。扩展可以取消它,或直接给出摘要。
189
+
190
+ ``preparation`` 是压缩的**唯一决策产物**(摘要哪些消息、从哪条开始保留):
191
+ 想改摘要范围就改这里的前提,想换摘要文本就返回 ``compaction``。
192
+ """
193
+
194
+ preparation: CompactionPreparation
195
+ branch_entries: list[SessionEntry]
196
+ custom_instructions: str | None = None
197
+ reason: Literal["manual", "threshold", "overflow"] = "manual"
198
+ will_retry: bool = False
199
+
200
+ type: ClassVar[Literal["session_before_compact"]] = "session_before_compact"
201
+
202
+
203
+ @dataclass(slots=True)
204
+ class SessionBeforeCompactResult:
205
+ """``session_before_compact`` 的返回值。``cancel`` 优先于 ``compaction``。"""
206
+
207
+ cancel: bool = False
208
+ compaction: CompactionResult | None = None
209
+
210
+
211
+ @dataclass(slots=True, kw_only=True)
212
+ class SessionShutdownEvent:
213
+ """会话即将释放。扩展在这里关掉自己开的资源(必须幂等)。"""
214
+
215
+ reason: Literal["quit"] = "quit"
216
+
217
+ type: ClassVar[Literal["session_shutdown"]] = "session_shutdown"
218
+
219
+
220
+ # ---------------------------------------------------------------------- 错误
221
+
222
+
223
+ @dataclass(slots=True, kw_only=True)
224
+ class ExtensionError:
225
+ """一次被隔离的扩展失败。
226
+
227
+ 它**不是**异常出口:扩展抛出的异常在这里被收成数据,主流程继续。三条信息缺一
228
+ 不可——``extension`` 说明是谁,``event`` 说明在哪个钩子上,``error`` 说明为什么。
229
+ """
230
+
231
+ extension: str
232
+ event: str
233
+ error: str
234
+
235
+ type: ClassVar[Literal["extension_error"]] = "extension_error"
236
+
237
+
238
+ type ExtensionErrorListener = Callable[[ExtensionError], Awaitable[None] | None]
239
+
240
+
241
+ # ------------------------------------------------------------------ 注册项
242
+
243
+
244
+ @dataclass(slots=True, kw_only=True)
245
+ class RegisteredCommand:
246
+ """扩展注册的 slash 命令。
247
+
248
+ ``description`` 只用于 ``/help``。``name`` 不含前导 ``/``:斜杠是"这是命令"的
249
+ 标记,不是名字的一部分。
250
+ """
251
+
252
+ name: str
253
+ handler: CommandHandler
254
+ description: str = ""
255
+ extension: str = ""
256
+
257
+ @property
258
+ def usage(self) -> str:
259
+ """``/help`` 里显示的用法串。"""
260
+ return f"/{self.name} [参数]"
261
+
262
+
263
+ # ------------------------------------------------------------------ 运行时
264
+
265
+
266
+ @dataclass(slots=True)
267
+ class ExtensionRuntime:
268
+ """扩展与会话之间的**动作**通道。
269
+
270
+ 注册发生在装载期(会话可能还不存在),动作只在运行期可用。用 ``None``
271
+ 表示未绑定,调用点直接报错,比桩函数少一层间接。
272
+
273
+ 为什么动作不放在 :class:`ExtensionAPI` 上直接持有会话对象:那样扩展就能顺着
274
+ ``api.session`` 摸到全部状态,"只能通过 API"这条约束会立刻失效。这里只开一个
275
+ 明确的洞:追加条目。
276
+ """
277
+
278
+ append_entry: AppendEntryAction | None = None
279
+
280
+
281
+ # ------------------------------------------------------------------ 扩展
282
+
283
+
284
+ @runtime_checkable
285
+ class Extension(Protocol):
286
+ """一个扩展:一个名字 + 一个激活函数。
287
+
288
+ ``activate`` 同步或异步均可。它在装载期被调用一次,参数是这个扩展专属的
289
+ :class:`ExtensionAPI`——注册项写进那个对象,因此"哪个扩展注册了什么"永远清楚,
290
+ 卸载时按对象整体摘掉,不需要反查。
291
+ """
292
+
293
+ name: str
294
+
295
+ def activate(self, api: ExtensionAPI) -> Awaitable[None] | None: ...
296
+
297
+
298
+ @dataclass(slots=True)
299
+ class InlineExtension:
300
+ """用函数定义的小扩展,省掉一个只有一个方法的类。
301
+
302
+ 它和模块扩展走完全相同的装载路径(:meth:`ExtensionRunner.load`),测试与示例
303
+ 因此不需要为"内联"和"文件"准备两套装配。
304
+ """
305
+
306
+ name: str
307
+ activate_fn: Callable[[ExtensionAPI], Awaitable[None] | None]
308
+
309
+ def activate(self, api: ExtensionAPI) -> Awaitable[None] | None:
310
+ return self.activate_fn(api)
311
+
312
+
313
+ # -------------------------------------------------------------------- API
314
+
315
+
316
+ @dataclass(slots=True)
317
+ class _RegisteredHandler:
318
+ """一条订阅记录。``active`` 是取消订阅的标记(见 :meth:`ExtensionAPI.on`)。"""
319
+
320
+ handler: ExtensionHandler
321
+ active: bool = True
322
+
323
+
324
+ class ExtensionAPI:
325
+ """交给扩展的注册面,同时是这个扩展的注册表。
326
+
327
+ 写入面是 :meth:`on` / :meth:`register_tool` / :meth:`register_command` /
328
+ :meth:`append_entry`;读取面(``handlers`` / ``tools`` / ``commands``)只给
329
+ :class:`~braid_coding_agent.extensions.runner.ExtensionRunner` 用。两者放在同一个
330
+ 对象上不是省事:注册项天然属于"注册它的那个扩展",拆成两个对象就要维护两张
331
+ 表之间的对应关系,卸载时还得两边一起清。
332
+ """
333
+
334
+ def __init__(self, name: str, runtime: ExtensionRuntime) -> None:
335
+ self._name = name
336
+ self._runtime = runtime
337
+ self._handlers: dict[str, list[_RegisteredHandler]] = {}
338
+ self._tools: dict[str, AgentTool] = {}
339
+ self._commands: dict[str, RegisteredCommand] = {}
340
+
341
+ @property
342
+ def name(self) -> str:
343
+ """扩展名。用于错误报告与命令归属。"""
344
+ return self._name
345
+
346
+ # ---------------------------------------------------------------- 订阅
347
+
348
+ def on(self, event: ExtensionEventName, handler: ExtensionHandler) -> Callable[[], None]:
349
+ """订阅一个事件,返回取消订阅的函数。
350
+
351
+ 同一个事件可以注册多个处理器,按注册顺序调用。取消订阅只影响**之后**的
352
+ 分发,正在进行的那一轮照旧跑完。
353
+ """
354
+ registration = _RegisteredHandler(handler=handler)
355
+ self._handlers.setdefault(event, []).append(registration)
356
+
357
+ def unsubscribe() -> None:
358
+ registration.active = False
359
+
360
+ return unsubscribe
361
+
362
+ # ---------------------------------------------------------------- 注册
363
+
364
+ def register_tool(self, tool: AgentTool) -> None:
365
+ """注册一个模型可调用的工具。
366
+
367
+ ``tool.parameters`` 必须是对象型 JSON Schema——校验靠它,声明也靠它。
368
+ 同名工具在本扩展内后注册者替换先注册者;跨扩展先加载者生效(由 runner 决定)。
369
+ """
370
+ if not tool.name:
371
+ raise ValueError("工具必须有非空名字")
372
+ require_parameters_schema(tool.name, tool.parameters)
373
+ self._tools[tool.name] = tool
374
+
375
+ def unregister_tool(self, name: str) -> bool:
376
+ """撤下一个本扩展注册的工具。返回是否真的移除了。
377
+
378
+ 典型调用方是 MCP:服务端可以随时改工具表(``tools/list_changed``),撤下的
379
+ 工具必须从可执行集合里消失,循环下一次请求才会告诉模型"这个工具没了"。
380
+ 注册表按扩展隔离,所以它只能撤掉自己注册的那一份。
381
+ """
382
+ return self._tools.pop(name, None) is not None
383
+
384
+ def register_command(
385
+ self, name: str, handler: CommandHandler, *, description: str = ""
386
+ ) -> None:
387
+ """注册一个 slash 命令。``name`` 不含前导 ``/``,只含小写字母、数字、``_``、``-``。"""
388
+ normalized = name.strip().lstrip("/")
389
+ if not normalized:
390
+ raise ValueError("命令必须有非空名字")
391
+ if not _COMMAND_NAME.fullmatch(normalized):
392
+ raise ValueError(f"非法命令名: {name}(只允许小写字母、数字、下划线、连字符)")
393
+ if normalized in self._commands:
394
+ raise ValueError(f"命令 /{normalized} 已被本扩展注册过")
395
+ self._commands[normalized] = RegisteredCommand(
396
+ name=normalized, handler=handler, description=description, extension=self._name
397
+ )
398
+
399
+ # ---------------------------------------------------------------- 动作
400
+
401
+ def append_entry(self, custom_type: str, data: JsonValue | None = None) -> str:
402
+ """往会话追加一条自定义条目,返回条目 id。
403
+
404
+ 这类条目**不进模型上下文**(与 ``CustomMessage`` 相反):它适合放"这次会话
405
+ 用过哪些临时文件"这种只给扩展自己看的状态。恢复会话时按分支读回来。
406
+ """
407
+ action = self._runtime.append_entry
408
+ if action is None:
409
+ raise RuntimeError("扩展动作在装载期不可用:append_entry 需要先绑定会话")
410
+ if not custom_type:
411
+ raise ValueError("自定义条目必须有非空 customType")
412
+ return action(custom_type, data)
413
+
414
+ # -------------------------------------------------------------- 读取面
415
+
416
+ def handlers(self, event: str) -> list[ExtensionHandler]:
417
+ """某个事件上仍然有效的处理器,按注册顺序。"""
418
+ return [
419
+ registration.handler
420
+ for registration in self._handlers.get(event, ())
421
+ if registration.active
422
+ ]
423
+
424
+ def tools(self) -> list[AgentTool]:
425
+ """已注册的工具,按注册顺序。"""
426
+ return list(self._tools.values())
427
+
428
+ def commands(self) -> list[RegisteredCommand]:
429
+ """已注册的命令,按注册顺序。"""
430
+ return list(self._commands.values())
431
+
432
+ def event_names(self) -> Sequence[str]:
433
+ """该扩展订阅了哪些事件(按名字排序),用于诊断输出。"""
434
+ return sorted(self._handlers)
435
+
436
+ def __repr__(self) -> str:
437
+ return (
438
+ f"ExtensionAPI({self._name!r}, tools={list(self._tools)}, "
439
+ f"commands={list(self._commands)}, events={self.event_names()})"
440
+ )
441
+
442
+
443
+ #: 合法的命令名:小写字母开头,只含小写字母、数字、下划线、连字符。
444
+ _COMMAND_NAME = re.compile(r"^[a-z][a-z0-9_-]*$")
445
+
446
+
447
+ def require_parameters_schema(tool_name: str, parameters: object) -> None:
448
+ """检查工具参数是对象型 JSON Schema。
449
+
450
+ 参数声明成 ``object`` 而不是 ``dict``:扩展可能从 JSON 配置里读参数、也可能
451
+ 绕过类型标注动态构造工具。校验必须在运行期真的发生,不能因为"类型标注说是 dict"
452
+ 就省掉。
453
+ """
454
+ if not isinstance(parameters, dict):
455
+ raise ValueError(f"工具 {tool_name} 的 parameters 必须是 JSON Schema 对象")
456
+
457
+
458
+ __all__ = [
459
+ "AppendEntryAction",
460
+ "BeforeAgentStartEvent",
461
+ "BeforeAgentStartPatch",
462
+ "BeforeAgentStartResult",
463
+ "CommandHandler",
464
+ "ContextEvent",
465
+ "ContextResult",
466
+ "Extension",
467
+ "ExtensionAPI",
468
+ "ExtensionError",
469
+ "ExtensionErrorListener",
470
+ "ExtensionEventName",
471
+ "ExtensionHandler",
472
+ "ExtensionRuntime",
473
+ "InlineExtension",
474
+ "RegisteredCommand",
475
+ "SessionBeforeCompactEvent",
476
+ "SessionBeforeCompactResult",
477
+ "SessionShutdownEvent",
478
+ "ToolCallEvent",
479
+ "ToolResultEvent",
480
+ ]