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,2706 @@
1
+ """AgentSession:把 Agent、会话树、提示词与模型选择组装成一个会话对象。
2
+
3
+ ## 三个容易写错的地方
4
+
5
+ **① ``AgentSession`` 里不能再实现一遍循环。**
6
+ 它只做编排:准备消息、写盘、转发事件。任何"再判断一次要不要继续"的代码都属于
7
+ :mod:`braid_agent.loop`,写在这里会让两处状态机慢慢分叉。
8
+
9
+ **② 落盘只挂在 ``message_end`` 上,别处都不写。**
10
+ 循环在第一次请求前就把待发消息(补丁、用户消息)走完 ``message_end``,所以"用户消息
11
+ 先落盘"不需要编排层另写一条路径;自己再预写一遍,反而要造一套去重机制来防止重复。
12
+ :class:`SessionRecorder` 只有一个 ``record`` 入口,写的就是事件里那份消息副本。
13
+
14
+ **③ ``agent_end`` 之后还有活。**
15
+ 订阅者可能正在写盘、重试可能要再发一次请求、压缩可能正在摘要。``agent_settled``
16
+ 放在 ``finally`` 里,且在所有 Agent 事件处理完之后,才是"这段工作真的结束了"。
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ import inspect
23
+ import logging
24
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
25
+ from dataclasses import dataclass, field, replace
26
+ from typing import TYPE_CHECKING, ClassVar, Literal, cast
27
+
28
+ from braid_agent.agent import Agent, default_convert_to_llm
29
+ from braid_agent.tools import AgentTool, tool_declarations
30
+ from braid_agent.types import (
31
+ AfterToolCallContext,
32
+ AfterToolCallResult,
33
+ AgentEndEvent,
34
+ AgentEvent,
35
+ AgentMessage,
36
+ BeforeToolCallContext,
37
+ BeforeToolCallResult,
38
+ MessageEndEvent,
39
+ MessageStartEvent,
40
+ ToolExecutionEndEvent,
41
+ ToolExecutionStartEvent,
42
+ )
43
+ from braid_ai.cancel import CancelToken
44
+ from braid_ai.models import Models, clamp_thinking_level
45
+ from braid_ai.overflow import is_context_overflow, is_recoverable_length
46
+ from braid_ai.retry import (
47
+ RetryBackoffCancelled,
48
+ RetryCallbacks,
49
+ RetryPolicy,
50
+ RetrySleepFn,
51
+ backoff_sleep,
52
+ is_retryable_assistant_error,
53
+ retry_delay_ms,
54
+ )
55
+ from braid_ai.transcript import get_current_system_message
56
+ from braid_ai.types import (
57
+ AssistantMessage,
58
+ Cost,
59
+ ImageContent,
60
+ Message,
61
+ Model,
62
+ ModelThinkingLevel,
63
+ SystemMessage,
64
+ TextContent,
65
+ ToolCall,
66
+ ToolResultMessage,
67
+ Usage,
68
+ UserMessage,
69
+ )
70
+ from braid_ai.utils.clock import Clock, SystemClock
71
+ from braid_ai.wire import content_text
72
+ from braid_coding_agent.checkpoint import CheckpointStore
73
+ from braid_coding_agent.compaction.prepare import (
74
+ DEFAULT_COMPACTION_SETTINGS,
75
+ CompactionPreparation,
76
+ CompactionSettings,
77
+ estimate_projected_context_tokens,
78
+ prepare_compaction,
79
+ )
80
+ from braid_coding_agent.compaction.summarize import (
81
+ CompactionResult,
82
+ SummarizationError,
83
+ )
84
+ from braid_coding_agent.compaction.summarize import (
85
+ compact as generate_compaction,
86
+ )
87
+ from braid_coding_agent.compaction.tokens import (
88
+ calculate_context_tokens,
89
+ estimate_context_tokens,
90
+ estimate_tokens,
91
+ should_compact,
92
+ )
93
+ from braid_coding_agent.compaction.tool_results import plan_tool_result_cleanup
94
+ from braid_coding_agent.extensions import (
95
+ BeforeAgentStartEvent,
96
+ ExtensionError,
97
+ ExtensionRunner,
98
+ SessionBeforeCompactEvent,
99
+ SessionShutdownEvent,
100
+ render_prompt_sections,
101
+ )
102
+ from braid_coding_agent.observability.collector import ObservabilityCollector
103
+ from braid_coding_agent.permissions.engine import PermissionEngine
104
+ from braid_coding_agent.permissions.engine import build_request as build_permission_request
105
+ from braid_coding_agent.prompt.context_files import ContextFile
106
+ from braid_coding_agent.prompt.project_context import ProjectContext
107
+ from braid_coding_agent.prompt.system_prompt import (
108
+ Skill,
109
+ build_system_prompt_sections,
110
+ diff_system_prompt_sections,
111
+ )
112
+ from braid_coding_agent.session.context_breakdown import (
113
+ ContextBreakdown,
114
+ build_context_breakdown,
115
+ )
116
+ from braid_coding_agent.session.entries import (
117
+ CompactionEntry,
118
+ ContextEditEntry,
119
+ ContextReplacement,
120
+ CustomMessage,
121
+ ProjectedMessage,
122
+ SessionMessageEntry,
123
+ StorableMessage,
124
+ ms_from_iso,
125
+ )
126
+ from braid_coding_agent.session.evidence import RunEvidence
127
+ from braid_coding_agent.session.manager import SessionManager
128
+ from braid_coding_agent.session.plan import PlanState, PlanStore
129
+ from braid_coding_agent.session.plan_mode import (
130
+ PlanMode,
131
+ PlanModeReason,
132
+ PlanModeState,
133
+ )
134
+ from braid_coding_agent.session.projection import ModelRef, SessionProjection
135
+ from braid_coding_agent.session.status import (
136
+ CONTEXT_WARNING_RATIO,
137
+ ContextStatus,
138
+ SessionTotals,
139
+ )
140
+ from braid_coding_agent.skills.loader import SkillDocument, SkillsLoader, check_skill_access
141
+ from braid_coding_agent.tools.output_store import ToolOutputStore
142
+ from braid_coding_agent.verify.runner import VerifyBudget
143
+
144
+ if TYPE_CHECKING:
145
+ # 配置层在导入期会反向拉进本包(config → compaction.prepare → session 包),
146
+ # 运行期再导入就会撞上"模块只执行了一半"。注解延迟求值,这里只借类型。
147
+ from braid_coding_agent.config import AgentConfig
148
+ from braid_coding_agent.credentials import Credentials
149
+ from braid_coding_agent.sandbox.operations import SandboxOperations
150
+
151
+ logger = logging.getLogger(__name__)
152
+
153
+ #: 一次输入被接收的方式。``queued`` 表示已排队,等回合边界注入。
154
+ type QueuedDisposition = Literal["queued"]
155
+
156
+ #: 思考级别的全部合法取值,用于把会话文件里的字符串收窄成类型。
157
+ _THINKING_LEVELS: frozenset[str] = frozenset(
158
+ {"off", "minimal", "low", "medium", "high", "xhigh", "max"}
159
+ )
160
+
161
+
162
+ # ------------------------------------------------------------------ 用量统计
163
+
164
+
165
+ @dataclass(slots=True)
166
+ class SessionUsage:
167
+ """整段会话的累计用量。只统计**助手消息**自报的数字。
168
+
169
+ 工具结果里也可能带 ``usage``(工具内部调了模型),那部分不计入主对话:
170
+ 两笔账混在一起,UI 上"这次对话花了多少"就没有意义了。
171
+ """
172
+
173
+ input: int = 0
174
+ output: int = 0
175
+ cache_read: int = 0
176
+ cache_write: int = 0
177
+ total_tokens: int = 0
178
+ cost: Cost = field(default_factory=Cost)
179
+
180
+ @property
181
+ def cache_hit_rate(self) -> float:
182
+ """缓存读在全部输入 token 里的占比。
183
+
184
+ 分母是"要付输入价的部分":新读的输入、从缓存读的、写进缓存的。三者是一份
185
+ 请求前缀的三种归宿,命中率才有意义;把输出算进来会让长回答的会话看起来缓存
186
+ 更差。
187
+ """
188
+ prompt = self.input + self.cache_read + self.cache_write
189
+ return self.cache_read / prompt if prompt else 0.0
190
+
191
+ def add(self, usage: Usage) -> None:
192
+ """累加一条助手消息的用量。"""
193
+ self.input += usage.input
194
+ self.output += usage.output
195
+ self.cache_read += usage.cache_read
196
+ self.cache_write += usage.cache_write
197
+ self.total_tokens += usage.total_tokens
198
+ self.cost = Cost(
199
+ input=self.cost.input + usage.cost.input,
200
+ output=self.cost.output + usage.cost.output,
201
+ cache_read=self.cost.cache_read + usage.cost.cache_read,
202
+ cache_write=self.cost.cache_write + usage.cost.cache_write,
203
+ total=self.cost.total + usage.cost.total,
204
+ )
205
+
206
+
207
+ # -------------------------------------------------------------------- 落盘
208
+
209
+
210
+ class SessionRecorder:
211
+ """把 ``message_end`` 到达的消息写进会话,并累计用量。
212
+
213
+ 只有一个入口。落盘挂在 ``message_end`` 上而不是挂在"调用方手里的对象"上,有两个
214
+ 理由,都是 :mod:`braid_agent.loop` 已经保证的性质:
215
+
216
+ - **用户消息天然先于请求落盘。** 循环在发第一次请求之前,就把全部待发消息
217
+ (提示词补丁、用户消息)以 ``message_start``/``message_end`` 走完一遍
218
+ (``run_agent_loop`` 的开头)。所以进程死在长请求中途时,用户的话已经在文件里了。
219
+ - **文件顺序等于转录顺序。** 补丁消息、工具补丁、用户消息按同一顺序进转录、
220
+ 进事件流、进文件,不存在"预写盘的消息插到别人前面"的排序问题。
221
+
222
+ 循环发事件时会 ``deepcopy`` 一份消息(订阅者改坏事件里的消息不能影响转录),所以
223
+ 这里写盘的是事件的副本;``SessionManager`` 存的是值,副本与原件等价。
224
+ """
225
+
226
+ def __init__(self, session: SessionManager) -> None:
227
+ self._session = session
228
+ self.usage = SessionUsage()
229
+
230
+ def record(self, message: AgentMessage) -> str | None:
231
+ """``message_end`` 入口:能存储的消息写一条并返回条目 id,其余跳过。
232
+
233
+ 返回的条目 id 供重试/溢出恢复建立"消息对象 → 会话条目"的映射:
234
+ 省略一次失败尝试时,要按条目写 ``context_edit``。
235
+ """
236
+ storable = _storable(message)
237
+ if storable is None:
238
+ # 扩展自定义角色没有对应的存储形态:它们要么先被折成 custom,
239
+ # 要么本来就不该进历史。跳过比猜一个落盘形状安全。
240
+ return None
241
+ entry_id = self._session.append_message(storable)
242
+ if isinstance(storable, AssistantMessage):
243
+ self.usage.add(storable.usage)
244
+ return entry_id
245
+
246
+
247
+ def _storable(message: AgentMessage) -> StorableMessage | None:
248
+ """转录消息里哪些能直接进 ``message`` 条目。"""
249
+ if isinstance(
250
+ message, (SystemMessage, UserMessage, AssistantMessage, ToolResultMessage, CustomMessage)
251
+ ):
252
+ return message
253
+ return None
254
+
255
+
256
+ # ------------------------------------------------------------------ 提示词
257
+
258
+
259
+ @dataclass(slots=True)
260
+ class PromptBuilder:
261
+ """把"当前应该发给模型的提示词"算成分节,并给出转录增量。
262
+
263
+ 提示词是**可重放的数据**,不是对象上的一个字符串:分节存在系统消息里,
264
+ 变化时只发一条按名字替换的补丁。这个类负责两件事:
265
+
266
+ - :meth:`baseline`:空会话的第一条系统消息(全部分节 + 工具声明);
267
+ - :meth:`patch_for`:已有转录时,算出"模型手上那版"到"这次要发的那版"的差。
268
+
269
+ 工具声明只在 ``baseline`` 里出现。之后的增删由
270
+ :func:`braid_agent.loop.declare_tool_changes` 在请求前按可执行集合算——两处都算会让
271
+ 同一回合出现两条工具补丁,第二条把第一条覆盖成空。
272
+ """
273
+
274
+ cwd: str
275
+ tools: Sequence[AgentTool]
276
+ tool_snippets: Mapping[str, str]
277
+ tool_guidelines: Mapping[str, Sequence[str]]
278
+ context_files: Sequence[ContextFile] = ()
279
+ skills: Sequence[Skill] = ()
280
+ custom_prompt: str | None = None
281
+ append_system_prompt: str = ""
282
+ clock: Clock = field(default_factory=SystemClock)
283
+
284
+ def tool_list(self) -> list[AgentTool]:
285
+ """当前可执行工具,顺序即声明顺序。给 ``agent.state.tools`` 用。"""
286
+ return list(self.tools)
287
+
288
+ def sections(self) -> dict[str, str]:
289
+ """按固定顺序渲染全部分节(已带标签)。"""
290
+ return build_system_prompt_sections(
291
+ cwd=self.cwd,
292
+ selected_tools=[tool.name for tool in self.tools],
293
+ tool_snippets=self.snippets(),
294
+ tool_guidelines=self.tool_guidelines,
295
+ context_files=self.context_files,
296
+ skills=self.skills,
297
+ custom_prompt=self.custom_prompt,
298
+ append_system_prompt=self.append_system_prompt,
299
+ )
300
+
301
+ def snippets(self) -> dict[str, str]:
302
+ """工具名 → 一句话介绍。没登记介绍的工具用描述首行兜底。
303
+
304
+ 兜底是为扩展注册的工具准备的:它们的声明里有 ``description``,但没人
305
+ 会给它们写 ``tool_snippets``。没有兜底时,模型看得到工具声明却看不到提示词里
306
+ 的工具清单,两处对不上。
307
+ """
308
+ snippets = dict(self.tool_snippets)
309
+ for tool in self.tools:
310
+ if tool.name in snippets:
311
+ continue
312
+ description = tool.description.strip()
313
+ first_line = description.splitlines()[0] if description else ""
314
+ if first_line:
315
+ snippets[tool.name] = first_line
316
+ return snippets
317
+
318
+ def baseline(self) -> SystemMessage:
319
+ """空会话的第一条系统消息:全部分节 + 全部工具声明。"""
320
+ sections: dict[str, str | None] = {name: text for name, text in self.sections().items()}
321
+ return SystemMessage(
322
+ timestamp=self.clock.now_ms(),
323
+ content="",
324
+ sections=sections,
325
+ tools_added=tool_declarations(self.tools) or None,
326
+ )
327
+
328
+ def patch_for(
329
+ self,
330
+ messages: Sequence[AgentMessage],
331
+ sections: Mapping[str, str] | None = None,
332
+ ) -> SystemMessage | None:
333
+ """算出要追加的系统消息补丁;没有变化时返回 ``None``。
334
+
335
+ ``previous`` 从**转录重放**得到,不是"上一轮我们算出来的那版":中间可能经过
336
+ 压缩、分支、另一条写入路径,只有转录是事实。
337
+
338
+ :param sections: 本次要发的分节。``None`` 表示用 :meth:`sections` 自己算;
339
+ 扩展改过提示词时由调用方传入合并后的结果。
340
+ """
341
+ previous = _current_sections(messages)
342
+ current = self.sections() if sections is None else dict(sections)
343
+ patch = diff_system_prompt_sections(previous, current)
344
+ if patch is None:
345
+ return None
346
+ return SystemMessage(timestamp=self.clock.now_ms(), content="", sections=patch)
347
+
348
+
349
+ def _current_sections(messages: Sequence[AgentMessage]) -> dict[str, str | None]:
350
+ """重放转录得到的当前分节;没有任何系统消息时是空表。
351
+
352
+ 用 :func:`braid_agent.agent.default_convert_to_llm` 过滤而不是自己写一份:分节只存在于
353
+ 系统消息里,两种过滤对它等价,而共用同一个函数能保证"重放用的转录"和"发请求用的
354
+ 转录"是同一份。
355
+ """
356
+ message = get_current_system_message(default_convert_to_llm(list(messages)))
357
+ return dict(message.sections or {}) if message is not None else {}
358
+
359
+
360
+ # -------------------------------------------------------------------- 事件
361
+
362
+
363
+ @dataclass(slots=True, kw_only=True)
364
+ class AgentSettledEvent:
365
+ """整次 run 真正结束:``agent_end`` 的订阅者已经跑完,重试/压缩等后续工作也没了。
366
+
367
+ 与 ``agent_end`` 的区别是这一片最容易被误解的地方:``agent_end`` 是**循环**的
368
+ 最后一个事件,``agent_settled`` 是**会话**的最后一个事件。中间可能还有一次重试、
369
+ 一次压缩、一批队列消息。
370
+ """
371
+
372
+ aborted: bool = False
373
+ #: 整段会话的累计用量快照。放在收尾事件里,客户端不必自己累加 message_end。
374
+ usage: SessionTotals | None = None
375
+
376
+ type: ClassVar[Literal["agent_settled"]] = "agent_settled"
377
+
378
+
379
+ @dataclass(slots=True, kw_only=True)
380
+ class QueueUpdateEvent:
381
+ """待注入消息变了。``steering`` 与 ``follow_up`` 是文本快照,不是消息对象。"""
382
+
383
+ steering: list[str] = field(default_factory=list[str])
384
+ follow_up: list[str] = field(default_factory=list[str])
385
+
386
+ type: ClassVar[Literal["queue_update"]] = "queue_update"
387
+
388
+
389
+ @dataclass(slots=True, kw_only=True)
390
+ class ModelChangedEvent:
391
+ """当前模型变了。``previous`` 为 ``None`` 表示之前没有选中任何模型。"""
392
+
393
+ model: Model
394
+ previous: Model | None = None
395
+
396
+ type: ClassVar[Literal["model_changed"]] = "model_changed"
397
+
398
+
399
+ @dataclass(slots=True, kw_only=True)
400
+ class ThinkingLevelChangedEvent:
401
+ """当前思考级别变了。``level`` 是**钳制之后**的实际值。"""
402
+
403
+ level: ModelThinkingLevel
404
+ previous: ModelThinkingLevel
405
+
406
+ type: ClassVar[Literal["thinking_level_changed"]] = "thinking_level_changed"
407
+
408
+
409
+ @dataclass(slots=True, kw_only=True)
410
+ class AutoRetryStartEvent:
411
+ """一次自动重试已排定:第 ``attempt`` 次(1 起),退避 ``delay_ms`` 后重发。
412
+
413
+ ``error_message`` 是触发重试的那次错误文本。事件发出时失败尝试还**没有**
414
+ 从模型投影里省略;退避结束、下一次请求发出前才省略。
415
+ """
416
+
417
+ attempt: int
418
+ max_attempts: int
419
+ delay_ms: int
420
+ error_message: str
421
+
422
+ type: ClassVar[Literal["auto_retry_start"]] = "auto_retry_start"
423
+
424
+
425
+ @dataclass(slots=True, kw_only=True)
426
+ class AutoRetryEndEvent:
427
+ """重试序列结束,恰好发一次。
428
+
429
+ ``success=True``:某次重试拿到了正常响应,``final_error`` 为空;
430
+ ``success=False``:预算耗尽、取消或不可恢复,``final_error`` 带最后一次的
431
+ 错误文本(取消时是 "Retry cancelled")。``attempt`` 是最后一次重试的序号。
432
+ """
433
+
434
+ success: bool
435
+ attempt: int
436
+ final_error: str | None = None
437
+
438
+ type: ClassVar[Literal["auto_retry_end"]] = "auto_retry_end"
439
+
440
+
441
+ @dataclass(slots=True, kw_only=True)
442
+ class AgentEndWithRetryEvent(AgentEndEvent):
443
+ """``agent_end`` 加上会话层的重试预告。
444
+
445
+ ``will_retry=True`` 表示低层 run 刚结束,但紧接着有一次自动重试——这与
446
+ ``agent_settled`` 的区别最容易读错:``agent_end`` 关闭的是**低层 run**,
447
+ 重试、溢出恢复、压缩这些会话级后续工作之后才结束。
448
+ """
449
+
450
+ will_retry: bool = False
451
+
452
+
453
+ @dataclass(slots=True)
454
+ class OverflowRecoveryRequest:
455
+ """交给溢出恢复钩子的全部信息。
456
+
457
+ 钩子接住这个请求,产出一条压缩条目并返回 ``True``;返回 ``True`` 表示模型上下文
458
+ 已经变小、可以原样重试,返回 ``False`` 或抛异常都视为恢复失败。
459
+ """
460
+
461
+ message: AssistantMessage
462
+ #: ``error_overflow``:显式报错;``silent_overflow``:成功响应但用量超窗;
463
+ #: ``truncated_length``:``length`` 停止且输出低于期望。
464
+ kind: Literal["error_overflow", "silent_overflow", "truncated_length"]
465
+ #: ``True`` 表示恢复后要续跑被打断的回合;``False`` 表示只是为下一次
466
+ #: 请求压缩(成功响应上的静默溢出无法从尾部续跑)。
467
+ will_retry: bool
468
+
469
+
470
+ #: 溢出恢复钩子:检测到溢出时调用一次,返回是否压缩成功。
471
+ type OverflowRecoveryHook = Callable[[OverflowRecoveryRequest], Awaitable[bool] | bool]
472
+
473
+ #: 压缩的触发原因。
474
+ type CompactionReason = Literal["manual", "threshold", "overflow"]
475
+
476
+
477
+ @dataclass(slots=True, kw_only=True)
478
+ class CompactionStartEvent:
479
+ """压缩开始。``reason`` 说明是谁触发的。"""
480
+
481
+ reason: CompactionReason
482
+
483
+ type: ClassVar[Literal["compaction_start"]] = "compaction_start"
484
+
485
+
486
+ @dataclass(slots=True, kw_only=True)
487
+ class CompactionEndEvent:
488
+ """压缩结束。
489
+
490
+ 成功时 ``result`` 带完整的 :class:`CompactionResult`;取消时 ``aborted=True``
491
+ 且 ``result`` 为空;失败时 ``error_message`` 说明原因。``will_retry=True``
492
+ 表示压缩之后会自动续跑被打断的回合(溢出恢复路径)。
493
+ """
494
+
495
+ reason: CompactionReason
496
+ result: CompactionResult | None = None
497
+ aborted: bool = False
498
+ will_retry: bool = False
499
+ error_message: str | None = None
500
+
501
+ type: ClassVar[Literal["compaction_end"]] = "compaction_end"
502
+
503
+
504
+ @dataclass(slots=True, kw_only=True)
505
+ class ToolResultCleanupEvent:
506
+ """更早的大块工具结果被替换成一行摘要。
507
+
508
+ ``chars_before`` 与 ``chars_after`` 是这一轮被替换条目的原文字符数合计与替换文本
509
+ 的字符数合计;``tokens`` 与 ``context_window`` 是触发时的上下文占用与窗口,界面
510
+ 据此说明"为什么现在清理"。它只在真的写了条目时发出。
511
+ """
512
+
513
+ cleared: int
514
+ chars_before: int
515
+ chars_after: int
516
+ tokens: int
517
+ context_window: int
518
+
519
+ type: ClassVar[Literal["tool_result_cleanup"]] = "tool_result_cleanup"
520
+
521
+
522
+ @dataclass(slots=True, kw_only=True)
523
+ class SummarizationRetryScheduledEvent:
524
+ """摘要请求将被重试(瞬时错误 + 退避中)。"""
525
+
526
+ attempt: int
527
+ max_attempts: int
528
+ delay_ms: int
529
+ error_message: str
530
+
531
+ type: ClassVar[Literal["summarization_retry_scheduled"]] = "summarization_retry_scheduled"
532
+
533
+
534
+ @dataclass(slots=True, kw_only=True)
535
+ class SummarizationRetryAttemptStartEvent:
536
+ """一次摘要重试请求真正发出。"""
537
+
538
+ source: Literal["compaction"] = "compaction"
539
+ reason: CompactionReason | None = None
540
+
541
+ type: ClassVar[Literal["summarization_retry_attempt_start"]] = (
542
+ "summarization_retry_attempt_start"
543
+ )
544
+
545
+
546
+ @dataclass(slots=True, kw_only=True)
547
+ class SummarizationRetryFinishedEvent:
548
+ """摘要重试序列收尾(成功、耗尽或取消都恰好发一次)。"""
549
+
550
+ type: ClassVar[Literal["summarization_retry_finished"]] = "summarization_retry_finished"
551
+
552
+
553
+ @dataclass(slots=True, kw_only=True)
554
+ class ExtensionErrorEvent:
555
+ """一个扩展在某个钩子上失败了,失败已被隔离。
556
+
557
+ 它不是错误路径的替代品:主流程继续,事件只是让 UI / RPC 客户端知道"你以为生效
558
+ 的那条规则可能没生效"。``extension`` 是扩展名,``event`` 是钩子名。
559
+ """
560
+
561
+ extension: str
562
+ event: str
563
+ error: str
564
+
565
+ type: ClassVar[Literal["extension_error"]] = "extension_error"
566
+
567
+
568
+ class CompactionCancelledByExtension(SummarizationError):
569
+ """扩展取消了这次压缩。
570
+
571
+ 它不是失败:与用户取消走同一条收尾路径(``CompactionEndEvent(aborted=True)``),
572
+ 区别只在谁按的停止键。会话层据此决定事件字段,调用方据此决定要不要重试。
573
+ """
574
+
575
+
576
+ @dataclass(slots=True, kw_only=True)
577
+ class CompletionEvidenceEvent:
578
+ """一次逻辑 run 的完成证据。只在**这次 run 改过文件**时发出。
579
+
580
+ ``unverified`` 为真表示"改了文件、但一条验证命令都没跑"。它不是错误:改动可能
581
+ 本来就是文档或配置,验证也确实可能无从跑起。它的用途是让用户与上层知道
582
+ "这一次的结论没有执行证据",模型自己在最终回答里应当写明。
583
+
584
+ ``reminder_sent`` 说明会话是否已经为此追问过模型一次。追问只发生一次:模型第二次
585
+ 仍然没有跑检查时,会话不再循环追问——那样会把"提醒"变成另一条无限循环。
586
+ """
587
+
588
+ #: 本次 run 成功写入/编辑过的路径,按第一次出现的顺序。
589
+ modified_paths: list[str]
590
+ #: 本次 run 执行过的验证命令原文,按执行顺序。
591
+ verification_commands: list[str]
592
+ #: 是否已经因为"有改动、没验证"追问过模型。
593
+ reminder_sent: bool
594
+ #: 有改动、却没有验证命令。
595
+ unverified: bool
596
+
597
+ type: ClassVar[Literal["completion_evidence"]] = "completion_evidence"
598
+
599
+
600
+ @dataclass(slots=True, kw_only=True)
601
+ class ContextWarningEvent:
602
+ """上下文接近自动压缩触发线。
603
+
604
+ ``remaining_percent`` 的分母是触发线本身,不是整个上下文窗口:用户要知道的是
605
+ "离下一次压缩还剩多少可用空间"。这条事件只播报事实,不改变压缩策略;
606
+ 阈值、预留与触发时机全部由 :class:`~braid_coding_agent.compaction.prepare.CompactionSettings`
607
+ 决定。
608
+ """
609
+
610
+ context_window: int
611
+ tokens: int
612
+ threshold: int
613
+ remaining_tokens: int
614
+ remaining_percent: float
615
+
616
+ type: ClassVar[Literal["context_warning"]] = "context_warning"
617
+
618
+
619
+ @dataclass(slots=True, kw_only=True)
620
+ class PlanUpdateEvent:
621
+ """计划真的变了:版本号前进了一步。
622
+
623
+ 只在 ``update_plan`` 工具**成功执行**且内容与上一版不同时发出。重复提交同一份
624
+ 表、被参数校验或权限拒绝的调用都不发事件——界面不该为一个没有发生的变化重画。
625
+ 计划本身存树上的 ``custom`` 条目(见 :mod:`.plan`),事件里带的是**派生状态**,
626
+ 客户端重放会话文件也能算出同样的表。
627
+ """
628
+
629
+ state: PlanState
630
+
631
+ type: ClassVar[Literal["plan_update"]] = "plan_update"
632
+
633
+
634
+ @dataclass(slots=True, kw_only=True)
635
+ class PlanModeEvent:
636
+ """规划模式状态变了:进入、提交计划、批准、要求修改或退出。
637
+
638
+ ``state`` 带上完整状态(含计划全文),因为界面要在审批之前把计划显示出来:
639
+ 审批提示只说"以上计划是否批准",计划正文由这条事件负责呈现与留档。
640
+ """
641
+
642
+ state: PlanModeState
643
+ reason: PlanModeReason
644
+
645
+ type: ClassVar[Literal["plan_mode"]] = "plan_mode"
646
+
647
+
648
+ #: 会话对外发出的事件:Agent 事件原样转发,外加会话级事件、重试事件与压缩事件。
649
+ type SessionEvent = (
650
+ AgentEvent
651
+ | AgentEndWithRetryEvent
652
+ | AgentSettledEvent
653
+ | AutoRetryStartEvent
654
+ | AutoRetryEndEvent
655
+ | CompactionEndEvent
656
+ | CompactionStartEvent
657
+ | CompletionEvidenceEvent
658
+ | ContextWarningEvent
659
+ | ExtensionErrorEvent
660
+ | PlanModeEvent
661
+ | PlanUpdateEvent
662
+ | QueueUpdateEvent
663
+ | ModelChangedEvent
664
+ | SummarizationRetryAttemptStartEvent
665
+ | SummarizationRetryFinishedEvent
666
+ | SummarizationRetryScheduledEvent
667
+ | ThinkingLevelChangedEvent
668
+ | ToolResultCleanupEvent
669
+ )
670
+
671
+ #: 会话订阅者。同步/异步均可,按注册顺序逐个 ``await``。
672
+ type SessionListener = Callable[[SessionEvent], Awaitable[None] | None]
673
+
674
+
675
+ # ------------------------------------------------------------------ 会话对象
676
+
677
+
678
+ class AgentSession:
679
+ """一个可持久化、可恢复、可切换模型的会话。
680
+
681
+ 构造即完成三件事:恢复或写入转录起点、把可执行工具装到 Agent 上、订阅 Agent 事件。
682
+ 之后所有写入都通过 Agent 的 ``prompt`` / ``steer`` / ``follow_up`` 发生,本对象不
683
+ 另开一条通往模型的路径。
684
+
685
+ :param agent: 已经接好 ``stream_fn`` 与 ``convert_to_llm`` 的 Agent。
686
+ ``stream_fn`` 通常就是 ``Models.stream``。
687
+ :param session: 会话树。空会话会被写入一条系统消息基线。
688
+ :param models: 模型目录,``set_model`` 用它把 ``provider/model`` 解析成对象;
689
+ 恢复会话时也用它找回当时记录的模型。
690
+ :param prompt_builder: 提示词分节与工具声明的来源。
691
+ :param clock: 用户消息与系统补丁的时间戳来源。
692
+ :param retry_policy: 自动重试策略。``None``(缺省)表示关闭:失败的助手消息
693
+ 原样结束本次 run,不重试。传入策略后,可重试的瞬时错误(限流、过载、
694
+ 网络中断)按指数退避自动重发。
695
+ :param overflow_recovery: 溢出恢复钩子。``None`` 且未提供 ``compaction_settings``
696
+ 时,检测到溢出也不恢复。``compaction_settings`` 提供后,内建压缩成为标准
697
+ 恢复实现;显式钩子仍优先。
698
+ :param compaction_settings: 压缩设置。提供后启用三件事:请求前/run 后的
699
+ 阈值检查(自动压缩)、溢出时的内建压缩恢复、请求上下文改由会话投影
700
+ 提供。``None``(缺省)表示整个压缩系统不参与本会话。
701
+ :param extensions: 扩展运行时。提供后启用四件事:扩展注册的工具进入可执行集合、
702
+ ``before_agent_start`` 改提示词、``context`` 改对话、工具执行前后两个钩子
703
+ (阻断/改写)、``session_before_compact`` 取消或接管压缩。``None``(缺省)
704
+ 表示本会话不认识扩展机制。
705
+ :param retry_sleep: 退避睡眠实现,测试注入假时钟用;缺省用可取消的真实睡眠。
706
+ :param tool_outputs: ``bash`` 完整输出的落盘目录。内存会话在 :meth:`dispose` 时
707
+ 整体删除,落盘会话把文件留给保留期(见 :mod:`braid_coding_agent.tools.output_store`)。
708
+ :param config: 启动时构造一次的配置对象。界面按它列出模型目录、默认模型与来源。
709
+ :param credentials: 凭证状况。界面按它标出"这个模型现在不可用,原因是什么"。
710
+ :param project_context: 可刷新的规则文件快照。
711
+ :param permission_engine: 工具执行前的权限判定。``None`` 表示不启用权限引擎。
712
+ 它与扩展钩子装在同一个 ``before_tool_call`` 上,权限先判、扩展后判。
713
+ :param plan_mode: 规划模式状态。给出了才有 ``/plan`` 的能力:进入时把权限引擎切到
714
+ ``plan``,退出时切回进入前的模式。``None`` 表示这次运行不支持规划模式。
715
+ :param checkpoints: 文件检查点。给了就启用三件事:``write`` / ``edit`` 执行前
716
+ 记下目标文件内容,``bash`` 前后记工作区状态,每次 run 的边界开合一个回合。
717
+ 它排在权限判定之后、扩展之前:被拒绝的调用不该产生任何快照。
718
+ :param verify: ``verify`` 工具的连续失败预算。每次用户回合开始时清零——
719
+ "连续三次验证失败就停"是同一个任务的约束,换个新任务不该带着旧账。
720
+ :param observability: 观测收集器。``None`` 表示本会话不采集 span、审计与用量汇总。
721
+ 收集器订阅会话事件,并在工具钩子之后接收权限判定;它不参与任何决策。
722
+ """
723
+
724
+ def __init__(
725
+ self,
726
+ *,
727
+ agent: Agent,
728
+ session: SessionManager,
729
+ models: Models,
730
+ prompt_builder: PromptBuilder,
731
+ clock: Clock | None = None,
732
+ retry_policy: RetryPolicy | None = None,
733
+ overflow_recovery: OverflowRecoveryHook | None = None,
734
+ compaction_settings: CompactionSettings | None = None,
735
+ extensions: ExtensionRunner | None = None,
736
+ retry_sleep: RetrySleepFn | None = None,
737
+ tool_outputs: ToolOutputStore | None = None,
738
+ config: AgentConfig | None = None,
739
+ credentials: Credentials | None = None,
740
+ project_context: ProjectContext | None = None,
741
+ skills_loader: SkillsLoader | None = None,
742
+ permission_engine: PermissionEngine | None = None,
743
+ plan_mode: PlanMode | None = None,
744
+ sandbox: SandboxOperations | None = None,
745
+ checkpoints: CheckpointStore | None = None,
746
+ plan: PlanStore | None = None,
747
+ verify: VerifyBudget | None = None,
748
+ observability: ObservabilityCollector | None = None,
749
+ ) -> None:
750
+ self._agent = agent
751
+ self._session = session
752
+ self._models = models
753
+ #: 启动时构造一次的配置与凭证。界面按它们显示"模型从哪来、哪些现在不能用"。
754
+ #: ``None`` 表示库调用方自己拼的会话,没有配置层参与。
755
+ self._config = config
756
+ self._credentials = credentials
757
+ #: 可刷新的规则文件来源。每次 prompt 之前重读磁盘,变化时更新两份 builder。
758
+ self._project_context = project_context
759
+ #: 可刷新的技能来源。与规则文件同样按哈希比较,变化时更新 skills 分节。
760
+ self._skills_loader = skills_loader
761
+ #: 调用方给的提示词来源。``_prompt`` 是"算上扩展工具之后"的那份:
762
+ #: 工具集与上下文文件都会随会话变化,其余分节文本不动。
763
+ self._base_prompt = prompt_builder
764
+ self._prompt = prompt_builder
765
+ #: 调用方给的 ``--append-system-prompt``。规划模式的指引按当前状态拼在它后面:
766
+ #: 每轮从这份原文重算,退出规划模式后能回到一字不差的原样。
767
+ self._user_append = prompt_builder.append_system_prompt
768
+ self._extensions = extensions
769
+ #: 权限判定属于会话状态:换会话要连"本会话已批准"一起换掉。
770
+ self._permission_engine = permission_engine
771
+ #: 命令执行的技术边界。进程级共享(代理端口只该有一个),界面通过 ``/sandbox`` 读它。
772
+ self._sandbox = sandbox
773
+ #: 文件检查点。与会话同生命周期:``/clear`` 换会话也换快照目录。
774
+ self._checkpoints = checkpoints
775
+ #: 计划状态。``None`` 表示这次运行没有 ``update_plan`` 工具,也就没有事件。
776
+ self._plan = plan
777
+ #: 规划模式。``None`` 表示这次运行不支持 ``/plan``(没有权限引擎或没有交互入口)。
778
+ self._plan_mode = plan_mode
779
+ #: 验证工具的连续失败预算。``None`` 表示本次运行没有 ``verify`` 工具。
780
+ self._verify = verify
781
+ #: 观测收集器。``None`` 表示本会话不采集任何可观测性数据。
782
+ self._observability = observability
783
+ #: 已经通知过界面的计划版本。构造时取当前版本:``/resume`` 恢复出的旧计划
784
+ #: 不该再发一次"新计划"事件。
785
+ self._plan_notified_revision = plan.state.revision if plan is not None else 0
786
+ self._tool_outputs = tool_outputs
787
+ self._clock: Clock = clock if clock is not None else SystemClock()
788
+ self._recorder = SessionRecorder(session)
789
+ self._listeners: list[SessionListener] = []
790
+ #: 正在跑 ``_run`` 的任务。``dispose`` 要等它把收尾(检查点回合、完成证据、
791
+ #: ``agent_settled``)全部做完,否则收尾会在监听器被清空之后才发生。
792
+ self._run_task: asyncio.Task[None] | None = None
793
+ self._steering_texts: list[str] = []
794
+ self._follow_up_texts: list[str] = []
795
+ self._abort_requested = False
796
+ self._disposed = False
797
+
798
+ # ---- 重试与溢出恢复 --------------------------------------------
799
+ # 策略显式传入才启用:库的默认行为必须可预测,真实退避(2s/4s/8s)
800
+ # 出现在不知情的调用方里就是事故。
801
+ self._retry_policy = retry_policy
802
+ self._overflow_recovery = overflow_recovery
803
+ self._retry_sleep = retry_sleep
804
+ self._retry_attempt = 0
805
+ self._retry_token: CancelToken | None = None
806
+ # ---- 压缩 ------------------------------------------------------
807
+ # 设置提供后,请求上下文改由会话投影提供(见 _install_request_projection),
808
+ # 这是"压缩是树上的投影"能对请求生效的前提。
809
+ self._compaction_settings = compaction_settings
810
+ self._compaction_token: CancelToken | None = None
811
+ # 失败响应:下一次请求要重发它。设置它的只有自动重试与溢出恢复;
812
+ # 上下文里已经没有这条消息(被投影省略了),所以下一次请求按"续跑"路由。
813
+ self._failed_response: AssistantMessage | None = None
814
+ self._overflow_recovery_attempted = False
815
+ self._last_assistant_message: AssistantMessage | None = None
816
+ # 消息对象 → 会话条目 id。键是 id():record 时的对象、转录里的对象、
817
+ # 会话条目里的对象是同一个引用,对象活着期间 id 不会变。
818
+ self._entry_ids: dict[int, str] = {}
819
+ # ---- 完成证据 --------------------------------------------------
820
+ # 与 run 同生命周期:prompt() 开头清零,agent_settled 之前结算。
821
+ self._evidence = RunEvidence()
822
+ self._completion_evidence: CompletionEvidenceEvent | None = None
823
+ # ---- 上下文提示 ------------------------------------------------
824
+ # 只在"从不告警变成告警"时发一次;压缩之后剩余空间恢复,状态跟着复位。
825
+ self._context_warned = False
826
+
827
+ self._refresh_tools()
828
+ self._restore_or_initialize()
829
+ if plan_mode is not None:
830
+ # 状态变化由规划模式自己发起(工具里也在改),会话负责把它变成事件。
831
+ plan_mode.bind_notify(self._on_plan_mode_change)
832
+ if compaction_settings is not None:
833
+ self._install_request_projection()
834
+ self._unsubscribe_extension_errors: Callable[[], None] = lambda: None
835
+ if extensions is not None or permission_engine is not None or checkpoints is not None:
836
+ self._install_tool_hooks()
837
+ if extensions is not None:
838
+ extensions.bind_append_entry(self._session.append_custom)
839
+ self._install_extension_context()
840
+ self._unsubscribe_extension_errors = extensions.on_error(self._on_extension_error)
841
+ self._unsubscribe = agent.subscribe(self._on_agent_event)
842
+
843
+ # -------------------------------------------------------------- 只读状态
844
+
845
+ @property
846
+ def agent(self) -> Agent:
847
+ """底层 Agent。改它的状态等于改会话状态,本对象不做仲裁。"""
848
+ return self._agent
849
+
850
+ @property
851
+ def session(self) -> SessionManager:
852
+ """会话树。测试与 UI 需要它来读条目、算投影。"""
853
+ return self._session
854
+
855
+ @property
856
+ def extensions(self) -> ExtensionRunner | None:
857
+ """扩展运行时。``None`` 表示本会话不认识扩展机制。
858
+
859
+ REPL 用它列出扩展注册的命令;测试用它断言加载/卸载的结果。
860
+ """
861
+ return self._extensions
862
+
863
+ @property
864
+ def permission_engine(self) -> PermissionEngine | None:
865
+ """当前会话的权限引擎。``None`` 表示这次运行没有装配权限判定。"""
866
+ return self._permission_engine
867
+
868
+ @property
869
+ def sandbox(self) -> SandboxOperations | None:
870
+ """命令执行的沙箱。``None`` 表示 ``mode = "off"``,命令以当前用户权限运行。"""
871
+ return self._sandbox
872
+
873
+ @property
874
+ def checkpoints(self) -> CheckpointStore | None:
875
+ """文件检查点。``None`` 表示这次运行不记录文件快照,``/undo`` 不可用。"""
876
+ return self._checkpoints
877
+
878
+ @property
879
+ def plan(self) -> PlanStore | None:
880
+ """当前会话的计划。``None`` 表示这次运行没有装配 ``update_plan``。"""
881
+ return self._plan
882
+
883
+ @property
884
+ def plan_mode(self) -> PlanMode | None:
885
+ """规划模式。``None`` 表示这次运行不支持 ``/plan``。"""
886
+ return self._plan_mode
887
+
888
+ @property
889
+ def verify_budget(self) -> VerifyBudget | None:
890
+ """``verify`` 工具的连续失败预算。``None`` 表示本次运行没有 ``verify``。
891
+
892
+ ``/status`` 与测试按它读"这一轮已经连续失败几次"。
893
+ """
894
+ return self._verify
895
+
896
+ @property
897
+ def observability(self) -> ObservabilityCollector | None:
898
+ """本次运行的观测收集器。``None`` 表示未启用。``/status`` 从这里读 trace id。"""
899
+ return self._observability
900
+
901
+ @property
902
+ def model(self) -> Model:
903
+ """当前模型。"""
904
+ return self._agent.state.model
905
+
906
+ @property
907
+ def config(self) -> AgentConfig | None:
908
+ """启动时构造的配置对象。``None`` 表示库调用方没有装配配置层。
909
+
910
+ ``/models`` 与 ``braid models`` 读同一份对象:运行中不重读文件,界面显示的
911
+ 就是装配时用的那份,不会出现"列表里的数字和实际请求按的数字不同"。
912
+ """
913
+ return self._config
914
+
915
+ @property
916
+ def credentials(self) -> Credentials | None:
917
+ """凭证状况来源。``None`` 表示这个会话不知道自己用的是哪个 Key。"""
918
+ return self._credentials
919
+
920
+ @property
921
+ def project_context(self) -> ProjectContext | None:
922
+ """规则文件的可刷新状态。``/context`` 按它列出文件、字符数与变化时间。
923
+
924
+ ``None`` 表示库调用方自己拼的会话,没有配置层与规则文件发现。
925
+ """
926
+ return self._project_context
927
+
928
+ @property
929
+ def skills_loader(self) -> SkillsLoader | None:
930
+ """可刷新的技能来源。``/skills`` 用它列清单,``/skill`` 用它按名字加载正文。"""
931
+ return self._skills_loader
932
+
933
+ @property
934
+ def thinking_level(self) -> ModelThinkingLevel:
935
+ """当前思考级别(已钳制到模型支持的档位)。"""
936
+ return self._agent.state.thinking_level
937
+
938
+ @property
939
+ def usage(self) -> SessionUsage:
940
+ """本次会话进程内累计的用量。恢复的历史不计入——那些数字在会话文件里。"""
941
+ return self._recorder.usage
942
+
943
+ @property
944
+ def completion_evidence(self) -> CompletionEvidenceEvent | None:
945
+ """上一次逻辑 run 的完成证据;那次 run 没改文件时为 ``None``。
946
+
947
+ 文本模式用它决定要不要在 stderr 写一句"未验证":stdout 是产物通道,
948
+ 结论的可信度属于诊断信息。
949
+ """
950
+ return self._completion_evidence
951
+
952
+ @property
953
+ def is_streaming(self) -> bool:
954
+ """是否有一次 run 正在进行(含 ``agent_end`` 的订阅者)。"""
955
+ return self._agent.state.is_streaming
956
+
957
+ @property
958
+ def is_disposed(self) -> bool:
959
+ """是否已经释放。"""
960
+ return self._disposed
961
+
962
+ @property
963
+ def retry_attempt(self) -> int:
964
+ """当前重试序号(0 表示不在重试序列里)。"""
965
+ return self._retry_attempt
966
+
967
+ @property
968
+ def is_retrying(self) -> bool:
969
+ """是否正处于退避等待。"""
970
+ return self._retry_token is not None
971
+
972
+ @property
973
+ def is_compacting(self) -> bool:
974
+ """是否有一次压缩正在进行(手动或自动)。
975
+
976
+ RPC 的 ``get_state`` 与 ``prompt`` 预检都要读它:压缩期间提交提示会被拒绝,
977
+ 客户端得先知道"现在是不是压着"。
978
+ """
979
+ return self._compaction_token is not None
980
+
981
+ @property
982
+ def compaction_settings(self) -> CompactionSettings | None:
983
+ """压缩设置。``None`` 表示整个压缩系统不参与本会话(自动压缩因此为关)。"""
984
+ return self._compaction_settings
985
+
986
+ def context_status(self) -> ContextStatus:
987
+ """一份只读的会话状态快照。
988
+
989
+ 数字全部来自会话自己持有的事实:模型窗口取当前选中的模型;上下文体积取
990
+ **会话投影**,压缩与 ``context_edit`` 已经体现在里面;累计用量遍历会话树的
991
+ 全部条目。刻意不读 :attr:`usage`:那份只覆盖本进程,恢复出来的历史会凭空
992
+ 消失。
993
+
994
+ ``near_limit`` 的判据是"剩余空间占触发线不足 20%":它回答的是"离下一次
995
+ 压缩还有多少空间"。
996
+ """
997
+ model = self.model
998
+ window = model.context_window or 0
999
+ settings = self._compaction_settings
1000
+ enabled = settings is not None and settings.enabled
1001
+ reserve = settings.reserve_tokens if enabled and settings is not None else None
1002
+ threshold = max(window - reserve, 0) if reserve is not None and window > 0 else None
1003
+
1004
+ projection = self._session.build_projection()
1005
+ estimate = estimate_projected_context_tokens(projection, self._session.get_branch())
1006
+ percent = estimate.tokens / window * 100.0 if window > 0 else 0.0
1007
+ remaining = threshold - estimate.tokens if threshold is not None else None
1008
+ near_limit = (
1009
+ threshold is not None
1010
+ and threshold > 0
1011
+ and remaining is not None
1012
+ and remaining <= threshold * CONTEXT_WARNING_RATIO
1013
+ )
1014
+ return ContextStatus(
1015
+ model=f"{model.provider}/{model.id}",
1016
+ context_window=window,
1017
+ tokens=estimate.tokens,
1018
+ usage_tokens=estimate.usage_tokens,
1019
+ trailing_tokens=estimate.trailing_tokens,
1020
+ percent=percent,
1021
+ auto_compaction_enabled=enabled,
1022
+ reserve_tokens=reserve,
1023
+ threshold=threshold,
1024
+ remaining_tokens=remaining,
1025
+ near_limit=near_limit,
1026
+ totals=SessionTotals.from_entries(self._session.get_entries()),
1027
+ tool_names=tuple(tool.name for tool in self._effective_tools()),
1028
+ queue_length=len(self._steering_texts) + len(self._follow_up_texts),
1029
+ plan=self._plan.state if self._plan is not None else None,
1030
+ plan_mode=self._plan_mode.state if self._plan_mode is not None else None,
1031
+ )
1032
+
1033
+ def context_breakdown(
1034
+ self,
1035
+ *,
1036
+ subagent_names: Sequence[str] = (),
1037
+ mcp_servers: Sequence[str] = (),
1038
+ ) -> ContextBreakdown:
1039
+ """当前请求的上下文来源明细。
1040
+
1041
+ 总量与 :meth:`context_status` 是同一个数字:有服务端 usage 时它来自服务端,
1042
+ 分项来自字符估算,两者之间的差额单独列出。子代理的完整提示词属于另一个
1043
+ 会话,这里只计主会话里的 ``task`` 工具声明;名字只作为说明传进来。
1044
+ """
1045
+ projection = self._session.build_projection()
1046
+ system = get_current_system_message(cast("Sequence[Message]", projection.messages))
1047
+ loader = self._skills_loader
1048
+ skill_names = tuple(doc.name for doc in loader.documents) if loader is not None else ()
1049
+ status = self.context_status()
1050
+ return build_context_breakdown(
1051
+ system=system,
1052
+ messages=projection.messages,
1053
+ total_tokens=status.tokens,
1054
+ context_window=status.context_window,
1055
+ subagent_names=subagent_names,
1056
+ skill_names=skill_names,
1057
+ mcp_servers=mcp_servers,
1058
+ )
1059
+
1060
+ def get_steering_messages(self) -> list[str]:
1061
+ """待注入的 steering 文本,按入队顺序。"""
1062
+ return list(self._steering_texts)
1063
+
1064
+ def get_follow_up_messages(self) -> list[str]:
1065
+ """待注入的 follow-up 文本,按入队顺序。"""
1066
+ return list(self._follow_up_texts)
1067
+
1068
+ # ---------------------------------------------------------------- 订阅
1069
+
1070
+ def subscribe(self, listener: SessionListener) -> Callable[[], None]:
1071
+ """注册会话订阅者,返回取消订阅的函数。
1072
+
1073
+ 监听器抛异常会让当前 run 进入失败处理(与 :class:`braid_agent.Agent` 的规则一致):
1074
+ 它发生在事件分发的中途,循环已经无法假装一切正常。错误隔离是扩展机制的事,
1075
+ 不是编排层能兜住的。
1076
+ """
1077
+ self._listeners.append(listener)
1078
+
1079
+ def unsubscribe() -> None:
1080
+ if listener in self._listeners:
1081
+ self._listeners.remove(listener)
1082
+
1083
+ return unsubscribe
1084
+
1085
+ # ---------------------------------------------------------------- 输入
1086
+
1087
+ async def prompt(self, text: str, images: Sequence[ImageContent] | None = None) -> None:
1088
+ """发起一次 run,等到整次 run(含 ``agent_settled``)结束才返回。
1089
+
1090
+ 顺序是契约:
1091
+
1092
+ 1. 扩展的工具集合更新一次(可能被加载或卸载过);
1093
+ 2. ``before_agent_start`` 让扩展改提示词分节、追加消息;
1094
+ 3. 提示词补丁(有变化才算)插在用户消息前面——模型要先知道新规则;
1095
+ 4. 这些消息一起交给 ``agent.prompt``,循环在第一次请求之前就把它们走完
1096
+ ``message_end``,所以请求发出时会话文件里已经有用户消息与补丁;
1097
+ 5. 助手消息与工具结果在各自的 ``message_end`` 落盘。
1098
+
1099
+ :raises RuntimeError: 会话已释放,已有一次 run 在进行(要插话请用
1100
+ :meth:`steer` / :meth:`follow_up`),或压缩正在进行。
1101
+ :raises ValueError: 文本为空。空文本不产生一条空用户消息——那会让模型收到
1102
+ 一个没有内容的请求;要"只有技能正文"的一轮,走 :meth:`invoke_skill`。
1103
+ """
1104
+ if not text.strip() and not images:
1105
+ raise ValueError("prompt 需要非空文本")
1106
+ await self._start_run(text, images)
1107
+
1108
+ async def _start_run(
1109
+ self,
1110
+ text: str,
1111
+ images: Sequence[ImageContent] | None,
1112
+ *,
1113
+ leading: Sequence[AgentMessage] = (),
1114
+ ) -> None:
1115
+ """一次 run 的公共前置:前置检查、计数重置、观测边界与消息准备。
1116
+
1117
+ :param leading: 排在扩展消息之后、用户消息之前的消息。技能调用把正文放在
1118
+ 这里,于是同一个请求里"系统提示词补丁 → 技能正文 → 用户参数"顺序成立。
1119
+ """
1120
+ self._require_active()
1121
+ if self._compaction_token is not None:
1122
+ raise RuntimeError(
1123
+ "Cannot submit a prompt while compaction is in progress. "
1124
+ "Wait for compaction to finish and retry."
1125
+ )
1126
+ if self._agent.state.is_streaming:
1127
+ raise RuntimeError(
1128
+ "AgentSession is already processing a prompt. "
1129
+ "Use steer() or follow_up() to queue messages, or wait for idle."
1130
+ )
1131
+
1132
+ # 发送前的阈值检查:上一条助手消息可能已经
1133
+ # 把上下文顶过线(尤其它以 aborted 收尾时,run 后检查会跳过它)。
1134
+ # 忽略返回值:这里的压缩只服务于即将发出的请求,不续跑任何东西。
1135
+ if self._compaction_settings is not None:
1136
+ last_assistant = self._find_last_assistant_message()
1137
+ if last_assistant is not None:
1138
+ await self._check_compaction(last_assistant, skip_aborted_check=False)
1139
+
1140
+ # 新的一次用户回合:验证失败预算重新给满。放在这里而不是 run 收尾,
1141
+ # 是因为一次 run 内部的自动重试与压缩续跑都属于同一个任务。
1142
+ if self._verify is not None:
1143
+ self._verify.begin_turn()
1144
+
1145
+ # 规划模式的提示词段落按当前状态重算:进入、批准、退出都在这里生效,
1146
+ # 变化会以一条系统消息补丁出现在用户消息之前。
1147
+ self._apply_plan_section()
1148
+
1149
+ # 观测边界:一次用户输入 = 一条 trace。放在准备消息之后、进入循环之前,
1150
+ # 这样 span 树里第一个事件就是 agent_start。
1151
+ if self._observability is not None:
1152
+ current = self.model
1153
+ self._observability.begin_run(
1154
+ session_id=self._session.get_session_id(),
1155
+ model=f"{current.provider}/{current.id}",
1156
+ )
1157
+ await self._run(await self._prepare_prompts(text, images, leading=leading))
1158
+
1159
+ async def enter_plan_mode(self, goal: str = "") -> PlanModeState:
1160
+ """进入规划模式:切只读、装规划指引、暴露 ``submit_plan``。
1161
+
1162
+ 模式一直生效到用户批准或主动退出,不随回合结束恢复。状态写在会话树上,
1163
+ 所以压缩与 ``/resume`` 之后仍然有效。
1164
+
1165
+ :raises RuntimeError: 本次运行没有装配规划模式、没有权限引擎,或正有一次
1166
+ run 在进行。运行中换模式会让这一次 run 的提示词与权限判定不一致。
1167
+ """
1168
+ self._require_active()
1169
+ self._require_idle_for_mode_change()
1170
+ mode = self._plan_mode
1171
+ if mode is None:
1172
+ raise RuntimeError("本次运行没有装配规划模式,无法进入 /plan")
1173
+ state = await mode.enter(goal)
1174
+ # 工具与提示词都在下一次请求前重算;这里先刷新一次,让状态查询立刻一致。
1175
+ self._apply_plan_section()
1176
+ self._refresh_tools()
1177
+ return state
1178
+
1179
+ async def approve_plan(self) -> PlanModeState:
1180
+ """批准当前计划:退出规划模式,恢复进入前的权限模式。
1181
+
1182
+ :raises RuntimeError: 没有规划模式、还没有可批准的计划,或正有一次 run 在进行。
1183
+ """
1184
+ self._require_active()
1185
+ self._require_idle_for_mode_change()
1186
+ mode = self._plan_mode
1187
+ if mode is None:
1188
+ raise RuntimeError("本次运行没有装配规划模式,无法批准计划")
1189
+ state = await mode.approve()
1190
+ self._apply_plan_section()
1191
+ self._refresh_tools()
1192
+ return state
1193
+
1194
+ async def leave_plan_mode(self) -> PlanModeState:
1195
+ """退出规划模式(不执行计划)。没在规划模式时同样把状态归零。"""
1196
+ self._require_active()
1197
+ self._require_idle_for_mode_change()
1198
+ mode = self._plan_mode
1199
+ if mode is None:
1200
+ raise RuntimeError("本次运行没有装配规划模式")
1201
+ state = await mode.leave()
1202
+ self._apply_plan_section()
1203
+ self._refresh_tools()
1204
+ return state
1205
+
1206
+ def _require_idle_for_mode_change(self) -> None:
1207
+ """模式切换只在两次 run 之间进行。
1208
+
1209
+ 运行中切模式会让"这一轮的提示词"与"这一刻的权限判定"对不上:提示词还说只读,
1210
+ 权限已经放开了。审批因此被安排在回合边界(REPL / TUI / RPC 都在 run 结束后
1211
+ 才发这条命令)。
1212
+ """
1213
+ if self._agent.state.is_streaming:
1214
+ raise RuntimeError("会话正在运行,不能在回合中途切换规划模式")
1215
+
1216
+ async def steer(
1217
+ self, text: str, images: Sequence[ImageContent] | None = None
1218
+ ) -> QueuedDisposition:
1219
+ """排队一条消息:当前回合与工具执行完之后、下一次请求之前注入。"""
1220
+ self._require_active()
1221
+ self._agent.steer(self._user_message(text, images))
1222
+ self._steering_texts.append(text)
1223
+ await self._emit_queue_update()
1224
+ return "queued"
1225
+
1226
+ def load_skill(self, name: str) -> SkillDocument:
1227
+ """把一份技能的正文作为 custom 消息注入转录与会话,供下一回合的模型读取。
1228
+
1229
+ 与 ``skill`` 工具的区别在触发方:工具由模型主动调用,这里由用户用 ``/skill``
1230
+ 显式加载——因此 ``disable-model-invocation`` 的技能也能进来。权限检查与工具
1231
+ 共用 :func:`check_skill_access`,用户显式加载同样不能越过权限规则。
1232
+
1233
+ 只准备上下文,不发起 run:用户接着说自己要做什么。要"加载即执行"用
1234
+ :meth:`invoke_skill`,``/<技能名>`` 走的是那条路径。
1235
+ """
1236
+ doc = self._require_user_skill(name)
1237
+ # CustomMessage.role 是 ClassVar,结构上不满足 AgentMessage 的可变属性要求;
1238
+ # 循环只读 role,convert_to_llm 按类型分派,收窄是安全的(见 extensions/runner.py)。
1239
+ agent_message = cast("AgentMessage", self._skill_message(doc))
1240
+ self._agent.state.messages.append(agent_message)
1241
+ self._recorder.record(agent_message)
1242
+ return doc
1243
+
1244
+ async def invoke_skill(self, name: str, args: str = "") -> SkillDocument:
1245
+ """用户以 ``/<技能名>`` 调用技能:正文进转录,并立刻跑一次 run。
1246
+
1247
+ 正文排在用户参数之前,因此同一个请求里模型先读到流程、再读到这次调用的具体
1248
+ 要求。没有参数时这一轮的指令就是正文本身——这正是斜杠命令与 ``/skill``
1249
+ 的差别:``/skill`` 只准备上下文,``/<技能名>`` 是一条命令。
1250
+
1251
+ :raises RuntimeError: 会话已释放、已有一次 run 在进行,或没有装配 Skills。
1252
+ :raises ValueError: 技能不存在,或被 ``user-invocable: false`` 排除在用户侧之外。
1253
+ :raises PermissionError: 技能声明的工具或权限不满足当前模式。
1254
+ """
1255
+ doc = self._require_user_skill(name)
1256
+ # 收窄理由见 load_skill:CustomMessage 的 role 是 ClassVar。
1257
+ message = cast("AgentMessage", self._skill_message(doc))
1258
+ await self._start_run(args, None, leading=[message])
1259
+ return doc
1260
+
1261
+ def _require_user_skill(self, name: str) -> SkillDocument:
1262
+ """解析用户侧可调用的技能:存在、允许用户调用、权限预检通过。"""
1263
+ loader = self._skills_loader
1264
+ if loader is None:
1265
+ raise RuntimeError("本次运行没有装配 Skills,无法加载技能")
1266
+ doc = loader.find(name)
1267
+ if doc is None:
1268
+ raise ValueError(f"没有名为 {name!r} 的技能(用 /skills 查看可用技能)")
1269
+ if not doc.user_invocable:
1270
+ raise ValueError(f"技能 {name!r} 标记了 user-invocable: false,只能由模型加载")
1271
+ access = check_skill_access(doc, self._permission_engine, cwd=str(self._prompt.cwd))
1272
+ if not access.allowed:
1273
+ raise PermissionError(access.reason)
1274
+ return doc
1275
+
1276
+ def _skill_message(self, doc: SkillDocument) -> CustomMessage:
1277
+ """技能正文的消息形状:外层标签给出名字,正文原样。"""
1278
+ return CustomMessage(
1279
+ custom_type="skill",
1280
+ timestamp=self._clock.now_ms(),
1281
+ content=(f'<skill name="{doc.name}">\n{doc.body}\n</skill>'),
1282
+ display=True,
1283
+ details={"path": doc.file_path},
1284
+ )
1285
+
1286
+ async def follow_up(
1287
+ self, text: str, images: Sequence[ImageContent] | None = None
1288
+ ) -> QueuedDisposition:
1289
+ """排队一条消息:Agent 本来要停下来时才注入。"""
1290
+ self._require_active()
1291
+ self._agent.follow_up(self._user_message(text, images))
1292
+ self._follow_up_texts.append(text)
1293
+ await self._emit_queue_update()
1294
+ return "queued"
1295
+
1296
+ # ---------------------------------------------------------------- 控制
1297
+
1298
+ async def abort(self) -> None:
1299
+ """取消当前 run 并等到空闲。取消是数据:转录里会留下一条 ``aborted`` 消息。
1300
+
1301
+ 退避等待中的重试也会被取消:退避醒来后发 ``auto_retry_end(success=False)``
1302
+ 并放弃这次重试,run 随之收尾。进行中的压缩同样被取消:
1303
+ 摘要请求响应取消后,本次压缩不写任何条目。
1304
+ """
1305
+ self._abort_requested = True
1306
+ self.abort_retry()
1307
+ self.abort_compaction()
1308
+ self._agent.abort()
1309
+ await self._agent.wait_for_idle()
1310
+
1311
+ def abort_retry(self) -> None:
1312
+ """取消正在进行的退避等待。空闲或不在重试时什么都不做。"""
1313
+ if self._retry_token is not None:
1314
+ self._retry_token.cancel("Aborted by user")
1315
+
1316
+ def abort_compaction(self) -> None:
1317
+ """取消正在进行的压缩(手动或自动)。空闲时什么都不做。"""
1318
+ if self._compaction_token is not None:
1319
+ self._compaction_token.cancel("Aborted by user")
1320
+
1321
+ async def wait_for_idle(self) -> None:
1322
+ """等到当前 run 与它的 ``agent_end`` 订阅者全部完成。"""
1323
+ await self._agent.wait_for_idle()
1324
+
1325
+ # ------------------------------------------------------------ 会话回退
1326
+
1327
+ def rewind_conversation(self, target_entry_id: str | None, *, summary: str) -> str:
1328
+ """把对话拨回 ``target_entry_id`` 之后,返回新的叶子条目 id。
1329
+
1330
+ ``target_entry_id`` 为 ``None`` 表示回到会话开始。做法是在树上追加一条
1331
+ branch_summary 条目(``parent_id`` 指向目标,``from_id`` 记下被放弃的叶子),
1332
+ 再把 Agent 的转录按新路径重算一遍。
1333
+
1334
+ 三样进程内状态必须一起清掉:条目 id 映射(指向已放弃的消息)、上一条助手消息
1335
+ (自动重试与压缩拿它当判断依据)、计划与规划模式的状态(它们从树上算出来,
1336
+ 树上那几条已经被放弃了)。漏掉任何一样,下一次请求都会带着一个不存在的过去。
1337
+
1338
+ :raises RuntimeError: 会话已释放,或正在跑一次 run。
1339
+ :raises ValueError: 目标条目不在活动分支上。
1340
+ """
1341
+ self._require_active()
1342
+ self._require_idle_for_mode_change()
1343
+ entry_id = self._session.rewind(target_entry_id, summary)
1344
+ self._entry_ids.clear()
1345
+ self._last_assistant_message = None
1346
+ self._overflow_recovery_attempted = False
1347
+ if self._plan is not None:
1348
+ self._plan.reload()
1349
+ if self._plan_mode is not None:
1350
+ self._plan_mode.reload()
1351
+ self._apply_plan_section()
1352
+ self._refresh_tools()
1353
+ self._refresh_finalized_context()
1354
+ return entry_id
1355
+
1356
+ # ------------------------------------------------------------ 模型选择
1357
+
1358
+ async def set_model(self, provider: str, model_id: str) -> None:
1359
+ """切换模型,并把选择写成 session entry。
1360
+
1361
+ 历史助手消息保留自己的 ``provider``/``model``——它们记录的是"谁回答了那一轮",
1362
+ 改不了也不该改。切换只影响下一次请求。
1363
+
1364
+ :raises ValueError: ``provider/model`` 不在模型目录里。
1365
+ """
1366
+ self._require_active()
1367
+ model = self._models.get_model(provider, model_id)
1368
+ if model is None:
1369
+ raise ValueError(f"未知模型: {provider}/{model_id}")
1370
+ previous = self._agent.state.model
1371
+ if previous.provider == model.provider and previous.id == model.id:
1372
+ return
1373
+
1374
+ self._agent.state.model = model
1375
+ self._session.append_model_change(provider, model_id)
1376
+ await self._dispatch(ModelChangedEvent(model=model, previous=previous))
1377
+ # 新模型可能不支持当前档位:钳制并记账,否则恢复时会读回一个发不出去的级别。
1378
+ await self._apply_thinking_level(self._agent.state.thinking_level)
1379
+
1380
+ async def set_thinking_level(self, level: ModelThinkingLevel) -> None:
1381
+ """设置思考级别,钳制到模型支持的最近档位,变化时写 session entry。"""
1382
+ self._require_active()
1383
+ await self._apply_thinking_level(level)
1384
+
1385
+ async def _apply_thinking_level(self, level: ModelThinkingLevel) -> None:
1386
+ model = self._agent.state.model
1387
+ effective = clamp_thinking_level(model, level)
1388
+ previous = self._agent.state.thinking_level
1389
+ if effective == previous:
1390
+ return
1391
+ self._agent.state.thinking_level = effective
1392
+ self._session.append_thinking_level_change(effective)
1393
+ await self._dispatch(ThinkingLevelChangedEvent(level=effective, previous=previous))
1394
+
1395
+ # ---------------------------------------------------------------- 压缩
1396
+
1397
+ async def compact(self, custom_instructions: str | None = None) -> CompactionResult:
1398
+ """手动压缩(``/compact`` 的库入口),返回压缩结果。
1399
+
1400
+ 与自动压缩共用同一套准备与摘要流程,但不受 ``enabled`` 约束:用户
1401
+ 明确要求时"配置里关了自动压缩"不构成拒绝理由。先取消当前 run
1402
+ 压缩结束后转录已重建,下一次请求从压缩后的
1403
+ 投影出发。手动压缩永不自动续跑。
1404
+
1405
+ :param custom_instructions: 可选的摘要侧重点,追加到摘要提示词。
1406
+ :raises SummarizationError: 没有可压缩的内容(会话太小或已压缩),
1407
+ 或摘要请求失败。失败时不写任何条目。
1408
+ :raises RuntimeError: 会话已释放,或已有压缩正在进行。
1409
+ """
1410
+ self._require_active()
1411
+ if self._compaction_token is not None:
1412
+ raise RuntimeError("Cannot compact while another compaction is in progress")
1413
+ await self.abort()
1414
+
1415
+ settings = self._compaction_settings or DEFAULT_COMPACTION_SETTINGS
1416
+ token = CancelToken()
1417
+ self._compaction_token = token
1418
+ await self._dispatch(CompactionStartEvent(reason="manual"))
1419
+ try:
1420
+ branch = self._session.get_branch()
1421
+ preparation = prepare_compaction(branch, settings)
1422
+ if preparation is None:
1423
+ last = branch[-1] if branch else None
1424
+ if isinstance(last, CompactionEntry):
1425
+ raise SummarizationError("Already compacted")
1426
+ raise SummarizationError("Nothing to compact (session too small)")
1427
+ # 扩展先发言:它可以取消这次压缩,也可以直接给出摘要(跳过模型调用)。
1428
+ from_extension = False
1429
+ result = await self._request_extension_compaction(
1430
+ preparation, custom_instructions, "manual", False
1431
+ )
1432
+ if result is not None:
1433
+ from_extension = True
1434
+ else:
1435
+ result = await generate_compaction(
1436
+ preparation,
1437
+ self.model,
1438
+ stream_fn=self._agent.stream_fn,
1439
+ custom_instructions=custom_instructions,
1440
+ signal=token,
1441
+ thinking_level=self._agent.state.thinking_level,
1442
+ retry=self._retry_policy,
1443
+ callbacks=self._summarization_callbacks("manual"),
1444
+ clock=self._clock,
1445
+ sleep_fn=self._retry_sleep,
1446
+ )
1447
+ if token.cancelled:
1448
+ raise SummarizationError("Compaction cancelled")
1449
+ self._persist_compaction(result, from_extension=from_extension)
1450
+ await self._dispatch(
1451
+ CompactionEndEvent(reason="manual", result=result, aborted=False, will_retry=False)
1452
+ )
1453
+ return result
1454
+ except Exception as exc:
1455
+ aborted = token.cancelled or isinstance(exc, CompactionCancelledByExtension)
1456
+ await self._dispatch(
1457
+ CompactionEndEvent(
1458
+ reason="manual",
1459
+ result=None,
1460
+ aborted=aborted,
1461
+ will_retry=False,
1462
+ error_message=None if aborted else f"Compaction failed: {exc}",
1463
+ )
1464
+ )
1465
+ raise
1466
+ finally:
1467
+ if self._compaction_token is token:
1468
+ self._compaction_token = None
1469
+
1470
+ # ---------------------------------------------------------------- 释放
1471
+
1472
+ async def dispose(self) -> None:
1473
+ """取消运行、取消退避、取消压缩、取消订阅、通知扩展、丢掉监听器。可重复调用。
1474
+
1475
+ 最后释放会话文件的跨进程锁:此前的 ``wait_for_idle`` 保证不会再有
1476
+ 条目要写,锁交出去之后别的进程才能打开同一个会话。
1477
+ """
1478
+ if self._disposed:
1479
+ return
1480
+ self._disposed = True
1481
+ self._abort_requested = True
1482
+ self.abort_retry()
1483
+ self.abort_compaction()
1484
+ self._agent.abort()
1485
+ await self._agent.wait_for_idle()
1486
+ # ``wait_for_idle`` 只等到**内核** run 结束。会话层的收尾(检查点回合、完成
1487
+ # 证据、``agent_settled``)在它之后,可能还在等一次磁盘 I/O。不等这一步就
1488
+ # 清监听器,客户端会永远收不到 settle 事件。
1489
+ task = self._run_task
1490
+ if task is not None and task is not asyncio.current_task():
1491
+ await asyncio.gather(task, return_exceptions=True)
1492
+ if self._extensions is not None:
1493
+ # 扩展在这里关掉自己开的资源。放在退订之前:处理器里可能还会读会话状态。
1494
+ await self._extensions.emit(SessionShutdownEvent(reason="quit"))
1495
+ self._unsubscribe_extension_errors()
1496
+ self._unsubscribe()
1497
+ self._listeners.clear()
1498
+ self._steering_texts.clear()
1499
+ self._follow_up_texts.clear()
1500
+ if self._tool_outputs is not None:
1501
+ # 放在最后:dispose 之前可能还有一次 bash 在收尾(已完成 wait_for_idle)。
1502
+ self._tool_outputs.release()
1503
+ self._session.release_lock()
1504
+
1505
+ # -------------------------------------------------------------- 内部
1506
+
1507
+ def _restore_or_initialize(self) -> None:
1508
+ """空会话写基线;有历史的会话从投影重建转录。"""
1509
+ context = self._session.build_context()
1510
+ if context.messages:
1511
+ # 投影即事实:压缩、编辑、分支的结果都已经体现在这些消息里,
1512
+ # 再"重跑一遍"只会把已经发生过的事重做一次。
1513
+ self._agent.state.messages = _as_agent_messages(context.messages)
1514
+ self._restore_selection(context.model, context.thinking_level)
1515
+ else:
1516
+ baseline = self._prompt.baseline()
1517
+ self._session.append_message(baseline)
1518
+ self._agent.state.messages = [baseline]
1519
+ self._agent.state.tools = self._prompt.tool_list()
1520
+
1521
+ def _restore_selection(self, model_ref: ModelRef | None, thinking_level: str) -> None:
1522
+ """从会话记录恢复模型与思考级别。解析不了模型时保留调用方给的那个。"""
1523
+ if model_ref is not None:
1524
+ model = self._models.get_model(model_ref.provider, model_ref.model_id)
1525
+ if model is None:
1526
+ logger.warning(
1527
+ "会话记录的模型 %s/%s 不在模型目录里,继续使用当前模型",
1528
+ model_ref.provider,
1529
+ model_ref.model_id,
1530
+ )
1531
+ else:
1532
+ self._agent.state.model = model
1533
+ self._agent.state.thinking_level = clamp_thinking_level(
1534
+ self._agent.state.model, _as_thinking_level(thinking_level)
1535
+ )
1536
+
1537
+ def _user_message(self, text: str, images: Sequence[ImageContent] | None) -> UserMessage:
1538
+ content: list[TextContent | ImageContent] = [TextContent(text=text)]
1539
+ if images:
1540
+ content.extend(images)
1541
+ return UserMessage(timestamp=self._clock.now_ms(), content=content)
1542
+
1543
+ async def _run(self, prompts: Sequence[AgentMessage]) -> None:
1544
+ """一次 run 的边界:``agent_settled`` 一定发出,即使循环抛了异常。
1545
+
1546
+ ``agent.prompt`` 返回后进入**会话级收尾循环**:上一次 run 的最后一个助手
1547
+ 消息可能触发自动重试或溢出恢复(两者都要求"再跑一次"),每次续跑后重新
1548
+ 判断,直到没有后续工作或用户取消。这就是 ``agent_end`` 与 ``agent_settled``
1549
+ 之间那段时间的真正用途。
1550
+
1551
+ 完成证据也在这个边界上结算:``prompt`` 开头清零,``agent_settled``
1552
+ 之前把"改了什么、验证没有"作为一条事件发出去。放在 ``finally`` 里,是因为
1553
+ 被取消的 run 同样需要交代——半成品改动没有验证,正是最该说出来的情形。
1554
+ """
1555
+ self._abort_requested = False
1556
+ self._evidence.reset()
1557
+ self._completion_evidence = None
1558
+ self._run_task = asyncio.current_task()
1559
+ # 检查点的回合边界包住整次 run:自动重试、溢出恢复与后续追问都属于
1560
+ # "用户的一次要求",撤销的粒度就是它。
1561
+ if self._checkpoints is not None:
1562
+ await self._checkpoints.begin_turn()
1563
+ try:
1564
+ await self._agent.prompt(list(prompts))
1565
+ while not self._abort_requested:
1566
+ if await self._handle_post_agent_run():
1567
+ if self._abort_requested:
1568
+ break
1569
+ await self._agent.continue_()
1570
+ continue
1571
+ break
1572
+ finally:
1573
+ if self._checkpoints is not None:
1574
+ await self._checkpoints.end_turn()
1575
+ if self._abort_requested:
1576
+ await self._finish_cancelled_retry()
1577
+ self._failed_response = None
1578
+ await self._dispatch_completion_evidence()
1579
+ status = self.context_status()
1580
+ await self._dispatch_context_warning(status)
1581
+ await self._dispatch(
1582
+ AgentSettledEvent(aborted=self._abort_requested, usage=status.totals)
1583
+ )
1584
+ if self._observability is not None:
1585
+ self._observability.finish_run(totals=status.totals, session=self._session)
1586
+ self._run_task = None
1587
+
1588
+ async def _on_agent_event(self, event: AgentEvent, signal: CancelToken | None) -> None:
1589
+ """Agent 事件 → 落盘 → 重试记账 → 转发。
1590
+
1591
+ 顺序是"先改状态,再通知"(与 :class:`braid_agent.Agent` 同一条规则):
1592
+ 订阅者收到 ``message_end`` 时,会话文件里已经有这条消息了。重试成功的
1593
+ 收尾事件(``auto_retry_end``)在 ``message_end`` **之后**发:对订阅者来说,
1594
+ "这条消息进了转录"先于"重试序列结束"。
1595
+ """
1596
+ del signal # 会话层不消费取消令牌:取消由 Agent 处理,状态由事件反映。
1597
+ retry_end: AutoRetryEndEvent | None = None
1598
+ plan_tool_end: ToolExecutionEndEvent | None = None
1599
+ if isinstance(event, ToolExecutionStartEvent):
1600
+ self._evidence.note_start(event.tool_call_id, event.tool_name, event.args)
1601
+ elif isinstance(event, ToolExecutionEndEvent):
1602
+ self._evidence.note_end(event.tool_call_id, event.tool_name, is_error=event.is_error)
1603
+ # 计划事件排到转发之后:订阅者先看到"工具执行完了",再看到"计划变成了什么"。
1604
+ plan_tool_end = event
1605
+ elif isinstance(event, MessageEndEvent):
1606
+ entry_id = self._recorder.record(event.message)
1607
+ if entry_id is not None:
1608
+ self._entry_ids[id(event.message)] = entry_id
1609
+ if isinstance(event.message, UserMessage) and self._checkpoints is not None:
1610
+ # 把这一回合与发起它的用户消息绑起来:``/rewind`` 要按"树上的一句话"
1611
+ # 找到那一刻的工作区快照,光有时间戳对不准同一毫秒里的两次事件。
1612
+ await self._checkpoints.bind_message(entry_id)
1613
+ if isinstance(event.message, AssistantMessage):
1614
+ self._last_assistant_message = event.message
1615
+ if event.message.stop_reason not in ("error", "length"):
1616
+ # 成功(或至少不是错误/截断)的响应清掉溢出恢复标记:
1617
+ # 上一次恢复已经完成使命,下一次溢出应该重新获得一次机会。
1618
+ self._overflow_recovery_attempted = False
1619
+ if event.message.stop_reason != "error" and self._retry_attempt > 0:
1620
+ # 重试计数在成功响应落盘时立刻清零:一个回合里可能有多条助手
1621
+ # 消息(工具往返),不能让上一次失败的计数累计到下一次。
1622
+ retry_end = AutoRetryEndEvent(success=True, attempt=self._retry_attempt)
1623
+ self._retry_attempt = 0
1624
+ elif isinstance(event, MessageStartEvent) and event.message.role == "user":
1625
+ # 新的用户输入开始:上次遗留的溢出恢复标记作废。
1626
+ self._overflow_recovery_attempted = False
1627
+ await self._deliver_queued_text(event.message)
1628
+ if isinstance(event, AgentEndEvent):
1629
+ # 扩展先看:它们属于这次 run。
1630
+ if self._extensions is not None:
1631
+ await self._extensions.emit(event)
1632
+ await self._dispatch(
1633
+ AgentEndWithRetryEvent(
1634
+ messages=list(event.messages),
1635
+ will_retry=self._will_retry_after_agent_end(event),
1636
+ )
1637
+ )
1638
+ else:
1639
+ await self._dispatch(event)
1640
+ if plan_tool_end is not None:
1641
+ await self._maybe_notify_plan(plan_tool_end)
1642
+ if retry_end is not None:
1643
+ await self._dispatch(retry_end)
1644
+
1645
+ async def _deliver_queued_text(self, message: AgentMessage) -> None:
1646
+ """一条用户消息真的进入转录时,把它从待注入清单里摘掉并广播。"""
1647
+ text = content_text(getattr(message, "content", ""))
1648
+ for texts in (self._steering_texts, self._follow_up_texts):
1649
+ if text in texts:
1650
+ texts.remove(text)
1651
+ await self._emit_queue_update()
1652
+ return
1653
+
1654
+ async def _emit_queue_update(self) -> None:
1655
+ await self._dispatch(
1656
+ QueueUpdateEvent(
1657
+ steering=list(self._steering_texts), follow_up=list(self._follow_up_texts)
1658
+ )
1659
+ )
1660
+
1661
+ async def _maybe_notify_plan(self, event: ToolExecutionEndEvent) -> None:
1662
+ """``update_plan`` 成功且内容真的变了时,发一条 ``plan_update``。
1663
+
1664
+ 事件在 ``tool_execution_end`` **之后**发出:订阅者先看到"工具执行完了",
1665
+ 再看到"计划变成了什么",两次渲染不会把同一次变化画成两份。版本号去重让
1666
+ "模型每个回合都重复同一份表"退化成一次事件;版本号在构造时取当前值,
1667
+ ``/resume`` 恢复出的旧计划因此不再发一次"新计划"。
1668
+ """
1669
+ plan = self._plan
1670
+ if plan is None or event.tool_name != "update_plan" or event.is_error:
1671
+ return
1672
+ state = plan.state
1673
+ if state.revision == self._plan_notified_revision:
1674
+ return
1675
+ self._plan_notified_revision = state.revision
1676
+ await self._dispatch(PlanUpdateEvent(state=state))
1677
+
1678
+ async def _dispatch(self, event: SessionEvent) -> None:
1679
+ # 观测先记:它是只读的,排在 UI 之前不会让界面看到"记了日志"这件事,
1680
+ # 同时保证订阅者抛错时事件已经进了 span 树与用量账本。
1681
+ if self._observability is not None:
1682
+ self._observability.on_event(event)
1683
+ for listener in list(self._listeners):
1684
+ result = listener(event)
1685
+ if inspect.isawaitable(result):
1686
+ await result
1687
+
1688
+ # ------------------------------------------------- 重试与溢出恢复
1689
+
1690
+ def _will_retry_after_agent_end(self, event: AgentEndEvent) -> bool:
1691
+ """``agent_end`` 之后是否会立刻自动重试。给 JSON/RPC 的 ``willRetry`` 用。
1692
+
1693
+ 预算已用尽(``_retry_attempt >= max_retries``)或策略未启用时为否——
1694
+ 订阅方看到 ``will_retry=True`` 就知道**不要**把这个 run 的错误当终态展示。
1695
+ """
1696
+ if self._abort_requested:
1697
+ return False
1698
+ policy = self._retry_policy
1699
+ if policy is None or not policy.enabled or self._retry_attempt >= policy.max_retries:
1700
+ return False
1701
+ for message in reversed(event.messages):
1702
+ if isinstance(message, AssistantMessage):
1703
+ return self._is_retryable_error(message)
1704
+ return False
1705
+
1706
+ async def _handle_post_agent_run(self) -> bool:
1707
+ """一次低层 run 结束后判断会话级后续工作,返回是否要 ``continue_()``。
1708
+
1709
+ 优先级:取消 > 自动重试 > 溢出恢复 > 队列消息。前两级优先,
1710
+ 因为它们都要求"转录回到失败前的状态再跑一次",而队列消息只会追加。
1711
+ """
1712
+ message = self._last_assistant_message
1713
+ self._last_assistant_message = None
1714
+ if self._abort_requested:
1715
+ await self._finish_cancelled_retry()
1716
+ return False
1717
+ if message is None:
1718
+ return self._agent.has_queued_messages()
1719
+
1720
+ if self._is_retryable_error(message) and await self._prepare_retry(message):
1721
+ if self._abort_requested:
1722
+ await self._finish_cancelled_retry()
1723
+ self._failed_response = message
1724
+ return not self._abort_requested
1725
+ if self._abort_requested:
1726
+ await self._finish_cancelled_retry()
1727
+ return False
1728
+
1729
+ if message.stop_reason == "error" and self._retry_attempt > 0:
1730
+ # 重试过但最终失败:报出终态。attempt 保留到这一刻才清零,
1731
+ # 订阅方才能知道"第几次重试之后放弃的"。
1732
+ await self._dispatch(
1733
+ AutoRetryEndEvent(
1734
+ success=False,
1735
+ attempt=self._retry_attempt,
1736
+ final_error=message.error_message,
1737
+ )
1738
+ )
1739
+ self._retry_attempt = 0
1740
+
1741
+ if await self._check_overflow_or_compaction(message):
1742
+ return not self._abort_requested
1743
+
1744
+ if await self._remind_unverified_completion(message):
1745
+ return not self._abort_requested
1746
+
1747
+ # agent_end 订阅者可能刚排了新消息。
1748
+ return not self._abort_requested and self._agent.has_queued_messages()
1749
+
1750
+ # ------------------------------------------- 完成证据与验证提醒
1751
+
1752
+ async def _remind_unverified_completion(self, message: AssistantMessage) -> bool:
1753
+ """改了文件却没跑验证时,追问模型一次,返回是否排进了消息。
1754
+
1755
+ 追问排在**压缩之后**:上下文刚被压缩过就再塞一条长提醒,等于把压缩省下来的
1756
+ 空间又填回去。排在重试之后则是因为失败重试有自己的收尾,不该被提醒打断。
1757
+
1758
+ 只追问一次(``reminder_sent``),且只在模型真的给出了回答时追问:run 以
1759
+ ``error``/``aborted``/``length`` 收尾时,缺的是成功的回合本身,不缺验证。
1760
+ """
1761
+ if not self._should_remind_verification(message):
1762
+ return False
1763
+ self._evidence.reminder_sent = True
1764
+ await self.follow_up(self._verification_reminder_text())
1765
+ return True
1766
+
1767
+ def _should_remind_verification(self, message: AssistantMessage) -> bool:
1768
+ if self._abort_requested or self._evidence.reminder_sent:
1769
+ return False
1770
+ if message.stop_reason not in ("stop", "toolUse"):
1771
+ return False
1772
+ if not self._evidence.needs_verification:
1773
+ return False
1774
+ # 没有 bash 就无从验证:追问只会让模型编一条命令,或者直接说"我做不到"。
1775
+ return any(tool.name == "bash" for tool in self._agent.state.tools)
1776
+
1777
+ def _verification_reminder_text(self) -> str:
1778
+ """追问正文。写成用户口吻,因为它就是以用户消息的形式进转录的。
1779
+
1780
+ 明确给出三条出路(跑验证、改口说未验证、解释为什么不需要),否则模型容易
1781
+ 把"提醒"读成"再试一次",然后在没有新信息的情况下重复上一轮。
1782
+ """
1783
+ modified = self._evidence.modified_paths
1784
+ listed = ", ".join(modified[:5]) + ("…" if len(modified) > 5 else "")
1785
+ return (
1786
+ f"[braid] You changed {len(modified)} file(s) in this run ({listed}) but ran no "
1787
+ "verification command. Before answering, do one of these: run the project's "
1788
+ "check (for example `uv run pytest -q`, `npm test`, `make verify`), or state "
1789
+ "explicitly that the change is unverified and why you could not check it. "
1790
+ "Do not claim tests passed without running them."
1791
+ )
1792
+
1793
+ async def _dispatch_completion_evidence(self) -> None:
1794
+ """结算本次 run 的完成证据。没改文件就什么都不发——那是最常见的情形。"""
1795
+ if not self._evidence.modified_paths:
1796
+ self._completion_evidence = None
1797
+ return
1798
+ event = CompletionEvidenceEvent(
1799
+ modified_paths=list(self._evidence.modified_paths),
1800
+ verification_commands=list(self._evidence.verification_commands),
1801
+ reminder_sent=self._evidence.reminder_sent,
1802
+ unverified=self._evidence.needs_verification,
1803
+ )
1804
+ self._completion_evidence = event
1805
+ await self._dispatch(event)
1806
+
1807
+ async def _dispatch_context_warning(self, status: ContextStatus) -> None:
1808
+ """上下文接近触发线时发一次提示。
1809
+
1810
+ 状态边沿触发:连续两次 run 都接近时只在第一次发;压缩之后剩余空间恢复,
1811
+ ``_context_warned`` 复位,再接近时还能再发一次。它不修改压缩设置,也不
1812
+ 触发压缩本身,只让 REPL、JSON 与 RPC 的订阅者看见同一个事实。
1813
+ """
1814
+ if (
1815
+ status.near_limit
1816
+ and not self._context_warned
1817
+ and status.threshold is not None
1818
+ and status.remaining_tokens is not None
1819
+ ):
1820
+ await self._dispatch(
1821
+ ContextWarningEvent(
1822
+ context_window=status.context_window,
1823
+ tokens=status.tokens,
1824
+ threshold=status.threshold,
1825
+ remaining_tokens=status.remaining_tokens,
1826
+ remaining_percent=status.remaining_tokens / status.threshold * 100.0,
1827
+ )
1828
+ )
1829
+ self._context_warned = status.near_limit
1830
+
1831
+ async def _prepare_retry(self, message: AssistantMessage) -> bool:
1832
+ """为一次自动重试做三件事,返回是否真的要重试。
1833
+
1834
+ 1. 记账并检查预算(初始调用不算重试,``max_retries=0`` 等于关闭);
1835
+ 2. 发 ``auto_retry_start``,把失败尝试从模型投影里省略——原始历史保留,
1836
+ 模型看不到这次失败,下一次请求从失败前的尾部续跑;
1837
+ 3. 退避等待(可取消)。等待期间被取消就发 ``auto_retry_end(success=False)``
1838
+ 并放弃,取消的责任在 :meth:`abort_retry`。
1839
+ """
1840
+ policy = self._retry_policy
1841
+ if policy is None or not policy.enabled:
1842
+ return False
1843
+
1844
+ self._retry_attempt += 1
1845
+ if self._retry_attempt > policy.max_retries:
1846
+ # 保留已完成的重试计数,让外层能报出最终失败;这里只是不再加码。
1847
+ self._retry_attempt -= 1
1848
+ return False
1849
+
1850
+ delay_ms = retry_delay_ms(policy, self._retry_attempt)
1851
+ await self._dispatch(
1852
+ AutoRetryStartEvent(
1853
+ attempt=self._retry_attempt,
1854
+ max_attempts=policy.max_retries,
1855
+ delay_ms=delay_ms,
1856
+ error_message=message.error_message or "Unknown error",
1857
+ )
1858
+ )
1859
+
1860
+ # 先省略再等待:等待期间用户看到的转录已经是"失败前"的状态。
1861
+ self._omit_recovery_attempt(message)
1862
+
1863
+ token = CancelToken()
1864
+ self._retry_token = token
1865
+ try:
1866
+ sleep = self._retry_sleep if self._retry_sleep is not None else backoff_sleep
1867
+ await sleep(delay_ms, token)
1868
+ except RetryBackoffCancelled:
1869
+ await self._finish_cancelled_retry()
1870
+ return False
1871
+ finally:
1872
+ self._retry_token = None
1873
+ return True
1874
+
1875
+ async def _finish_cancelled_retry(self) -> None:
1876
+ """把被取消的重试序列收尾。没有进行中的重试时什么都不做。"""
1877
+ if self._retry_attempt == 0:
1878
+ return
1879
+ attempt = self._retry_attempt
1880
+ self._retry_attempt = 0
1881
+ await self._dispatch(
1882
+ AutoRetryEndEvent(success=False, attempt=attempt, final_error="Retry cancelled")
1883
+ )
1884
+
1885
+ def _is_retryable_error(self, message: AssistantMessage) -> bool:
1886
+ """错误是否值得自动重试。溢出不算:重试只会原样再撞一次。"""
1887
+ model = self._model_for_message(message)
1888
+ window = model.context_window if model is not None else self.model.context_window
1889
+ if is_context_overflow(message, window):
1890
+ return False
1891
+ return is_retryable_assistant_error(message)
1892
+
1893
+ def _model_for_message(self, message: AssistantMessage) -> Model | None:
1894
+ """按消息自报的 provider/model 在目录里找回产生它的模型;找不到返回 ``None``。"""
1895
+ return self._models.get_model(message.provider, message.model)
1896
+
1897
+ def _is_output_truncation(self, message: AssistantMessage, message_model: Model) -> bool:
1898
+ """这条 ``length`` 停是否属于"本可以更长"的截断。
1899
+
1900
+ 调用方显式给了输出预算(``--max-tokens``)时不算:停在那个数字上正是它要的
1901
+ 结果,压缩改不了调用方定下的上限,重试只会再截一次。没有显式预算时按模型
1902
+ 目录值判断——低于目录上限却停在 ``length``,说明截断来自端点或上下文挤压,
1903
+ 值得一次有界的压缩续跑。
1904
+ """
1905
+ if self._agent.stream_options.max_tokens is not None:
1906
+ return False
1907
+ return is_recoverable_length(message, message_model.max_tokens)
1908
+
1909
+ # ------------------------------------------------------- 压缩与溢出
1910
+
1911
+ async def _check_overflow_or_compaction(self, message: AssistantMessage) -> bool:
1912
+ """run 结束后的溢出/阈值路由。
1913
+
1914
+ 显式钩子优先;未提供钩子且启用了压缩时,走内建的
1915
+ ``_check_compaction``:溢出识别 →
1916
+ 一次压缩恢复预算 → 阈值兜底,全部落在同一个函数里。
1917
+ """
1918
+ if self._overflow_recovery is not None:
1919
+ return await self._check_overflow_recovery(message)
1920
+ if self._compaction_settings is not None:
1921
+ return await self._check_compaction(message)
1922
+ return False
1923
+
1924
+ def _find_last_assistant_message(self) -> AssistantMessage | None:
1925
+ """转录里最后一条助手消息。发送前的阈值检查从它出发。"""
1926
+ for message in reversed(self._agent.state.messages):
1927
+ if isinstance(message, AssistantMessage):
1928
+ return message
1929
+ return None
1930
+
1931
+ def _latest_compaction_entry(self) -> CompactionEntry | None:
1932
+ """当前分支上最近一次压缩条目。"""
1933
+ latest: CompactionEntry | None = None
1934
+ for entry in self._session.get_branch():
1935
+ if isinstance(entry, CompactionEntry):
1936
+ latest = entry
1937
+ return latest
1938
+
1939
+ def _summarization_callbacks(self, reason: CompactionReason) -> RetryCallbacks:
1940
+ """摘要重试的三段回调 → 会话事件。``reason`` 在事件里跟着走,
1941
+ 订阅方才知道这次重试属于哪次压缩。"""
1942
+
1943
+ async def on_scheduled(
1944
+ attempt: int, max_attempts: int, delay_ms: int, error_message: str
1945
+ ) -> None:
1946
+ await self._dispatch(
1947
+ SummarizationRetryScheduledEvent(
1948
+ attempt=attempt,
1949
+ max_attempts=max_attempts,
1950
+ delay_ms=delay_ms,
1951
+ error_message=error_message,
1952
+ )
1953
+ )
1954
+
1955
+ async def on_attempt_start() -> None:
1956
+ await self._dispatch(
1957
+ SummarizationRetryAttemptStartEvent(source="compaction", reason=reason)
1958
+ )
1959
+
1960
+ async def on_finished(success: bool, attempt: int, final_error: str | None) -> None:
1961
+ del success, attempt, final_error # 细节留在日志里。
1962
+ logger.debug("摘要重试结束: reason=%s", reason)
1963
+ await self._dispatch(SummarizationRetryFinishedEvent())
1964
+
1965
+ return RetryCallbacks(
1966
+ on_retry_scheduled=on_scheduled,
1967
+ on_retry_attempt_start=on_attempt_start,
1968
+ on_retry_finished=on_finished,
1969
+ )
1970
+
1971
+ async def _check_compaction(
1972
+ self, message: AssistantMessage, skip_aborted_check: bool = True
1973
+ ) -> bool:
1974
+ """一次 run 结束后的压缩检查。
1975
+
1976
+ 三个自动触发情形按顺序判断:
1977
+
1978
+ 1. **溢出 + 可续跑**:省略失败尝试 → 压缩 → 重试一次(预算由
1979
+ ``_overflow_recovery_attempted`` 把守);
1980
+ 2. **溢出 + 已完成**:只压缩,不续跑(``continue_`` 无法从一条说完的
1981
+ 助手消息续起);
1982
+ 3. **阈值**:usage 或估算越过 ``window - reserve`` → 压缩,不续跑。
1983
+
1984
+ 返回是否要 ``continue_()``。只有情形 1 会返回 ``True``。
1985
+ """
1986
+ settings = self._compaction_settings
1987
+ if settings is None or not settings.enabled:
1988
+ return False
1989
+ if skip_aborted_check and message.stop_reason == "aborted":
1990
+ return False
1991
+
1992
+ # 产生这条消息的模型决定窗口:换了更大窗口的模型之后,旧模型报的
1993
+ # 溢出不该触发新模型的压缩。
1994
+ message_model = self._model_for_message(message)
1995
+ same_model = message_model is not None
1996
+ context_window = (message_model or self.model).context_window or 0
1997
+ if self._predates_latest_compaction(message):
1998
+ # 压缩前的旧 usage 反映的是旧(更大)上下文,不能拿它再触发一次。
1999
+ return False
2000
+
2001
+ projection = self._session.build_projection()
2002
+ branch = self._session.get_branch()
2003
+ entry_id = self._entry_id_for(message)
2004
+ assistant_is_projected = entry_id is None or any(
2005
+ item.source_entry.id == entry_id and any(m.role == "assistant" for m in item.messages)
2006
+ for item in projection.entries
2007
+ )
2008
+ assistant_index = -1
2009
+ if entry_id is not None:
2010
+ assistant_index = next(
2011
+ (i for i, entry in enumerate(branch) if entry.id == entry_id), -1
2012
+ )
2013
+ entries_after = branch[assistant_index + 1 :] if assistant_index >= 0 else []
2014
+ has_post_assistant_edit = any(
2015
+ isinstance(entry, ContextEditEntry) for entry in entries_after
2016
+ )
2017
+ latest_edit_for_assistant = next(
2018
+ (
2019
+ entry
2020
+ for entry in reversed(entries_after)
2021
+ if isinstance(entry, ContextEditEntry) and entry.target_id == entry_id
2022
+ ),
2023
+ None,
2024
+ )
2025
+ # 显式溢出错误可以被恢复保留:没有编辑
2026
+ # 或最后一条编辑是"替换"时都算保留;被压缩吞掉或被"省略型"编辑盖住
2027
+ # 则说明它描述的输入已不在投影里。
2028
+ retained_for_explicit_recovery = entry_id is None or (
2029
+ not any(isinstance(entry, CompactionEntry) for entry in entries_after)
2030
+ and (
2031
+ latest_edit_for_assistant is None
2032
+ or latest_edit_for_assistant.replacement is not None
2033
+ )
2034
+ )
2035
+ usage_matches_projection = assistant_is_projected and not has_post_assistant_edit
2036
+
2037
+ explicit_overflow = message.stop_reason == "error" and is_context_overflow(message)
2038
+ context_overflow = same_model and (
2039
+ (explicit_overflow and retained_for_explicit_recovery)
2040
+ or (usage_matches_projection and is_context_overflow(message, context_window))
2041
+ )
2042
+ recoverable_length = (
2043
+ message_model is not None
2044
+ and assistant_is_projected
2045
+ and self._is_output_truncation(message, message_model)
2046
+ )
2047
+
2048
+ if context_overflow or recoverable_length:
2049
+ will_retry = message.stop_reason != "stop"
2050
+ if not will_retry:
2051
+ # 情形 2:响应已完成,压缩只为下一次请求服务。
2052
+ return await self._run_auto_compaction("overflow", False)
2053
+ if self._overflow_recovery_attempted:
2054
+ # 一次压缩没能救回来:报出终态,保留原始错误。
2055
+ error_message = (
2056
+ "Context overflow recovery failed after one compact-and-retry attempt. "
2057
+ "Try reducing context or switching to a larger-context model."
2058
+ if context_overflow
2059
+ else "Truncated response recovery failed after one compact-and-retry attempt."
2060
+ )
2061
+ await self._dispatch(
2062
+ CompactionEndEvent(
2063
+ reason="overflow",
2064
+ result=None,
2065
+ aborted=False,
2066
+ will_retry=False,
2067
+ error_message=error_message,
2068
+ )
2069
+ )
2070
+ return False
2071
+ self._overflow_recovery_attempted = True
2072
+ self._omit_recovery_attempt(message)
2073
+ retried = await self._run_auto_compaction("overflow", will_retry)
2074
+ if retried:
2075
+ self._failed_response = message
2076
+ return retried
2077
+
2078
+ # 情形 3:阈值,永不续跑。
2079
+ # 错误消息与全零 usage 不可信,退回估算;估算的 usage 来源若比最近一次
2080
+ # 压缩还旧(保留区里的历史消息),同样不触发。
2081
+ has_context_edits = any(
2082
+ isinstance(item.source_entry, ContextEditEntry) for item in projection.entries
2083
+ )
2084
+ direct_tokens = calculate_context_tokens(message.usage)
2085
+ if has_context_edits:
2086
+ context_tokens = estimate_projected_context_tokens(projection, branch).tokens
2087
+ elif message.stop_reason == "error" or direct_tokens == 0:
2088
+ estimate = estimate_context_tokens(list(self._agent.state.messages))
2089
+ if estimate.last_usage_index is not None:
2090
+ usage_message = self._agent.state.messages[estimate.last_usage_index]
2091
+ latest = self._latest_compaction_entry()
2092
+ if (
2093
+ latest is not None
2094
+ and isinstance(usage_message, AssistantMessage)
2095
+ and usage_message.timestamp <= ms_from_iso(latest.timestamp)
2096
+ ):
2097
+ return False
2098
+ context_tokens = estimate.tokens
2099
+ else:
2100
+ context_tokens = direct_tokens
2101
+ if should_compact(context_tokens, context_window, settings):
2102
+ return await self._run_auto_compaction("threshold", False)
2103
+ return False
2104
+
2105
+ async def _run_auto_compaction(self, reason: CompactionReason, will_retry: bool) -> bool:
2106
+ """执行一次自动压缩:准备 → 摘要 → 落盘 → 重建投影 → 发事件。
2107
+
2108
+ 返回是否要 ``continue_()``:``will_retry=True`` 的溢出恢复路径返回真;
2109
+ 其余情形只在"压缩期间排进了新消息"时继续一次,把队列送达。
2110
+ 任何失败(含取消)都不写条目,会话保持原样。
2111
+ """
2112
+ settings = self._compaction_settings
2113
+ if settings is None:
2114
+ return False
2115
+ preparation = prepare_compaction(self._session.get_branch(), settings)
2116
+ if preparation is None:
2117
+ return False
2118
+
2119
+ token = CancelToken()
2120
+ self._compaction_token = token
2121
+ started = False
2122
+ try:
2123
+ await self._dispatch(CompactionStartEvent(reason=reason))
2124
+ started = True
2125
+ # 扩展先发言:取消或自带摘要都跳过模型调用(与手动压缩同一套顺序)。
2126
+ from_extension = False
2127
+ result = await self._request_extension_compaction(preparation, None, reason, will_retry)
2128
+ if result is not None:
2129
+ from_extension = True
2130
+ else:
2131
+ result = await generate_compaction(
2132
+ preparation,
2133
+ self.model,
2134
+ stream_fn=self._agent.stream_fn,
2135
+ signal=token,
2136
+ thinking_level=self._agent.state.thinking_level,
2137
+ retry=self._retry_policy,
2138
+ callbacks=self._summarization_callbacks(reason),
2139
+ clock=self._clock,
2140
+ sleep_fn=self._retry_sleep,
2141
+ )
2142
+ if token.cancelled:
2143
+ raise SummarizationError("Compaction cancelled")
2144
+ self._persist_compaction(result, from_extension=from_extension)
2145
+ await self._dispatch(
2146
+ CompactionEndEvent(
2147
+ reason=reason, result=result, aborted=False, will_retry=will_retry
2148
+ )
2149
+ )
2150
+ if will_retry:
2151
+ return True
2152
+ # 压缩完成时可能已有 steering/follow-up 在等:继续一次把队列送达。
2153
+ return self._agent.has_queued_messages()
2154
+ except Exception as exc:
2155
+ aborted = token.cancelled or isinstance(exc, CompactionCancelledByExtension)
2156
+ if started:
2157
+ prefix = (
2158
+ "Context overflow recovery failed"
2159
+ if reason == "overflow"
2160
+ else "Auto-compaction failed"
2161
+ )
2162
+ await self._dispatch(
2163
+ CompactionEndEvent(
2164
+ reason=reason,
2165
+ result=None,
2166
+ aborted=aborted,
2167
+ will_retry=False,
2168
+ error_message=None if aborted else f"{prefix}: {exc}",
2169
+ )
2170
+ )
2171
+ return False
2172
+ finally:
2173
+ if self._compaction_token is token:
2174
+ self._compaction_token = None
2175
+
2176
+ def _persist_compaction(
2177
+ self, result: CompactionResult, *, from_extension: bool = False
2178
+ ) -> None:
2179
+ """把压缩结果写成条目并重建转录投影。摘要成功之后才允许失败——
2180
+ 这里的任何异常都属于"磁盘/格式坏了"这一类,向上传播是正确行为。"""
2181
+ self._session.append_compaction(
2182
+ summary=result.summary,
2183
+ tokens_before=result.tokens_before,
2184
+ first_kept_entry_id=result.first_kept_entry_id,
2185
+ usage=result.usage,
2186
+ details=result.details,
2187
+ # 扩展提供的摘要在会话文件里留痕:恢复时能看出它不是模型生成的。
2188
+ from_hook=from_extension,
2189
+ )
2190
+ self._refresh_finalized_context()
2191
+ projection = self._session.build_projection()
2192
+ result.estimated_tokens_after = sum(
2193
+ estimate_tokens(message) for message in projection.messages
2194
+ )
2195
+ if result.usage is not None:
2196
+ # 摘要是一次真实的模型调用:计入会话总账。
2197
+ self._recorder.usage.add(result.usage)
2198
+
2199
+ def _install_request_projection(self) -> None:
2200
+ """把"请求上下文 = 会话投影"装进 Agent(包装调用方已有的变换)。
2201
+
2202
+ 装上之后,**每次请求**的上下文都从会话树重建:压缩、省略、分支
2203
+ 的结果即时生效,长 run 中途的多次请求之间也不会漂移。调用方传入的
2204
+ ``transform_context`` 收到的是投影,其产出仍作为最终请求上下文——
2205
+ 包装而不是替换。
2206
+ """
2207
+ previous = self._agent.transform_context
2208
+
2209
+ async def transform(
2210
+ messages: list[AgentMessage], signal: CancelToken | None
2211
+ ) -> list[AgentMessage]:
2212
+ del messages # 循环的快照不再可信:投影是唯一事实来源。
2213
+ canonical = await self._canonical_request_messages()
2214
+ if previous is not None:
2215
+ result = previous(canonical, signal)
2216
+ if inspect.isawaitable(result):
2217
+ result = await result
2218
+ return result
2219
+ return canonical
2220
+
2221
+ self._agent.transform_context = transform
2222
+
2223
+ async def _canonical_request_messages(self) -> list[AgentMessage]:
2224
+ """当前请求应看到的消息:会话投影,必要时先清理工具结果再压缩。"""
2225
+ assert self._compaction_settings is not None
2226
+ projection = self._session.build_projection()
2227
+ model = self.model
2228
+ if model.context_window > 0:
2229
+ tokens = estimate_projected_context_tokens(
2230
+ projection, self._session.get_branch()
2231
+ ).tokens
2232
+ # 清理由轻到重的顺序:先按条替换(不动对话),仍然超标才摘要整段。
2233
+ if await self._clean_tool_results(projection, tokens, model.context_window):
2234
+ projection = self._session.build_projection()
2235
+ tokens = estimate_projected_context_tokens(
2236
+ projection, self._session.get_branch()
2237
+ ).tokens
2238
+ if should_compact(tokens, model.context_window, self._compaction_settings):
2239
+ await self._run_auto_compaction("threshold", False)
2240
+ projection = self._session.build_projection()
2241
+ return _as_agent_messages(projection.messages)
2242
+
2243
+ async def _clean_tool_results(
2244
+ self, projection: SessionProjection, tokens: int, context_window: int
2245
+ ) -> bool:
2246
+ """把更早的大块工具结果换成一行摘要;返回是否写了条目。
2247
+
2248
+ 只在请求之前做:上下文体积只在请求时有代价,别处清理只是无谓的信息丢失。
2249
+ 计划由 :func:`~braid_coding_agent.compaction.tool_results.plan_tool_result_cleanup`
2250
+ 给出,这里只落成 ``context_edit`` 条目并发事件——原始条目一个都不动,
2251
+ 会话文件因此仍能还原清理之前的完整记录。
2252
+ """
2253
+ settings = self._compaction_settings
2254
+ if settings is None or not settings.enabled:
2255
+ return False
2256
+ plan = plan_tool_result_cleanup(
2257
+ projection,
2258
+ self._session.get_branch(),
2259
+ tokens=tokens,
2260
+ context_window=context_window,
2261
+ settings=settings.tool_results,
2262
+ )
2263
+ if not plan.targets:
2264
+ return False
2265
+ for target in plan.targets:
2266
+ self._session.append_context_edit(
2267
+ target.entry_id, ContextReplacement(content=target.replacement)
2268
+ )
2269
+ await self._dispatch(
2270
+ ToolResultCleanupEvent(
2271
+ cleared=len(plan.targets),
2272
+ chars_before=plan.chars_before,
2273
+ chars_after=plan.chars_after,
2274
+ tokens=tokens,
2275
+ context_window=context_window,
2276
+ )
2277
+ )
2278
+ return True
2279
+
2280
+ # --------------------------------------------------------- 规划模式
2281
+
2282
+ def _apply_plan_section(self) -> None:
2283
+ """把规划模式的提示词段落按当前状态重算一次。
2284
+
2285
+ 每次都从用户给的原文(``self._user_append``)重算,而不是在上一版上追加:
2286
+ 进入、修改、批准、退出都走同一条路径,不会因为顺序不同留下残留。
2287
+ 提示词分节是转录里可重放的数据,变化在下一次 ``patch_for`` 时变成一条补丁;
2288
+ 压缩之后重新算一次就回到正确内容,不依赖任何一条消息活下来。
2289
+ """
2290
+ section = self._plan_mode.prompt_section() if self._plan_mode is not None else ""
2291
+ combined = "\n\n".join(part for part in (self._user_append.strip(), section) if part)
2292
+ if self._base_prompt.append_system_prompt == combined:
2293
+ return
2294
+ self._base_prompt = replace(self._base_prompt, append_system_prompt=combined)
2295
+ self._prompt = replace(self._prompt, append_system_prompt=combined)
2296
+
2297
+ async def _on_plan_mode_change(self, state: PlanModeState, reason: PlanModeReason) -> None:
2298
+ """规划模式变化 → 会话事件。界面据此重画模式指示与计划正文。"""
2299
+ await self._dispatch(PlanModeEvent(state=state, reason=reason))
2300
+
2301
+ # --------------------------------------------------------- 扩展
2302
+
2303
+ def _refresh_tools(self) -> None:
2304
+ """把扩展注册的工具与当前的规划工具并进可执行集合。
2305
+
2306
+ 只在 ``prompt()`` 开始时调用,不在事件里调用:工具集变化必须发生在**两次请求
2307
+ 之间**。若在执行途中改,本回合已发出的调用可能指向一个刚被卸载的工具,
2308
+ 而模型手里的声明还是旧的。
2309
+
2310
+ 工具声明差异不在这里发消息——:func:`braid_agent.loop.declare_tool_changes` 会在
2311
+ 下一次请求前按"可执行 vs 已声明"自己算,两处都算会得到两条互相覆盖的补丁。
2312
+ """
2313
+ tools = self._effective_tools()
2314
+ if list(self._prompt.tools) == tools and list(self._agent.state.tools) == tools:
2315
+ return
2316
+ # 用 ``replace`` 造新对象而不是改 ``_base_prompt``:那份对象是调用方传进来的,
2317
+ # 会话不应该在别人的对象上留下自己的工具集。
2318
+ self._prompt = replace(self._base_prompt, tools=tools)
2319
+ self._agent.state.tools = tools
2320
+
2321
+ def _effective_tools(self) -> list[AgentTool]:
2322
+ """可以执行的工具:内置的全留,扩展的追加在后面(同名以内置为准)。
2323
+
2324
+ ``submit_plan`` 只在规划模式生效期间可执行:它是规划模式的协议,不是用户可以
2325
+ 从 ``--tools`` 里挑选的能力,所以不占白名单里的位置。
2326
+ """
2327
+ tools = list(self._base_prompt.tools)
2328
+ mode = self._plan_mode
2329
+ if mode is not None and mode.tool is not None and mode.active:
2330
+ tools.append(mode.tool)
2331
+ if self._extensions is not None:
2332
+ known = {tool.name for tool in tools}
2333
+ tools.extend(tool for tool in self._extensions.tools() if tool.name not in known)
2334
+ return tools
2335
+
2336
+ def _install_tool_hooks(self) -> None:
2337
+ """把工具钩子接到权限引擎、检查点与扩展运行时上。
2338
+
2339
+ 直接**替换** ``Agent`` 上的钩子:会话是这两个钩子的所有者。构造 ``Agent``
2340
+ 时传进来的钩子会被覆盖——想让两段逻辑共存,把它写成扩展。
2341
+
2342
+ 顺序是权限先判、检查点再记、``before_tool_call`` 扩展最后看:被拒绝的调用
2343
+ 不该产生任何快照,也不该触发"记录每次工具调用"的扩展。检查点排在扩展之前,
2344
+ 是因为扩展可能在钩子里改写参数——检查点记的是**即将被执行**的那份参数。
2345
+ """
2346
+ extensions = self._extensions
2347
+ engine = self._permission_engine
2348
+ checkpoints = self._checkpoints
2349
+
2350
+ async def before(
2351
+ context: BeforeToolCallContext, signal: CancelToken | None
2352
+ ) -> BeforeToolCallResult | None:
2353
+ if engine is not None:
2354
+ decision = await engine.authorize(
2355
+ context.tool_call.name,
2356
+ context.tool_call.id,
2357
+ context.args,
2358
+ signal,
2359
+ )
2360
+ if self._observability is not None:
2361
+ request = build_permission_request(
2362
+ context.tool_call.name,
2363
+ context.tool_call.id,
2364
+ context.args,
2365
+ str(self._prompt.cwd),
2366
+ )
2367
+ self._observability.record_permission(decision, request)
2368
+ if decision.action == "deny":
2369
+ return BeforeToolCallResult(block=True, reason=decision.reason)
2370
+ if checkpoints is not None:
2371
+ # 快照失败会抛出去,循环把它折成 is_error 结果:一次改不动的编辑,
2372
+ # 好过一次撤不回的编辑。
2373
+ await checkpoints.before_tool(
2374
+ context.tool_call.id, context.tool_call.name, context.args, signal
2375
+ )
2376
+ if extensions is not None:
2377
+ return await extensions.emit_before_tool_call(context)
2378
+ return None
2379
+
2380
+ self._agent.before_tool_call = before
2381
+
2382
+ if extensions is None and checkpoints is None:
2383
+ return
2384
+ runner = extensions
2385
+
2386
+ async def after(
2387
+ context: AfterToolCallContext, signal: CancelToken | None
2388
+ ) -> AfterToolCallResult | None:
2389
+ """收尾:先让检查点记账,再交给扩展改写结果。"""
2390
+ if checkpoints is not None:
2391
+ await checkpoints.after_tool(
2392
+ context.tool_call.id, context.tool_call.name, context.args, signal
2393
+ )
2394
+ if runner is None:
2395
+ return None
2396
+ return await runner.emit_after_tool_call(context)
2397
+
2398
+ self._agent.after_tool_call = after
2399
+
2400
+ def _install_extension_context(self) -> None:
2401
+ """把 ``context`` 钩子接到请求前变换上(**包装**调用方已有的变换)。
2402
+
2403
+ 包装而不是替换:压缩已经把 ``transform_context`` 换成了"从会话投影
2404
+ 重建",扩展看到的是投影之后的对话——这正是模型即将看到的那份。
2405
+ """
2406
+ extensions = self._extensions
2407
+ assert extensions is not None
2408
+ previous = self._agent.transform_context
2409
+
2410
+ async def transform(
2411
+ messages: list[AgentMessage], signal: CancelToken | None
2412
+ ) -> list[AgentMessage]:
2413
+ if previous is None:
2414
+ current: list[AgentMessage] = messages
2415
+ else:
2416
+ result = previous(messages, signal)
2417
+ current = await result if inspect.isawaitable(result) else result
2418
+ return await extensions.emit_context(current)
2419
+
2420
+ self._agent.transform_context = transform
2421
+
2422
+ def _refresh_project_context(self) -> None:
2423
+ """规则文件变了就把新快照装进两份 builder,让分节差分算出补丁。
2424
+
2425
+ 先刷工具再刷上下文:``_refresh_tools`` 会用 ``replace(_base_prompt, tools=...)``
2426
+ 重建 ``_prompt``,只改其中一份会在下一次工具变化时被覆盖回旧规则。
2427
+ """
2428
+ context = self._project_context
2429
+ if context is None or not context.refresh():
2430
+ return
2431
+ files = context.files
2432
+ self._base_prompt = replace(self._base_prompt, context_files=files)
2433
+ self._prompt = replace(self._prompt, context_files=files)
2434
+
2435
+ def _refresh_skills(self) -> None:
2436
+ """技能文件变了就刷新清单,让分节差分写出 ``skills`` 补丁。
2437
+
2438
+ 正文不进提示词:这里只把 ``disable_model_invocation`` 之外的清单项交给
2439
+ ``PromptBuilder``,模型要读正文得另走 ``skill`` 工具。
2440
+ """
2441
+ loader = self._skills_loader
2442
+ if loader is None or not loader.refresh():
2443
+ return
2444
+ skills = loader.prompt_skills()
2445
+ self._base_prompt = replace(self._base_prompt, skills=skills)
2446
+ self._prompt = replace(self._prompt, skills=skills)
2447
+
2448
+ async def _prepare_prompts(
2449
+ self,
2450
+ text: str,
2451
+ images: Sequence[ImageContent] | None,
2452
+ *,
2453
+ leading: Sequence[AgentMessage] = (),
2454
+ ) -> list[AgentMessage]:
2455
+ """一次 run 的待发消息:刷新工具 → 提示词补丁 → 扩展消息 → 前置消息 → 用户消息。
2456
+
2457
+ 顺序是契约:补丁必须先于用户消息(模型要先知道新规则),扩展追加的消息排在
2458
+ 用户消息之前(它们是"这次 run 的背景",不是"用户说的话")。技能正文属于这次
2459
+ 调用的指令,排在扩展消息之后、用户参数之前。
2460
+ """
2461
+ self._refresh_tools()
2462
+ self._refresh_project_context()
2463
+ self._refresh_skills()
2464
+ sections: Mapping[str, str] | None = None
2465
+ extra: Sequence[AgentMessage] = ()
2466
+ if self._extensions is not None and self._extensions.has_handlers("before_agent_start"):
2467
+ current = self._prompt.sections()
2468
+ result = await self._extensions.emit_before_agent_start(
2469
+ BeforeAgentStartEvent(
2470
+ prompt=text,
2471
+ system_prompt=render_prompt_sections(current),
2472
+ sections=current,
2473
+ )
2474
+ )
2475
+ sections = result.sections
2476
+ extra = result.messages
2477
+ prompts: list[AgentMessage] = []
2478
+ patch = self._prompt.patch_for(self._agent.state.messages, sections)
2479
+ if patch is not None:
2480
+ prompts.append(patch)
2481
+ prompts.extend(extra)
2482
+ prompts.extend(leading)
2483
+ if text.strip() or images:
2484
+ prompts.append(self._user_message(text, images))
2485
+ return prompts
2486
+
2487
+ async def _on_extension_error(self, error: ExtensionError) -> None:
2488
+ """扩展失败 → 会话事件。主流程继续,订阅方自行决定怎么呈现。"""
2489
+ await self._dispatch(
2490
+ ExtensionErrorEvent(extension=error.extension, event=error.event, error=error.error)
2491
+ )
2492
+
2493
+ async def _request_extension_compaction(
2494
+ self,
2495
+ preparation: CompactionPreparation,
2496
+ custom_instructions: str | None,
2497
+ reason: CompactionReason,
2498
+ will_retry: bool,
2499
+ ) -> CompactionResult | None:
2500
+ """问一次扩展要不要接管这次压缩。
2501
+
2502
+ 返回 ``None`` 表示"照常摘要",返回结果表示"用我给的摘要",抛
2503
+ :class:`CompactionCancelledByExtension` 表示"这次不压了"。
2504
+ """
2505
+ extensions = self._extensions
2506
+ if extensions is None or not extensions.has_handlers("session_before_compact"):
2507
+ return None
2508
+ result = await extensions.emit_session_before_compact(
2509
+ SessionBeforeCompactEvent(
2510
+ preparation=preparation,
2511
+ branch_entries=self._session.get_branch(),
2512
+ custom_instructions=custom_instructions,
2513
+ reason=reason,
2514
+ will_retry=will_retry,
2515
+ )
2516
+ )
2517
+ if result is None:
2518
+ return None
2519
+ if result.cancel:
2520
+ raise CompactionCancelledByExtension("Compaction cancelled by extension")
2521
+ return result.compaction
2522
+
2523
+ # ------------------------------------------------- 溢出恢复钩子路径
2524
+
2525
+ async def _check_overflow_recovery(self, message: AssistantMessage) -> bool:
2526
+ """溢出恢复:识别溢出 → 调一次恢复钩子 → 成功且可续跑时安排重试。
2527
+
2528
+ 这是**扩展覆盖路径**:显式传入的钩子优先于内建压缩。
2529
+ 恢复只尝试一次:``_overflow_recovery_attempted`` 在成功响应或新用户
2530
+ 输入时复位。
2531
+ """
2532
+ hook = self._overflow_recovery
2533
+ if hook is None:
2534
+ return False
2535
+ message_model = self._model_for_message(message)
2536
+ if message_model is None or message_model.context_window <= 0:
2537
+ # 产生这条消息的模型不在目录里:无法判定窗口,恢复无从谈起。
2538
+ return False
2539
+ if self._predates_latest_compaction(message):
2540
+ # 比最近一次压缩更早的消息是压缩前的旧账:它的 usage 反映的是旧
2541
+ # (更大)上下文,拿它触发恢复会让压缩紧接着压缩再来一次。
2542
+ return False
2543
+
2544
+ context_window = message_model.context_window
2545
+ overflow = is_context_overflow(message, context_window)
2546
+ truncated = self._is_output_truncation(message, message_model)
2547
+ if not (overflow or truncated):
2548
+ return False
2549
+
2550
+ will_retry = message.stop_reason != "stop"
2551
+ kind: Literal["error_overflow", "silent_overflow", "truncated_length"]
2552
+ if message.stop_reason == "error":
2553
+ kind = "error_overflow"
2554
+ elif message.stop_reason == "length":
2555
+ kind = "truncated_length"
2556
+ else:
2557
+ kind = "silent_overflow"
2558
+ request = OverflowRecoveryRequest(message=message, kind=kind, will_retry=will_retry)
2559
+
2560
+ if not will_retry:
2561
+ # 成功响应上的静默溢出:压缩只为下一次请求服务。agent.continue_()
2562
+ # 无法从一条"已经说完"的助手消息续跑,所以这里永不重试。
2563
+ await self._run_overflow_hook(hook, request)
2564
+ return self._agent.has_queued_messages()
2565
+
2566
+ if self._overflow_recovery_attempted:
2567
+ # 一次压缩没能救回来:放弃,原始错误保留为本次 run 的终态。
2568
+ return False
2569
+
2570
+ self._overflow_recovery_attempted = True
2571
+ self._omit_recovery_attempt(message)
2572
+ compacted = await self._run_overflow_hook(hook, request)
2573
+ if compacted:
2574
+ self._failed_response = message
2575
+ return True
2576
+ return False
2577
+
2578
+ async def _run_overflow_hook(
2579
+ self, hook: OverflowRecoveryHook, request: OverflowRecoveryRequest
2580
+ ) -> bool:
2581
+ result = hook(request)
2582
+ if inspect.isawaitable(result):
2583
+ result = await result
2584
+ return bool(result)
2585
+
2586
+ def _predates_latest_compaction(self, message: AssistantMessage) -> bool:
2587
+ """消息是否比当前分支上最近一次压缩更早。会话时间戳是 ISO 字符串。"""
2588
+ latest: CompactionEntry | None = None
2589
+ for entry in self._session.get_branch():
2590
+ if isinstance(entry, CompactionEntry):
2591
+ latest = entry
2592
+ if latest is None:
2593
+ return False
2594
+ return message.timestamp <= ms_from_iso(latest.timestamp)
2595
+
2596
+ def _omit_recovery_attempt(self, message: AssistantMessage) -> None:
2597
+ """把一次失败尝试(连同它引出的工具结果)从模型投影里省略。
2598
+
2599
+ "省略"是条目级的:原始历史不动,追加 ``context_edit(target, null)``,
2600
+ 投影重建时跳过这些条目。这样进程崩溃后恢复会话,失败尝试仍然不会
2601
+ 进入模型上下文——省略是**持久的**,靠内存里删消息做不到这一点。
2602
+ """
2603
+ tool_call_ids = {block.id for block in message.content if isinstance(block, ToolCall)}
2604
+ entry_id = self._entry_id_for(message)
2605
+ messages = self._agent.state.messages
2606
+ start = -1
2607
+ for index, candidate in enumerate(messages):
2608
+ if candidate is message or (
2609
+ entry_id is not None and self._entry_ids.get(id(candidate)) == entry_id
2610
+ ):
2611
+ start = index
2612
+ break
2613
+ tool_results: list[AgentMessage] = []
2614
+ if start >= 0:
2615
+ for candidate in messages[start + 1 :]:
2616
+ if candidate.role == "assistant":
2617
+ break
2618
+ if (
2619
+ candidate.role == "toolResult"
2620
+ and cast(ToolResultMessage, candidate).tool_call_id in tool_call_ids
2621
+ ):
2622
+ tool_results.append(candidate)
2623
+
2624
+ targets: list[AgentMessage] = [message, *tool_results]
2625
+ for target in targets:
2626
+ has_entry = self._entry_id_for(target) is not None
2627
+ if not has_entry and any(candidate is target for candidate in messages):
2628
+ raise RuntimeError(
2629
+ "Cannot persist recovery omission: a projected message has no source entry"
2630
+ )
2631
+ for target in targets:
2632
+ target_id = self._entry_id_for(target)
2633
+ if target_id is None:
2634
+ continue
2635
+ self._session.append_context_edit(target_id, None)
2636
+ self._refresh_finalized_context()
2637
+
2638
+ def _entry_id_for(self, message: AgentMessage) -> str | None:
2639
+ """消息对象 → 会话条目 id。
2640
+
2641
+ 先查本进程记录的映射;恢复的历史消息(没经过本进程的 ``message_end``)
2642
+ 退回按对象身份扫描分支。会话条目存的就是事件里那个对象,身份比较可靠。
2643
+ """
2644
+ entry_id = self._entry_ids.get(id(message))
2645
+ if entry_id is not None:
2646
+ return entry_id
2647
+ for entry in reversed(self._session.get_branch()):
2648
+ if isinstance(entry, SessionMessageEntry) and entry.message is message:
2649
+ self._entry_ids[id(message)] = entry.id
2650
+ return entry.id
2651
+ return None
2652
+
2653
+ def _refresh_finalized_context(self) -> None:
2654
+ """用会话投影覆盖 Agent 的转录。投影即事实:省略与压缩都体现在里面。"""
2655
+ context = self._session.build_context()
2656
+ self._agent.state.messages = _as_agent_messages(context.messages)
2657
+
2658
+ def _require_active(self) -> None:
2659
+ if self._disposed:
2660
+ raise RuntimeError("AgentSession has been disposed")
2661
+
2662
+
2663
+ def _as_thinking_level(value: str) -> ModelThinkingLevel:
2664
+ """会话文件里存的是字符串;不认识的值退回 ``off``。"""
2665
+ return value if value in _THINKING_LEVELS else "off" # type: ignore[return-value]
2666
+
2667
+
2668
+ def _as_agent_messages(messages: Sequence[ProjectedMessage]) -> list[AgentMessage]:
2669
+ """投影消息 → 转录消息。
2670
+
2671
+ ``branchSummary`` / ``compactionSummary`` 两种消息的 ``role`` 是 ``ClassVar``,
2672
+ 结构上不满足 ``CustomAgentMessage`` 对可变属性的要求(原因见
2673
+ :mod:`braid_agent.types` 的注解)。循环只读 ``role``,``convert_to_llm`` 按具体类型
2674
+ 分派,所以这里收窄成 ``AgentMessage`` 是安全的——真正不安全的做法是把它们丢掉,
2675
+ 那样摘要就永远进不了模型上下文。
2676
+ """
2677
+ return [cast(AgentMessage, message) for message in messages]
2678
+
2679
+
2680
+ __all__ = [
2681
+ "AgentEndWithRetryEvent",
2682
+ "AgentSession",
2683
+ "AgentSettledEvent",
2684
+ "AutoRetryEndEvent",
2685
+ "AutoRetryStartEvent",
2686
+ "CompactionCancelledByExtension",
2687
+ "CompactionEndEvent",
2688
+ "CompactionReason",
2689
+ "CompactionStartEvent",
2690
+ "ContextWarningEvent",
2691
+ "ExtensionErrorEvent",
2692
+ "ModelChangedEvent",
2693
+ "OverflowRecoveryHook",
2694
+ "OverflowRecoveryRequest",
2695
+ "PromptBuilder",
2696
+ "QueueUpdateEvent",
2697
+ "QueuedDisposition",
2698
+ "SessionEvent",
2699
+ "SessionListener",
2700
+ "SessionRecorder",
2701
+ "SessionUsage",
2702
+ "SummarizationRetryAttemptStartEvent",
2703
+ "SummarizationRetryFinishedEvent",
2704
+ "SummarizationRetryScheduledEvent",
2705
+ "ThinkingLevelChangedEvent",
2706
+ ]