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,751 @@
1
+ """Rich 渲染层:把内容块翻成按行组织的终端片段。
2
+
3
+ Rich 负责 Markdown、代码高亮、Diff、Panel 与进度条;这一层把 Rich 渲染出的
4
+ ``Segment`` 转成 prompt_toolkit 能直接消费的 ``(样式, 文本)`` 片段。样式用
5
+ inline 形式(``fg:#rrggbb bold``),不依赖预定义的样式类。
6
+
7
+ 每次渲染都以终端宽度为输入:Rich 自己折行,prompt_toolkit 的窗口不再二次折行,
8
+ 中英文混排与宽字符的宽度计算只发生一次。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+ from functools import lru_cache
15
+ from itertools import pairwise
16
+ from typing import IO, TYPE_CHECKING, ClassVar, cast
17
+
18
+ from prompt_toolkit.formatted_text import FormattedText
19
+ from rich.color import Color
20
+ from rich.console import Console, ConsoleOptions, Group, JustifyMethod, RenderableType, RenderResult
21
+ from rich.panel import Panel
22
+ from rich.progress_bar import ProgressBar
23
+ from rich.segment import Segment
24
+ from rich.style import Style as RichStyle
25
+ from rich.syntax import Syntax
26
+ from rich.text import Text
27
+ from rich.theme import Theme as RichTheme
28
+ from wcwidth import wcswidth
29
+
30
+ from braid_coding_agent.render.theme import LIGHT_THEME, THEMES, Theme
31
+ from braid_coding_agent.statusline import StatusLineValues, render_status_line
32
+
33
+ from .tui_model import StatusView, TuiSnapshot
34
+ from .tui_render import (
35
+ RenderBlock,
36
+ TuiRenderState,
37
+ overlay_blocks,
38
+ plan_block,
39
+ status_block,
40
+ transcript_blocks,
41
+ )
42
+
43
+ if TYPE_CHECKING:
44
+ from rich.markdown import Markdown
45
+
46
+ __all__ = [
47
+ "completion_fragments",
48
+ "overlay_line_count",
49
+ "render_blocks",
50
+ "render_snapshot",
51
+ "style_for_rich",
52
+ "to_formatted_text",
53
+ ]
54
+
55
+ #: 片段只有二元组:样式字符串与文本。prompt_toolkit 的控件直接接受这种结构。
56
+ type Fragment = tuple[str, str]
57
+ type FragmentLine = list[Fragment]
58
+
59
+ #: 代码块与 Diff 用的高亮主题。两者都是深色底,在浅色与深色终端上都保持可读。
60
+ CODE_THEME = "monokai"
61
+ DIFF_THEME = "ansi_light"
62
+
63
+ #: 思考卡片折叠时保留的末尾行数。
64
+ THINKING_PREVIEW_LINES = 3
65
+
66
+
67
+ @lru_cache(maxsize=1)
68
+ def _left_markdown_class() -> type[Markdown]:
69
+ """按需导入 Rich 的 Markdown 渲染器并造出左对齐子类。
70
+
71
+ ``rich.markdown`` 会连带导入一整套 Markdown 元素与样式解析,超过 100 毫秒。
72
+ 首帧只有输入框与状态栏,第一次回答到达之前用不到它。
73
+ """
74
+ from rich.markdown import Heading, Markdown, MarkdownElement
75
+
76
+ class _LeftHeading(Heading):
77
+ """标题一律左对齐:会话记录里居中的一级标题会让整段文字错位。"""
78
+
79
+ LEVEL_ALIGN: ClassVar[dict[str, JustifyMethod]] = {
80
+ "h1": "left",
81
+ "h2": "left",
82
+ "h3": "left",
83
+ "h4": "left",
84
+ "h5": "left",
85
+ "h6": "left",
86
+ }
87
+
88
+ class _LeftMarkdown(Markdown):
89
+ elements: ClassVar[dict[str, type[MarkdownElement]]] = {
90
+ **Markdown.elements,
91
+ "heading_open": _LeftHeading,
92
+ }
93
+
94
+ return _LeftMarkdown
95
+
96
+
97
+ def _left_markdown(text: str) -> RenderableType:
98
+ return _left_markdown_class()(text, code_theme=CODE_THEME, justify="left")
99
+
100
+
101
+ def _rich_theme(theme: Theme) -> RichTheme:
102
+ """把 braid 的调色板映射到 Rich 的 Markdown 样式名。"""
103
+ fg = theme.color("fg")
104
+ muted = theme.color("muted")
105
+ accent = theme.color("accent")
106
+ user = theme.color("user")
107
+ border = theme.color("border")
108
+ return RichTheme(
109
+ {
110
+ "markdown.h1": RichStyle(bold=True, underline=True, color=fg),
111
+ "markdown.h2": RichStyle(bold=True, color=fg),
112
+ "markdown.h3": RichStyle(bold=True, color=fg),
113
+ "markdown.h4": RichStyle(bold=True, color=muted),
114
+ "markdown.h5": RichStyle(bold=True, color=muted),
115
+ "markdown.h6": RichStyle(bold=True, color=muted),
116
+ "markdown.item.bullet": RichStyle(color=accent),
117
+ "markdown.item.number": RichStyle(color=accent),
118
+ "markdown.code": RichStyle(color=accent, bold=True),
119
+ "markdown.code_block": RichStyle(color=fg),
120
+ "markdown.block_quote": RichStyle(color=muted),
121
+ "markdown.link": RichStyle(color=user, underline=True),
122
+ "markdown.link_url": RichStyle(color=muted),
123
+ "markdown.hr": RichStyle(color=border),
124
+ "markdown.table.header": RichStyle(bold=True, color=fg),
125
+ "markdown.table.border": RichStyle(color=border),
126
+ "markdown.emph": RichStyle(italic=True),
127
+ "markdown.strong": RichStyle(bold=True),
128
+ },
129
+ inherit=True,
130
+ )
131
+
132
+
133
+ class _Sink:
134
+ """Console 的丢弃输出端:这里只用 ``render_lines``,不写任何字节。"""
135
+
136
+ encoding = "utf-8"
137
+
138
+ def write(self, text: str) -> int:
139
+ return len(text)
140
+
141
+ def flush(self) -> None:
142
+ return None
143
+
144
+ def isatty(self) -> bool:
145
+ return True
146
+
147
+
148
+ @lru_cache(maxsize=16)
149
+ def _console(width: int, theme_name: str) -> Console:
150
+ """按宽度与主题复用 Console。渲染只发生在事件循环线程,复用是安全的。"""
151
+ return Console(
152
+ file=cast("IO[str]", _Sink()),
153
+ width=max(1, width),
154
+ force_terminal=True,
155
+ color_system="truecolor",
156
+ theme=_rich_theme(THEMES[theme_name]),
157
+ legacy_windows=False,
158
+ safe_box=False,
159
+ highlight=False,
160
+ )
161
+
162
+
163
+ @lru_cache(maxsize=512)
164
+ def _hex(color: Color, foreground: bool) -> str:
165
+ triplet = color.get_truecolor(foreground=foreground)
166
+ return f"#{triplet.red:02x}{triplet.green:02x}{triplet.blue:02x}"
167
+
168
+
169
+ def style_for_rich(style: RichStyle | None) -> str:
170
+ """Rich 的 Style 转成 prompt_toolkit 的 inline 样式字符串。
171
+
172
+ 两边支持的属性是同一组(bold/dim/italic/underline/blink/reverse/strike),
173
+ 颜色统一成 truecolor 十六进制,由 prompt_toolkit 按终端能力降级。
174
+ """
175
+ if style is None:
176
+ return ""
177
+ parts: list[str] = []
178
+ if style.color is not None:
179
+ parts.append(f"fg:{_hex(style.color, True)}")
180
+ if style.bgcolor is not None:
181
+ parts.append(f"bg:{_hex(style.bgcolor, False)}")
182
+ for flag, name in (
183
+ (style.bold, "bold"),
184
+ (style.dim, "dim"),
185
+ (style.italic, "italic"),
186
+ (style.underline, "underline"),
187
+ (style.blink, "blink"),
188
+ (style.reverse, "reverse"),
189
+ (style.strike, "strike"),
190
+ ):
191
+ if flag:
192
+ parts.append(name)
193
+ return " ".join(parts)
194
+
195
+
196
+ def _segments_to_line(segments: list[Segment]) -> FragmentLine:
197
+ """把一行 Segment 合并成片段,并去掉行尾的纯空白填充。
198
+
199
+ Rich 会把段落补齐到渲染宽度;终端里看不见,但会进入 golden 与宽度断言。
200
+ 带背景色的填充是代码块与面板的一部分,必须保留。
201
+ """
202
+ line: FragmentLine = []
203
+ for segment in segments:
204
+ if not segment.text:
205
+ continue
206
+ style = style_for_rich(segment.style)
207
+ if line and line[-1][0] == style:
208
+ line[-1] = (style, line[-1][1] + segment.text)
209
+ continue
210
+ line.append((style, segment.text))
211
+ while line:
212
+ style, text = line[-1]
213
+ trimmed = text.rstrip()
214
+ if trimmed == text:
215
+ break
216
+ if trimmed:
217
+ line[-1] = (style, trimmed)
218
+ break
219
+ if "bg:" in style:
220
+ break
221
+ line.pop()
222
+ return line
223
+
224
+
225
+ def _render(console: Console, renderable: RenderableType, width: int) -> list[FragmentLine]:
226
+ options = console.options.update(width=max(1, width), height=None)
227
+ segments = console.render_lines(renderable, options, pad=False)
228
+ return [_segments_to_line(line) for line in segments]
229
+
230
+
231
+ def _trim(lines: list[FragmentLine]) -> list[FragmentLine]:
232
+ """去掉块首尾的空行;块之间的间隔由 :func:`render_blocks` 统一插入。"""
233
+ start = 0
234
+ end = len(lines)
235
+ while start < end and not "".join(text for _, text in lines[start]).strip():
236
+ start += 1
237
+ while end > start and not "".join(text for _, text in lines[end - 1]).strip():
238
+ end -= 1
239
+ return lines[start:end]
240
+
241
+
242
+ def _prefix(text: str, prefix: str, style: str, body: str) -> Text:
243
+ """给多行文本加首行前缀,续行用等宽空白对齐。"""
244
+ pad = " " * max(0, wcswidth(prefix))
245
+ result = Text()
246
+ for index, line in enumerate(text.splitlines() or [""]):
247
+ if index:
248
+ result.append("\n")
249
+ result.append(prefix if index == 0 else pad, style=style)
250
+ result.append(line, style=body)
251
+ return result
252
+
253
+
254
+ def _notice_style(level: str, theme: Theme) -> str:
255
+ role = level if level in ("ok", "warn", "err") else "muted"
256
+ return theme.color(role)
257
+
258
+
259
+ def _plan_renderable(block: RenderBlock, width: int, theme: Theme) -> RenderableType:
260
+ text = Text()
261
+ title = "▤ 规划" if block.label == "规划中" else "▤ 计划"
262
+ text.append(title, style=f"bold {theme.color('accent')}")
263
+ if block.label:
264
+ text.append(f" · {block.label}", style=theme.color("muted"))
265
+ if block.total:
266
+ text.append(f" {block.completed}/{block.total}", style=theme.color("muted"))
267
+ text.append(f" · v{block.revision}", style=theme.color("muted"))
268
+ bar_width = min(16, max(6, width // 4))
269
+ if width >= 48 and block.total:
270
+ text.append(" ")
271
+ text.append("█" * round(block.completed / block.total * bar_width), style=theme.color("ok"))
272
+ text.append(
273
+ "░" * (bar_width - round(block.completed / block.total * bar_width)),
274
+ style=theme.color("border"),
275
+ )
276
+ # 实施计划正文在上,执行步骤表在下:正文是"要做什么",步骤表是"做到哪了"。
277
+ # 批准之后正文仍然保留:执行期间要能回头对照计划,而不是只剩进度。
278
+ if block.document:
279
+ text.append("\n")
280
+ text.append(block.document, style=theme.color("fg"))
281
+ for line in block.lines:
282
+ text.append("\n")
283
+ if line.startswith("[x]"):
284
+ text.append("✓ ", style=theme.color("ok"))
285
+ text.append(line[3:].strip(), style=theme.color("muted"))
286
+ elif line.startswith("[>]"):
287
+ text.append("▸ ", style=theme.color("accent"))
288
+ text.append(line[3:].strip(), style=f"bold {theme.color('fg')}")
289
+ else:
290
+ text.append("· ", style=theme.color("muted"))
291
+ body = line[3:].strip() if line.startswith("[ ]") else line
292
+ text.append(body, style=theme.color("muted"))
293
+ return text
294
+
295
+
296
+ def _fit(text: str, max_width: int) -> str:
297
+ """按显示宽度截断,不切断宽字符。"""
298
+ if max_width <= 0:
299
+ return ""
300
+ if wcswidth(text) <= max_width:
301
+ return text
302
+ out = ""
303
+ for char in text:
304
+ if wcswidth(out + char) > max_width:
305
+ break
306
+ out += char
307
+ return out
308
+
309
+
310
+ @dataclass(slots=True)
311
+ class _StatusEntry:
312
+ """状态栏里的一个字段:键名、显示文本、颜色、加粗与占位宽度。"""
313
+
314
+ key: str
315
+ text: str
316
+ style: str
317
+ bold: bool = False
318
+ width: int = 0
319
+
320
+
321
+ def _separator_width(previous: _StatusEntry, current: _StatusEntry) -> int:
322
+ """字段之间的分隔:模型与进度条之间只留一个空格,其余用 `` · ``。"""
323
+ if previous.key == "model" and current.key == "context-used":
324
+ return 1
325
+ return 3
326
+
327
+
328
+ def _entries_width(entries: list[_StatusEntry]) -> int:
329
+ """整行宽度:字段宽度之和加上字段之间的分隔符。"""
330
+ if not entries:
331
+ return 0
332
+ width = sum(entry.width for entry in entries)
333
+ width += sum(_separator_width(previous, current) for previous, current in pairwise(entries))
334
+ return width
335
+
336
+
337
+ class _StatusLine:
338
+ """状态栏的一行。
339
+
340
+ 用 ``Segment`` 直接输出而不套 ``Table``:表格在窄终端会重新分配列宽并折行,
341
+ 状态栏必须严格占一行。
342
+ """
343
+
344
+ def __init__(
345
+ self,
346
+ theme: Theme,
347
+ *,
348
+ bar_width: int,
349
+ percent: float,
350
+ entries: tuple[_StatusEntry, ...],
351
+ ) -> None:
352
+ self.theme = theme
353
+ self.bar_width = bar_width
354
+ self.percent = percent
355
+ self.entries = entries
356
+
357
+ def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
358
+ del options
359
+ theme = self.theme
360
+ for index, entry in enumerate(self.entries):
361
+ if index:
362
+ separator = " " if _separator_width(self.entries[index - 1], entry) == 1 else " · "
363
+ yield Segment(separator, RichStyle(color=theme.color("muted")))
364
+ if entry.key == "context-used" and self.bar_width:
365
+ bar = ProgressBar(
366
+ total=100,
367
+ completed=self.percent,
368
+ width=self.bar_width,
369
+ style=theme.color("border"),
370
+ complete_style=theme.color("accent"),
371
+ finished_style=theme.color("accent"),
372
+ )
373
+ for line in console.render_lines(
374
+ bar,
375
+ console.options.update(width=self.bar_width, height=1),
376
+ pad=False,
377
+ ):
378
+ yield from line
379
+ yield Segment(" ", RichStyle())
380
+ yield Segment(entry.text, RichStyle(color=entry.style, bold=entry.bold))
381
+
382
+
383
+ def _status_renderable(view: StatusView, width: int, theme: Theme) -> RenderableType:
384
+ """单行状态栏:按字段清单拼接,宽度不足时从后往前丢弃字段。"""
385
+ fg = theme.color("fg")
386
+ muted = theme.color("muted")
387
+ values = StatusLineValues(
388
+ model=view.model,
389
+ context_percent=view.context_percent,
390
+ cost=view.cost,
391
+ tool_count=view.tool_count,
392
+ permission=view.permission,
393
+ plan=view.plan,
394
+ background=view.background,
395
+ used_tokens=view.used_tokens,
396
+ context_remaining=view.context_remaining,
397
+ context_window=view.context_window,
398
+ cache_hit=view.cache_hit,
399
+ )
400
+ limit = max(width - 1, 0)
401
+ percent = max(0.0, min(100.0, view.context_percent))
402
+ percent_text = f"{percent:.1f}%"
403
+ bar_width = 8 if width >= 72 else 0
404
+ styles = {
405
+ "cost": muted,
406
+ "tools": muted,
407
+ "permission": muted,
408
+ "plan": theme.color("ok"),
409
+ "background": theme.color("warn"),
410
+ "used-tokens": muted,
411
+ "context-remaining": muted,
412
+ "context-window": muted,
413
+ "cache-hit": muted,
414
+ }
415
+ entries: list[_StatusEntry] = []
416
+ for key in view.fields:
417
+ match key:
418
+ case "model":
419
+ if not view.model:
420
+ continue
421
+ entries.append(
422
+ _StatusEntry(
423
+ key=key,
424
+ text=view.model,
425
+ style=fg,
426
+ bold=True,
427
+ width=wcswidth(view.model),
428
+ )
429
+ )
430
+ case "context-used":
431
+ extra = bar_width + 1 if bar_width else 0
432
+ entries.append(
433
+ _StatusEntry(
434
+ key=key,
435
+ text=percent_text,
436
+ style=theme.color("accent"),
437
+ width=wcswidth(percent_text) + extra,
438
+ )
439
+ )
440
+ case _:
441
+ text = render_status_line(values, (key,))
442
+ if not text:
443
+ continue
444
+ entries.append(
445
+ _StatusEntry(
446
+ key=key,
447
+ text=text,
448
+ style=styles.get(key, muted),
449
+ width=wcswidth(text),
450
+ )
451
+ )
452
+ if not entries:
453
+ return Text("")
454
+ if width < 24:
455
+ first = entries[0]
456
+ style = f"bold {fg}" if first.bold else first.style
457
+ return Text(_fit(first.text, width), style=style)
458
+ while _entries_width(entries) > limit:
459
+ model_index = next(
460
+ (index for index, entry in enumerate(entries) if entry.key == "model"), None
461
+ )
462
+ if len(entries) > 1 and entries[-1].key not in ("model", "context-used"):
463
+ entries.pop()
464
+ continue
465
+ if model_index is not None and entries[model_index].width > 0:
466
+ # 其他字段已经放不下时再压缩模型名,避免一上来就丢掉模型。
467
+ entry = entries[model_index]
468
+ overflow = _entries_width(entries) - limit
469
+ new_width = max(0, entry.width - overflow)
470
+ if new_width == 0:
471
+ entries.pop(model_index)
472
+ continue
473
+ fitted = _fit(entry.text, new_width)
474
+ entries[model_index] = _StatusEntry(
475
+ key=entry.key,
476
+ text=fitted,
477
+ style=entry.style,
478
+ bold=entry.bold,
479
+ width=wcswidth(fitted),
480
+ )
481
+ continue
482
+ if len(entries) > 1:
483
+ entries.pop()
484
+ continue
485
+ entry = entries[0]
486
+ fitted = _fit(entry.text, limit)
487
+ entries[0] = _StatusEntry(
488
+ key=entry.key,
489
+ text=fitted,
490
+ style=entry.style,
491
+ bold=entry.bold,
492
+ width=wcswidth(fitted),
493
+ )
494
+ break
495
+ active_bar = 8 if width >= 72 and any(entry.key == "context-used" for entry in entries) else 0
496
+ return _StatusLine(theme, bar_width=active_bar, percent=percent, entries=tuple(entries))
497
+
498
+
499
+ def _block_renderable(block: RenderBlock, theme: Theme, width: int) -> RenderableType | None:
500
+ fg = theme.color("fg")
501
+ muted = theme.color("muted")
502
+ accent = theme.color("accent")
503
+ border = theme.color("border")
504
+ match block.kind:
505
+ case "banner":
506
+ body = Text()
507
+ for index, line in enumerate(block.lines):
508
+ if index:
509
+ body.append("\n")
510
+ body.append(line, style=f"bold {fg}" if index == 0 else muted)
511
+ return Panel(
512
+ body,
513
+ title=" braid ",
514
+ title_align="left",
515
+ border_style=border,
516
+ padding=(0, 1),
517
+ )
518
+ case "user":
519
+ return _prefix(block.text, "❯ ", theme.color("user"), theme.color("user"))
520
+ case "thinking":
521
+ lines = block.text.splitlines() or [""]
522
+ expanded = block.state == "expanded"
523
+ shown = lines if expanded else lines[-THINKING_PREVIEW_LINES:]
524
+ body = Text()
525
+ for index, line in enumerate(shown):
526
+ if index:
527
+ body.append("\n")
528
+ body.append(line, style=f"italic {muted}")
529
+ if expanded or len(lines) > THINKING_PREVIEW_LINES:
530
+ body.append("\n")
531
+ hint = "Ctrl+T 收起" if expanded else f"Ctrl+T 展开全文({len(lines)} 行)"
532
+ body.append(hint, style=muted)
533
+ return Panel(
534
+ body,
535
+ title=" ✻ 思考 ",
536
+ title_align="left",
537
+ border_style=border,
538
+ padding=(0, 1),
539
+ )
540
+ case "tool":
541
+ # 调用行始终用 ● 标记;运行中的 spinner 与错误颜色表达状态,
542
+ # 不换掉标记字符,避免同一行在生命周期里跳动。
543
+ style = theme.color("err") if block.state == "error" else accent
544
+ marker = "⠋" if block.state == "running" else "●"
545
+ text = _prefix(block.label or block.text, f"{marker} ", style, style)
546
+ if block.duration_ms is not None:
547
+ text.append(f" · {block.duration_ms}ms", style=muted)
548
+ if block.detail:
549
+ text.append("\n ", style=muted)
550
+ text.append(block.detail, style=muted)
551
+ return text
552
+ case "result":
553
+ style = theme.color("err") if block.level == "err" else muted
554
+ return _prefix(block.text, " ⎿ ", style, style)
555
+ case "answer":
556
+ if block.state == "streaming":
557
+ return Text(block.text, style=fg)
558
+ if not block.text.strip():
559
+ return None
560
+ return _left_markdown(block.text)
561
+ case "notice":
562
+ style = _notice_style(block.level, theme)
563
+ return _prefix(block.text, "· ", style, style)
564
+ case "plain":
565
+ return Text(block.text, style=fg)
566
+ case "diff":
567
+ header = Text()
568
+ header.append("⎿ ", style=muted)
569
+ header.append(block.detail or "本次会话的文件改动", style=muted)
570
+ code = Syntax(
571
+ block.text,
572
+ "diff",
573
+ theme=DIFF_THEME,
574
+ line_numbers=False,
575
+ word_wrap=True,
576
+ padding=0,
577
+ indent_guides=False,
578
+ )
579
+ return Group(header, code)
580
+ case "plan":
581
+ return _plan_renderable(block, width, theme)
582
+ case "status":
583
+ view = block.view
584
+ if view is None:
585
+ return Text(block.text, style=muted)
586
+ return _status_renderable(view, width, theme)
587
+ case "activity":
588
+ body = Text()
589
+ body.append(block.state or "⠋", style=f"bold {accent}")
590
+ body.append(" ")
591
+ body.append(block.label, style=fg)
592
+ if block.text:
593
+ body.append(f" · {block.text}", style=muted)
594
+ if block.detail:
595
+ body.append(f" · {block.detail}", style=muted)
596
+ return body
597
+ case "completion" | "rewind":
598
+ body = Text()
599
+ body.append(block.label, style=f"bold {accent}")
600
+ body.append(f" {block.detail}", style=muted)
601
+ for index, line in enumerate(block.lines):
602
+ body.append("\n")
603
+ selected = index == block.selected
604
+ body.append("▸ " if selected else " ", style=accent)
605
+ body.append(line, style=f"bold {fg}" if selected else fg)
606
+ return body
607
+ case "select":
608
+ body = Text()
609
+ body.append(block.label, style=f"bold {accent}")
610
+ body.append(f" {block.detail}", style=muted)
611
+ for index, option in enumerate(block.lines):
612
+ body.append("\n")
613
+ selected = index == block.selected
614
+ body.append("▸ " if selected else " ", style=accent)
615
+ body.append("● " if option == block.current else "○ ", style=theme.color("ok"))
616
+ body.append(option, style=f"bold {fg}" if selected else fg)
617
+ return body
618
+ case "prompt":
619
+ body = Text()
620
+ for index, line in enumerate(block.lines):
621
+ if index:
622
+ body.append("\n")
623
+ body.append(line, style=fg)
624
+ for index, option in enumerate(block.options):
625
+ body.append("\n")
626
+ if index == 0 and block.lines:
627
+ body.append("\n")
628
+ selected = index == block.selected
629
+ checked = index in block.checked
630
+ body.append("▸ " if selected else " ", style=accent)
631
+ if block.multiple:
632
+ body.append(
633
+ "[x] " if checked else "[ ] ",
634
+ style=theme.color("ok") if checked else muted,
635
+ )
636
+ body.append(option, style=f"bold {fg}" if selected else fg)
637
+ if block.detail:
638
+ body.append("\n\n")
639
+ body.append(block.detail, style=muted)
640
+ return Panel(
641
+ body,
642
+ title=f" {block.label} ",
643
+ title_align="left",
644
+ border_style=accent,
645
+ padding=(0, 1),
646
+ )
647
+ case "mcp":
648
+ body = Text()
649
+ if block.text:
650
+ body.append(block.text, style=theme.color("ok"))
651
+ body.append("\n")
652
+ for index, line in enumerate(block.lines):
653
+ if index:
654
+ body.append("\n")
655
+ selected = index == block.selected
656
+ body.append("▸ " if selected else " ", style=accent)
657
+ body.append(line, style=f"bold {fg}" if selected else fg)
658
+ if block.detail:
659
+ body.append("\n\n")
660
+ body.append(block.detail, style=muted)
661
+ return Panel(
662
+ body,
663
+ title=f" {block.label} ",
664
+ title_align="left",
665
+ border_style=accent,
666
+ padding=(0, 1),
667
+ )
668
+ return None
669
+
670
+
671
+ @lru_cache(maxsize=2048)
672
+ def _block_lines(
673
+ block: RenderBlock, width: int, theme_name: str, color: bool
674
+ ) -> tuple[tuple[Fragment, ...], ...]:
675
+ """单个块的渲染结果。块的字段全部可哈希,因此可以直接做缓存键。"""
676
+ theme = THEMES[theme_name]
677
+ renderable = _block_renderable(block, theme, width)
678
+ if renderable is None:
679
+ return ()
680
+ lines = _trim(_render(_console(width, theme_name), renderable, width))
681
+ if not color:
682
+ lines = [[("", text) for _, text in line] for line in lines]
683
+ return tuple(tuple(line) for line in lines)
684
+
685
+
686
+ def render_blocks(
687
+ blocks: tuple[RenderBlock, ...], *, width: int, theme: Theme, color: bool
688
+ ) -> list[FragmentLine]:
689
+ """按顺序渲染内容块,块之间插入一个空行。"""
690
+ lines: list[FragmentLine] = []
691
+ for block in blocks:
692
+ chunk = _block_lines(block, max(1, width), theme.name, color)
693
+ if not chunk:
694
+ continue
695
+ if lines:
696
+ lines.append([])
697
+ lines.extend([list(line) for line in chunk])
698
+ return lines or [[]]
699
+
700
+
701
+ def render_snapshot(
702
+ snapshot: TuiSnapshot, state: TuiRenderState, *, width: int, theme: Theme
703
+ ) -> list[FragmentLine]:
704
+ """把一份完整快照渲染成行:会话记录、计划、状态栏、浮层。
705
+
706
+ 这是 golden 断言与调试快照的唯一入口,四个区之间用空行分隔。
707
+ """
708
+ blocks = list(transcript_blocks(snapshot, banner=state.banner))
709
+ if snapshot.streaming_answer and blocks and blocks[-1].kind == "answer":
710
+ blocks[-1] = RenderBlock(kind="answer", text=blocks[-1].text, state="streaming")
711
+ plan = plan_block(snapshot)
712
+ if plan is not None:
713
+ blocks.append(plan)
714
+ blocks.append(status_block(snapshot))
715
+ blocks.extend(overlay_blocks(state))
716
+ return render_blocks(tuple(blocks), width=width, theme=theme, color=state.color)
717
+
718
+
719
+ def overlay_line_count(state: TuiRenderState, *, width: int, theme: Theme) -> int:
720
+ """浮层的实际行数。布局高度用它,避免截断或留白。"""
721
+ blocks = overlay_blocks(state)
722
+ if not blocks:
723
+ return 0
724
+ return len(render_blocks(blocks, width=max(1, width), theme=theme, color=state.color))
725
+
726
+
727
+ def completion_fragments(state: TuiRenderState, theme: Theme = LIGHT_THEME) -> list[Fragment]:
728
+ """浮层的纯文本片段,供不需要布局的断言与调试出口使用。"""
729
+ lines = render_blocks(overlay_blocks(state), width=80, theme=theme, color=state.color)
730
+ fragments: list[Fragment] = []
731
+ for index, line in enumerate(lines):
732
+ if index:
733
+ fragments.append(("", "\n"))
734
+ fragments.extend(line)
735
+ return fragments
736
+
737
+
738
+ def to_formatted_text(
739
+ snapshot: TuiSnapshot,
740
+ state: TuiRenderState,
741
+ *,
742
+ width: int = 80,
743
+ theme: Theme = LIGHT_THEME,
744
+ ) -> FormattedText:
745
+ lines = render_snapshot(snapshot, state, width=width, theme=theme)
746
+ fragments: list[Fragment] = []
747
+ for index, line in enumerate(lines):
748
+ if index:
749
+ fragments.append(("", "\n"))
750
+ fragments.extend(line)
751
+ return FormattedText(fragments)