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,823 @@
1
+ """渲染层:把会话事件变成终端上可以读的行。
2
+
3
+ 不做全屏 TUI,渲染策略退化成三条规则:
4
+
5
+ 1. **只追加**:助手文本、思考提示、工具摘要都编译成"一次写一行",不用光标上移;
6
+ 2. **状态行可以原地覆盖**:工具执行期间写一行不带换行的聚合状态(几个工具在跑、
7
+ 最近两个的名字、spinner),每次重画都用 ``\\r`` + ``\\x1b[K`` 覆盖同一行;
8
+ 输出被重定向到文件时(``live=False``)不写状态行,只留每个工具结束时的摘要行;
9
+ 3. **权威校正**:流式阶段按 delta 追加,``message_end`` 到达的官方消息才是事实;
10
+ 两者文本不一致时补一条校正行,而不是假装流式内容就是最终内容。
11
+
12
+ ## 为什么状态行是聚合的
13
+
14
+ 一批工具调用是并发执行的(见 ``braid_agent.loop`` 的并发执行器),``tool_execution_end``
15
+ 按完成顺序到达。行式渲染只有**一行**可以原地改写,于是并发的工具共用一行聚合状态:
16
+ 数量 + 最近两个标签 + spinner,每个工具结束时擦掉这行、追加它自己的摘要、再画回
17
+ 剩下的。这样第二个工具开始时不会把第一个的状态挤到同一行,第一个结束时也不会
18
+ 连带擦掉第二个。
19
+
20
+ ## 为什么 spinner 由调用方推进
21
+
22
+ 渲染器不读时钟(它只消费事件),测试才能对着确定的一帧断言。真实终端里一个跑了
23
+ 30 秒的 ``bash`` 需要看得见的进展,所以 :meth:`StreamRenderer.tick` 由交互模式按固定
24
+ 节拍调一次;非 TTY 下它是空操作。
25
+
26
+ ## 为什么折行要按显示宽度
27
+
28
+ ``len("你好")`` 是 2,终端上占 4 列;``len("🙂")`` 是 1,终端上占 2 列。用 ``len``
29
+ 折行会让中文与 emoji 的行在 80 列终端里溢出。这里用 :func:`wcwidth.wcswidth`
30
+ 量宽度,并在没有空格可断时按列硬断——
31
+ CJK 段落本来就没有空格可用。
32
+
33
+ ## 为什么渲染器不认识 Session
34
+
35
+ 它只消费 :data:`braid_coding_agent.session.agent_session.SessionEvent`,不持有会话、
36
+ 不发请求、不读时钟。这一层可以被单元测试直接喂事件序列(见
37
+ ``packages/braid-coding-agent/tests/repl/test_render.py``),也可以在
38
+ ``braid_coding_agent.modes.repl`` 里作为唯一的输出出口。
39
+
40
+ ## 主题与面板
41
+
42
+ ``RenderStyle.theme`` 提供浅色与深色两套 truecolor 配色,``color`` 为假时所有面板
43
+ 方法退化成纯文本行。命令面板的左列按 ``display_width`` 补齐,含中文的 usage 也落在
44
+ 同一列。底部状态行原地覆盖:写任何内容之前先擦掉它,内容输出完成后再重画;工具
45
+ 状态行在跑时占用同一行。输入前由 ``end_footer()`` 收尾,提示符从下一行开始。
46
+ """
47
+
48
+ from __future__ import annotations
49
+
50
+ import sys
51
+ from collections.abc import Callable, Mapping, Sequence
52
+ from dataclasses import dataclass, field
53
+ from typing import TextIO
54
+
55
+ from wcwidth import wcwidth
56
+
57
+ from braid_agent.tools import AgentToolResult
58
+ from braid_agent.types import (
59
+ AgentEndEvent,
60
+ LoopGuardTriggeredEvent,
61
+ MessageEndEvent,
62
+ MessageStartEvent,
63
+ MessageUpdateEvent,
64
+ ToolExecutionEndEvent,
65
+ ToolExecutionStartEvent,
66
+ )
67
+ from braid_ai.types import (
68
+ AssistantMessage,
69
+ JsonValue,
70
+ TextContent,
71
+ TextDeltaEvent,
72
+ TextEndEvent,
73
+ TextStartEvent,
74
+ ThinkingDeltaEvent,
75
+ ThinkingEndEvent,
76
+ ThinkingStartEvent,
77
+ ToolCallDeltaEvent,
78
+ ToolCallEndEvent,
79
+ ToolCallStartEvent,
80
+ )
81
+ from braid_coding_agent.session.agent_session import (
82
+ AgentEndWithRetryEvent,
83
+ AgentSettledEvent,
84
+ AutoRetryEndEvent,
85
+ AutoRetryStartEvent,
86
+ CompactionEndEvent,
87
+ CompactionStartEvent,
88
+ CompletionEvidenceEvent,
89
+ ContextWarningEvent,
90
+ ExtensionErrorEvent,
91
+ ModelChangedEvent,
92
+ PlanModeEvent,
93
+ PlanUpdateEvent,
94
+ QueueUpdateEvent,
95
+ SessionEvent,
96
+ ToolResultCleanupEvent,
97
+ )
98
+ from braid_coding_agent.tools.truncate import format_size
99
+
100
+ from .theme import (
101
+ LIGHT_THEME,
102
+ Theme,
103
+ display_width,
104
+ pad_to_width,
105
+ paint,
106
+ progress_bar,
107
+ )
108
+
109
+ __all__ = [
110
+ "RenderStyle",
111
+ "StreamRenderer",
112
+ "display_width",
113
+ "summarize_args",
114
+ "wrap_text",
115
+ ]
116
+
117
+ #: 旧的角色名映射到主题角色。调用点沿用 ``dim`` / ``red`` 这类名字,
118
+ #: 颜色值统一从 :class:`~braid_coding_agent.render.theme.Theme` 读取。
119
+ _ROLE_ALIASES: dict[str, str] = {
120
+ "dim": "muted",
121
+ "bold": "accent",
122
+ "red": "err",
123
+ "green": "ok",
124
+ "yellow": "warn",
125
+ "cyan": "user",
126
+ }
127
+
128
+ #: 面板左列的显示宽度;中文 usage 按 ``display_width`` 补齐后两列才对齐。
129
+ _PANEL_LEFT_WIDTH = 26
130
+
131
+ #: 工具参数里最值得显示给用户的键,按优先级排列。
132
+ _ARG_KEYS: tuple[str, ...] = ("path", "command", "pattern", "file_path", "query", "url")
133
+
134
+ #: 聚合状态行的 spinner 帧。只在交互终端里出现,纯文本输出里不存在。
135
+ _SPINNER_FRAMES: tuple[str, ...] = ("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")
136
+
137
+ #: 聚合状态行里单个工具标签的最大显示宽度。两个标签加上前缀要能落在一行里。
138
+ _STATUS_LABEL_WIDTH = 28
139
+
140
+ #: 压缩开始的提示语。三种触发原因的说法不同:手动是"我在等",阈值是"快满了",
141
+ #: 溢出是"已经撞上了,压缩后重试"。
142
+ _COMPACTION_START_TEXT: dict[str, str] = {
143
+ "manual": "手动压缩中…",
144
+ "threshold": "上下文接近上限,自动压缩中…",
145
+ "overflow": "上下文溢出,压缩后重试…",
146
+ }
147
+
148
+
149
+ def _guard_text(event: LoopGuardTriggeredEvent) -> str:
150
+ """护栏事件 → 一行中文。数字放在最前面,用户一眼看到"卡在哪"。
151
+
152
+ 三种护栏的后果不同,说法也不同:重复调用拦下的是一次调用(run 继续),
153
+ 另外两种是整次 run 到此为止。
154
+ """
155
+ if event.guard == "repeated_tool_call":
156
+ return (
157
+ f"连续 {event.repeats} 次相同的 {event.tool_name} 调用,已拦下这一次"
158
+ "(run 继续,模型会看到拦截原因)"
159
+ )
160
+ if event.guard == "request_budget":
161
+ return f"请求预算用尽({event.used}/{event.limit}),本次 run 结束"
162
+ return f"回合上限用尽({event.used}/{event.limit}),本次 run 结束"
163
+
164
+
165
+ @dataclass(slots=True)
166
+ class RenderStyle:
167
+ """渲染参数。``color`` 为假时输出纯文本,``theme`` 提供交互终端的配色。"""
168
+
169
+ width: int = 80
170
+ color: bool = True
171
+ theme: Theme = LIGHT_THEME
172
+
173
+
174
+ # ------------------------------------------------------------------ 宽度与折行
175
+
176
+
177
+ def wrap_text(text: str, width: int) -> list[str]:
178
+ """按显示宽度折行;保留原有换行,空行折成空串。"""
179
+ if width <= 0:
180
+ return [text]
181
+ lines: list[str] = []
182
+ for raw in text.split("\n"):
183
+ lines.extend(_wrap_line(raw, width))
184
+ return lines
185
+
186
+
187
+ def _wrap_line(line: str, width: int) -> list[str]:
188
+ """单行折行:有空格时按词断,没有空格(CJK 段落)时按列硬断。"""
189
+ if line == "":
190
+ return [""]
191
+ lines: list[str] = []
192
+ current: list[str] = []
193
+ current_width = 0
194
+ for char in line:
195
+ char_width = max(wcwidth(char), 1)
196
+ if current and current_width + char_width > width:
197
+ cut = _last_space_index(current)
198
+ if cut > 0:
199
+ lines.append("".join(current[:cut]))
200
+ current = current[cut + 1 :]
201
+ current_width = sum(max(wcwidth(item), 1) for item in current)
202
+ else:
203
+ lines.append("".join(current))
204
+ current = []
205
+ current_width = 0
206
+ current.append(char)
207
+ current_width += char_width
208
+ if current or not lines:
209
+ lines.append("".join(current))
210
+ return lines
211
+
212
+
213
+ def _last_space_index(chars: list[str]) -> int:
214
+ for index in range(len(chars) - 1, -1, -1):
215
+ if chars[index] == " ":
216
+ return index
217
+ return -1
218
+
219
+
220
+ # ------------------------------------------------------------------ 工具摘要
221
+
222
+
223
+ def summarize_args(args: Mapping[str, JsonValue]) -> str:
224
+ """从工具参数里挑一个最能说明"它在干什么"的值,截断到 40 列。
225
+
226
+ 显示的永远是模型给出的原文(``tool_execution_start.args``),不是修补后的参数:
227
+ 调试时想知道"模型到底说了什么",而结果里的 ``details`` 记录的是执行用的参数。
228
+ """
229
+ for key in _ARG_KEYS:
230
+ value = args.get(key)
231
+ if isinstance(value, str) and value.strip():
232
+ return _clip(value.strip(), 40)
233
+ for key, value in args.items():
234
+ if isinstance(value, str) and value.strip():
235
+ return f"{key}={_clip(value.strip(), 32)}"
236
+ return ""
237
+
238
+
239
+ def _clip(text: str, width: int) -> str:
240
+ """按显示宽度截断,超长补省略号。"""
241
+ if display_width(text) <= width:
242
+ return text
243
+ kept: list[str] = []
244
+ used = 0
245
+ for char in text:
246
+ char_width = max(wcwidth(char), 1)
247
+ if used + char_width > width - 1:
248
+ break
249
+ kept.append(char)
250
+ used += char_width
251
+ return "".join(kept) + "…"
252
+
253
+
254
+ def _result_size(result: AgentToolResult) -> str:
255
+ """工具结果的可见内容体积;只算文本块,图片按块数报。"""
256
+ text_bytes = 0
257
+ images = 0
258
+ for block in result.content:
259
+ if isinstance(block, TextContent):
260
+ text_bytes += len(block.text.encode("utf-8"))
261
+ else:
262
+ images += 1
263
+ if images:
264
+ return f"{format_size(text_bytes)}+{images}img"
265
+ return format_size(text_bytes)
266
+
267
+
268
+ # ------------------------------------------------------------------ 行写入器
269
+
270
+
271
+ @dataclass(slots=True)
272
+ class _LineWriter:
273
+ """流式文本的"未完成行"缓冲:够一行就吐出去,剩下的留着等下一个 delta。
274
+
275
+ 流式文本不能整段等 ``message_end`` 再打印(那样等于没有流式),也不能每个 delta
276
+ 都补一个换行(那样一句话被切成十几行)。折行状态因此必须跨 delta 保持。
277
+ """
278
+
279
+ emit: Callable[[str], None]
280
+ width: int
281
+ _current: list[str] = field(default_factory=list[str])
282
+ _current_width: int = 0
283
+
284
+ def feed(self, text: str) -> None:
285
+ for char in text:
286
+ if char == "\n":
287
+ self._flush_line()
288
+ continue
289
+ char_width = max(wcwidth(char), 1)
290
+ while self._current and self._current_width + char_width > self.width:
291
+ self._break_line()
292
+ self._current.append(char)
293
+ self._current_width += char_width
294
+
295
+ def finish(self) -> None:
296
+ """收尾:把残留的半行吐出去(``message_end``/``text_end`` 调用)。"""
297
+ if self._current:
298
+ self._flush_line()
299
+
300
+ def _break_line(self) -> None:
301
+ """一行满了:有空格就在最后一个空格处断(不拆开英文单词),否则按列硬断。
302
+
303
+ CJK 段落没有空格,所以中文永远是硬断——这与终端自己的折行行为一致。
304
+ 英文与路径反而必须按词断,否则 ``Ctrl+C`` 会被劈成 ``Ct`` / ``rl+C``。
305
+ """
306
+ cut = _last_space_index(self._current)
307
+ if cut > 0:
308
+ head = "".join(self._current[:cut])
309
+ rest = self._current[cut + 1 :]
310
+ else:
311
+ head = "".join(self._current)
312
+ rest = []
313
+ self.emit(head)
314
+ self._current = rest
315
+ self._current_width = sum(max(wcwidth(item), 1) for item in rest)
316
+
317
+ def _flush_line(self) -> None:
318
+ line = "".join(self._current)
319
+ self._current = []
320
+ self._current_width = 0
321
+ self.emit(line)
322
+
323
+
324
+ # ------------------------------------------------------------------- 渲染器
325
+
326
+
327
+ class StreamRenderer:
328
+ """把一次会话的事件流写成终端行。
329
+
330
+ :param out: 输出流(默认 stdout)。测试传 ``io.StringIO``。
331
+ :param style: 折行宽度与颜色开关。
332
+ :param live: 是否为交互终端。为真时工具状态行用 ``\\r`` 原地覆盖;为假时
333
+ 只输出最终摘要行——管道/日志里每个工具两行是噪音。
334
+ """
335
+
336
+ def __init__(
337
+ self,
338
+ out: TextIO | None = None,
339
+ *,
340
+ style: RenderStyle | None = None,
341
+ live: bool = False,
342
+ ) -> None:
343
+ self._out: TextIO = out if out is not None else sys.stdout
344
+ self._style = style if style is not None else RenderStyle()
345
+ self._live = live
346
+ self._writer: _LineWriter | None = None
347
+ #: 本条助手消息里每个内容块已经流出去的文本(按 contentIndex)。
348
+ self._streamed: dict[int, str] = {}
349
+ self._thinking_chars = 0
350
+ self._status_open = False
351
+ #: ``toolCallId`` → 标签,按启动顺序排列。并发执行时只有 id 能对回参数,
352
+ #: 聚合状态行也靠它算"现在有几个在跑、最近两个是谁"。
353
+ self._running_tools: dict[str, str] = {}
354
+ #: spinner 当前帧。只有 :meth:`tick` 推进它,事件渲染永远落在同一帧上。
355
+ self._spinner = 0
356
+ #: 底部状态行的文本,以及它是否停在屏幕最后一行。
357
+ self._footer_text: str | None = None
358
+ self._footer_open = False
359
+
360
+ # ------------------------------------------------------------ 外部入口
361
+
362
+ @property
363
+ def live(self) -> bool:
364
+ """是否在交互终端里原地改写状态行。交互模式据此决定要不要起 spinner 任务。"""
365
+ return self._live
366
+
367
+ @property
368
+ def visual(self) -> bool:
369
+ """是否启用主题色与面板装饰。管道输出保持纯文本。"""
370
+ return self._style.color
371
+
372
+ def tick(self) -> None:
373
+ """让聚合状态行的 spinner 走一格。没有工具在跑时什么都不做。
374
+
375
+ 节拍由调用方给(交互模式按固定间隔调):渲染器自己不读时钟,否则每一帧
376
+ 输出都带上"什么时候渲染的"这个不可复现的输入,快照测试就没法写。
377
+ """
378
+ if not self._live or not self._running_tools:
379
+ return
380
+ self._spinner = (self._spinner + 1) % len(_SPINNER_FRAMES)
381
+ self._render_status()
382
+
383
+ def handle(self, event: SessionEvent) -> None:
384
+ """一条会话事件 → 输出。未知事件(未来的扩展事件)静默忽略。"""
385
+ if isinstance(event, AgentEndWithRetryEvent):
386
+ if event.will_retry:
387
+ self.notice("请求失败,准备自动重试…")
388
+ return
389
+ if isinstance(event, AgentEndEvent):
390
+ return
391
+ if isinstance(event, AgentSettledEvent):
392
+ self._close_status()
393
+ return
394
+ if isinstance(event, MessageStartEvent):
395
+ if isinstance(event.message, AssistantMessage):
396
+ self._begin_message()
397
+ return
398
+ if isinstance(event, MessageUpdateEvent):
399
+ self._on_update(event)
400
+ return
401
+ if isinstance(event, MessageEndEvent):
402
+ self._on_message_end(event.message)
403
+ return
404
+ if isinstance(event, ToolExecutionStartEvent):
405
+ self._on_tool_start(event.tool_call_id, event.tool_name, event.args)
406
+ return
407
+ if isinstance(event, ToolExecutionEndEvent):
408
+ self._on_tool_end(
409
+ event.tool_call_id, event.tool_name, event.result, event.is_error, event.duration_ms
410
+ )
411
+ return
412
+ if isinstance(event, AutoRetryStartEvent):
413
+ self.notice(
414
+ f"自动重试 {event.attempt}/{event.max_attempts}"
415
+ f"({event.delay_ms}ms 后):{_clip(event.error_message, 60)}"
416
+ )
417
+ return
418
+ if isinstance(event, AutoRetryEndEvent):
419
+ if event.success:
420
+ self.notice(f"重试成功(第 {event.attempt} 次)")
421
+ else:
422
+ self.error(f"重试放弃:{_clip(event.final_error or '未知错误', 80)}")
423
+ return
424
+ if isinstance(event, CompactionStartEvent):
425
+ self.notice(_COMPACTION_START_TEXT.get(event.reason, "压缩中…"))
426
+ return
427
+ if isinstance(event, CompactionEndEvent):
428
+ self._on_compaction_end(event)
429
+ return
430
+ if isinstance(event, QueueUpdateEvent):
431
+ for text in event.steering:
432
+ self.notice(f"已排队(steer):{_clip(text, 60)}")
433
+ for text in event.follow_up:
434
+ self.notice(f"已排队(follow-up):{_clip(text, 60)}")
435
+ return
436
+ if isinstance(event, ModelChangedEvent):
437
+ self.notice(f"模型切换为 {event.model.provider}/{event.model.id}")
438
+ return
439
+ if isinstance(event, ExtensionErrorEvent):
440
+ # 隔离不等于静默:扩展失败了要说出来,否则用户以为那条规则还生效。
441
+ self.notice(f"扩展 {event.extension} 在 {event.event} 上失败:{_clip(event.error, 80)}")
442
+ return
443
+ if isinstance(event, LoopGuardTriggeredEvent):
444
+ self.warning(_guard_text(event))
445
+ return
446
+ if isinstance(event, CompletionEvidenceEvent):
447
+ self._on_completion_evidence(event)
448
+ return
449
+ if isinstance(event, ContextWarningEvent):
450
+ self.warning(
451
+ f"上下文接近自动压缩:已用 {event.tokens}/{event.context_window} tokens,"
452
+ f"距触发线 {event.threshold} 还剩 {event.remaining_tokens} tokens"
453
+ f"({event.remaining_percent:.1f}%)"
454
+ )
455
+ return
456
+ if isinstance(event, ToolResultCleanupEvent):
457
+ self.notice(
458
+ f"已清理 {event.cleared} 条旧工具结果"
459
+ f"({event.chars_before}→{event.chars_after} 字符)"
460
+ )
461
+ return
462
+ if isinstance(event, PlanUpdateEvent):
463
+ self._on_plan_update(event)
464
+ return
465
+ if isinstance(event, PlanModeEvent):
466
+ self._on_plan_mode(event)
467
+ return
468
+
469
+ # ------------------------------------------------------------ 普通输出
470
+
471
+ def write_line(self, text: str = "", role: str | None = None) -> None:
472
+ """写一行(自动折行),``role`` 在交互终端里决定颜色。"""
473
+ for line in wrap_text(text, self._style.width):
474
+ painted = self._paint(line, role) if role is not None and self.visual else line
475
+ self._write(painted + "\n")
476
+
477
+ def notice(self, text: str) -> None:
478
+ """提示信息:暗色、单行、可以随时忽略。"""
479
+ self._close_status()
480
+ self._write(self._paint(f"· {text}", "dim") + "\n")
481
+
482
+ def warning(self, text: str) -> None:
483
+ """警告:值得看一眼,但没有失败。护栏与未验证结论走这一档。"""
484
+ self._close_status()
485
+ self._write(self._paint(f"[注意] {text}", "yellow") + "\n")
486
+
487
+ def error(self, text: str) -> None:
488
+ """错误信息:红色,出现在它该出现的位置(不换到下一个提示符之后)。"""
489
+ self._close_status()
490
+ self._write(self._paint(f"[错误] {text}", "red") + "\n")
491
+
492
+ def write_user(self, text: str) -> None:
493
+ """回显一条用户输入。
494
+
495
+ 交互终端里 ``prompt_toolkit`` 已经把输入那行留在屏幕上了,但脚本化的
496
+ stdin(管道/测试)没有——统一在这里回显,两种来源的输出形状才一致。
497
+ """
498
+ self._close_status()
499
+ first, *rest = wrap_text(text, max(self._style.width - 4, 8))
500
+ if self.visual:
501
+ self._write(self._paint("▌ 用户", "user") + " " + first + "\n")
502
+ else:
503
+ self._write(self._paint(f"braid> {first}", "cyan") + "\n")
504
+ for line in rest:
505
+ self._write(" " + line + "\n")
506
+
507
+ def status_line(self, text: str) -> None:
508
+ """TTY 下原地刷新底部状态行;非 TTY 完全不写。
509
+
510
+ 输出任何内容之前先擦掉状态行,内容输出完成后再重画。工具状态行在跑时占用
511
+ 同一行,此时状态行让位。纯文本输出整行省略,管道消费方只看到回答与命令输出。
512
+ """
513
+ self._close_status()
514
+ if not self._live or not self.visual:
515
+ return
516
+ if self._footer_open and text == self._footer_text:
517
+ return
518
+ self._clear_footer()
519
+ if self._running_tools:
520
+ return
521
+ self._write_raw("\r\x1b[K" + self._paint(f"· {text}", "accent"))
522
+ self._footer_open = True
523
+ self._footer_text = text
524
+
525
+ def end_footer(self) -> None:
526
+ """输入前把状态行收尾,提示符从下一行开始。"""
527
+ if self._footer_open:
528
+ self._write_raw("\n")
529
+ self._footer_open = False
530
+
531
+ # -------------------------------------------------------------- 面板
532
+
533
+ def section(self, title: str, subtitle: str | None = None) -> None:
534
+ """命令面板标题。纯文本输出保持原来的标题行。"""
535
+ self._close_status()
536
+ if not self.visual:
537
+ self.write_line(title)
538
+ if subtitle:
539
+ self.notice(subtitle)
540
+ return
541
+ self._write(self._paint(title, "accent", bold=True) + "\n")
542
+ if subtitle:
543
+ self._write(self._paint(subtitle, "muted") + "\n")
544
+ self.rule()
545
+
546
+ def rule(self) -> None:
547
+ """交互终端里画一条分隔线;纯文本输出不增加行。"""
548
+ if not self.visual:
549
+ return
550
+ self._write(self._paint("─" * self._style.width, "border") + "\n")
551
+
552
+ def key_value(self, pairs: Sequence[tuple[str, str]]) -> None:
553
+ """两列键值。键按显示宽度补齐,中文标签也在同一列起始。"""
554
+ for key, value in pairs:
555
+ if self.visual:
556
+ self._write(self._paint(pad_to_width(key, 12), "muted") + " " + value + "\n")
557
+ else:
558
+ self._write(f"· {key} {value}\n")
559
+
560
+ def progress(self, label: str, percent: float, detail: str) -> None:
561
+ """上下文占用。纯文本输出保留百分比与明细。"""
562
+ self._close_status()
563
+ if not self.visual:
564
+ self.notice(f"{label}:{detail} · {percent:.1f}%")
565
+ return
566
+ bar = self._paint(progress_bar(percent), "warn" if percent >= 80 else "accent")
567
+ self._write(
568
+ self._paint(label, "muted") + " " + bar + f" {percent:.1f}% " + detail + "\n"
569
+ )
570
+
571
+ def panel_row(self, left: str, right: str, *, tag: str | None = None) -> None:
572
+ """两列面板行;左列按显示宽度补齐,状态标记放在右列。"""
573
+ self._close_status()
574
+ padded = pad_to_width(left, _PANEL_LEFT_WIDTH)
575
+ marked = f"[{tag}] {right}" if tag else right
576
+ if self.visual:
577
+ self._write(
578
+ self._paint("· ", "muted")
579
+ + self._paint(padded, "fg")
580
+ + " "
581
+ + self._paint(marked, "muted")
582
+ + "\n"
583
+ )
584
+ else:
585
+ self._write(f"· {padded} {marked}\n")
586
+
587
+ # --------------------------------------------------------- 消息内部状态
588
+
589
+ def _begin_message(self) -> None:
590
+ self._close_status()
591
+ self._streamed = {}
592
+ self._thinking_chars = 0
593
+ self._writer = _LineWriter(emit=self._write_stream_line, width=self._style.width)
594
+
595
+ def _on_update(self, event: MessageUpdateEvent) -> None:
596
+ inner = event.assistant_message_event
597
+ if isinstance(inner, TextStartEvent):
598
+ # 新的文本块从新的一行开始:上一个块可能停在半行(没有以换行结尾),
599
+ # 不先收尾两个块会在终端里连成一句。
600
+ self._finish_text()
601
+ return
602
+ if isinstance(inner, TextEndEvent):
603
+ self._streamed[inner.content_index] = inner.content
604
+ # 块结束就是行结束:后面无论是第二个文本块还是工具摘要,都不该接在这行后面。
605
+ self._finish_text()
606
+ return
607
+ if isinstance(inner, TextDeltaEvent):
608
+ self._streamed[inner.content_index] = (
609
+ self._streamed.get(inner.content_index, "") + inner.delta
610
+ )
611
+ self._feed(inner.delta)
612
+ return
613
+ if isinstance(inner, ThinkingStartEvent):
614
+ self._close_status()
615
+ self._finish_text()
616
+ self._thinking_chars = 0
617
+ return
618
+ if isinstance(inner, ThinkingDeltaEvent):
619
+ self._thinking_chars += len(inner.delta)
620
+ return
621
+ if isinstance(inner, ThinkingEndEvent):
622
+ prefix = "◌ " if self.visual else ""
623
+ self.notice(f"{prefix}思考 {self._thinking_chars} 字(已折叠)")
624
+ return
625
+ if isinstance(inner, (ToolCallStartEvent, ToolCallEndEvent, ToolCallDeltaEvent)):
626
+ # 工具调用的生命周期由 tool_execution_* 事件播报:那里有执行状态与耗时,
627
+ # 这里再打印一次 "正在生成参数" 只会让屏幕滚动。
628
+ return
629
+
630
+ def _on_message_end(self, message: object) -> None:
631
+ if not isinstance(message, AssistantMessage):
632
+ return
633
+ self._close_status()
634
+ self._finish_text()
635
+ for index, block in enumerate(message.content):
636
+ if not isinstance(block, TextContent):
637
+ continue
638
+ streamed = self._streamed.get(index)
639
+ if streamed is not None and streamed != block.text and block.text:
640
+ # 流式内容与官方消息不一致:Provider 改了文本、或 end 事件晚到。
641
+ # 权威消息才是模型真的说了什么,补一条完整版本,别让屏幕留住半句。
642
+ self.notice("流式内容与最终消息不一致,以下为完整回答:")
643
+ for line in wrap_text(block.text, self._style.width):
644
+ self._write(line + "\n")
645
+ if message.stop_reason == "error":
646
+ self.error(message.error_message or "请求失败")
647
+ elif message.stop_reason == "aborted":
648
+ self.error("已取消")
649
+ elif message.stop_reason == "length":
650
+ self.notice("回答被输出长度上限截断")
651
+ self._streamed = {}
652
+ self._thinking_chars = 0
653
+
654
+ # ------------------------------------------------------------- 工具状态
655
+
656
+ def _on_tool_start(self, tool_call_id: str, name: str, args: Mapping[str, JsonValue]) -> None:
657
+ """记下这次调用,交互终端里再重画聚合状态行。
658
+
659
+ 标签按 ``toolCallId`` 存:执行阶段是并发的,``tool_execution_end`` 按完成
660
+ 顺序到达,只有 id 能把摘要对回它自己的参数。
661
+ """
662
+ self._finish_text()
663
+ label = f"{name} {summarize_args(args)}".strip()
664
+ self._running_tools[tool_call_id] = label
665
+ self._render_status()
666
+
667
+ def _on_tool_end(
668
+ self,
669
+ tool_call_id: str,
670
+ name: str,
671
+ result: AgentToolResult,
672
+ is_error: bool,
673
+ duration_ms: int | None,
674
+ ) -> None:
675
+ """折叠成一行摘要:``✓ read notes.txt · 12ms · 1.2KB``。
676
+
677
+ 摘要带参数(而不是只有工具名):这一行是用户回头翻记录时唯一的线索,
678
+ ``✓ read`` 后面不跟路径就等于什么都没说。
679
+
680
+ 顺序是"擦掉聚合状态行 → 写摘要 → 重画剩下那些"。反过来会先写摘要再擦,
681
+ 擦的时候连摘要一起擦掉;只擦不重画,则还在跑的第二个工具就没有状态了。
682
+ """
683
+ label = self._running_tools.pop(tool_call_id, name)
684
+ mark = "✗" if is_error else "✓"
685
+ color = "red" if is_error else "green"
686
+ metrics = [_result_size(result)]
687
+ if duration_ms is not None:
688
+ metrics.insert(0, f"{duration_ms}ms")
689
+ line = self._paint(f"{mark} {label} · " + " · ".join(metrics), color)
690
+ if self._status_open:
691
+ # \r 回到行首,\x1b[K 清到行尾:这一行本来就是状态,用完就该消失。
692
+ self._write("\r\x1b[K")
693
+ self._status_open = False
694
+ self._write(line + "\n")
695
+ self._render_status()
696
+
697
+ def _on_compaction_end(self, event: CompactionEndEvent) -> None:
698
+ if event.aborted:
699
+ self.error("压缩已取消")
700
+ return
701
+ if event.result is None:
702
+ self.error(event.error_message or "压缩失败")
703
+ return
704
+ after = event.result.estimated_tokens_after
705
+ tail = f" → 约 {after} tokens" if after is not None else ""
706
+ self.notice(f"压缩完成:{event.result.tokens_before} tokens{tail}")
707
+
708
+ def _on_completion_evidence(self, event: CompletionEvidenceEvent) -> None:
709
+ """改了文件却没有验证:说出结论缺什么,而不是替用户判定对错。"""
710
+ if not event.unverified:
711
+ return
712
+ files = "、".join(event.modified_paths[:3])
713
+ more = f" 等 {len(event.modified_paths)} 个文件" if len(event.modified_paths) > 3 else ""
714
+ self.warning(f"未验证:改了 {files}{more},这次 run 没有执行任何验证命令")
715
+
716
+ def _on_plan_update(self, event: PlanUpdateEvent) -> None:
717
+ """计划每次真实变化都完整重印一遍。
718
+
719
+ 行式渲染没有"原地更新第 3 行"的能力,也不该有:终端回滚时用户翻到的每一版
720
+ 计划都是当时的事实。清空计划时只说一句——一份空列表印出来等于噪音。
721
+ """
722
+ self._close_status()
723
+ state = event.state
724
+ if state.is_empty:
725
+ self.notice("计划已清空")
726
+ return
727
+ header = (
728
+ f"计划(第 {state.revision} 版 · {state.completed}/{state.total} 完成"
729
+ + (f" · 正在做:{state.current.step}" if state.current is not None else "")
730
+ + "):"
731
+ )
732
+ self._write(self._paint(f"· {header}", "dim") + "\n")
733
+ for line in state.lines():
734
+ self._write(" " + line + "\n")
735
+
736
+ def _on_plan_mode(self, event: PlanModeEvent) -> None:
737
+ """规划模式的状态变化。
738
+
739
+ 计划正文在这里完整印一遍:审批提示只说"以上计划是否批准",用户要先看到计划
740
+ 才能回答。其余几个状态只印一行——它们是模式的开关,不是内容。
741
+ """
742
+ self._close_status()
743
+ state = event.state
744
+ if event.reason == "submitted":
745
+ header = f"实施计划(第 {state.revision} 版"
746
+ header += f" · {state.goal})" if state.goal else ")"
747
+ self._write(self._paint(f"· {header}:", "dim") + "\n")
748
+ for line in state.plan.splitlines():
749
+ self.write_line(line)
750
+ self._write(
751
+ self._paint("· 计划已提交,等待批准;批准之前不会产生任何文件改动", "dim") + "\n"
752
+ )
753
+ return
754
+ labels = {
755
+ "entered": "已进入规划模式(只读)",
756
+ "approved": f"已批准第 {state.revision} 版计划,规划模式已退出",
757
+ "revised": f"保持规划模式,第 {state.revision} 版计划待修改",
758
+ "left": "已退出规划模式",
759
+ }
760
+ self.notice(labels.get(event.reason, "规划模式状态变化"))
761
+
762
+ # ---------------------------------------------------------------- 底层
763
+
764
+ def _feed(self, text: str) -> None:
765
+ if self._writer is None:
766
+ self._begin_message()
767
+ assert self._writer is not None
768
+ self._writer.feed(text)
769
+
770
+ def _finish_text(self) -> None:
771
+ if self._writer is not None:
772
+ self._writer.finish()
773
+ self._writer = None
774
+
775
+ def _close_status(self) -> None:
776
+ """状态行没收尾就换行——否则后续输出会接在它后面。"""
777
+ if self._status_open:
778
+ self._write("\n")
779
+ self._status_open = False
780
+
781
+ def _render_status(self) -> None:
782
+ """重画聚合状态行。非交互终端不写(重定向到文件时 ``\\r`` 是乱码)。
783
+
784
+ 已经有一行状态时用 ``\\r\\x1b[K`` 原地替换,否则新起一行——两种情况写出的
785
+ 东西必须让用户看到"同一行在变",而不是每来一个工具就多一行。
786
+ """
787
+ if not self._live or not self._running_tools:
788
+ return
789
+ prefix = "\r\x1b[K" if self._status_open else ""
790
+ self._write(prefix + self._paint(f"· {self._status_text()} ", "dim"))
791
+ self._status_open = True
792
+
793
+ def _status_text(self) -> str:
794
+ """状态行正文:``2 个工具运行中:read a.txt、bash ls ⠋``。
795
+
796
+ 只列最近启动的两个:行式渲染只有一行,工具再多也只能挑最相关的两个;
797
+ 总数放在最前面,用户仍然知道"还有几个没结束"。
798
+ """
799
+ labels = list(self._running_tools.values())
800
+ shown = "、".join(_clip(label, _STATUS_LABEL_WIDTH) for label in labels[-2:])
801
+ return f"{len(labels)} 个工具运行中:{shown} {_SPINNER_FRAMES[self._spinner]}"
802
+
803
+ def _write_stream_line(self, line: str) -> None:
804
+ self._write(line + "\n")
805
+
806
+ def _clear_footer(self) -> None:
807
+ if self._footer_open:
808
+ self._write_raw("\r\x1b[K")
809
+ self._footer_open = False
810
+
811
+ def _write(self, text: str) -> None:
812
+ self._clear_footer()
813
+ self._write_raw(text)
814
+
815
+ def _write_raw(self, text: str) -> None:
816
+ self._out.write(text)
817
+ self._out.flush()
818
+
819
+ def _paint(self, text: str, color: str, *, bold: bool = False) -> str:
820
+ if not self._style.color:
821
+ return text
822
+ role = _ROLE_ALIASES.get(color, color)
823
+ return paint(text, role, self._style.theme, bold=bold or color == "bold")