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,2226 @@
1
+ """全屏 TUI:prompt_toolkit 负责交互与布局,Rich 负责内容渲染。
2
+
3
+ 这一层只做装配:订阅会话事件、把快照交给渲染层、绑定按键、把用户输入转成
4
+ 会话动作。Agent 循环、工具执行与会话存储都在 ``AgentSession`` 里,界面通过
5
+ 公开方法(``prompt`` / ``abort`` / ``set_model`` / ``checkpoints``)使用它们。
6
+
7
+ 内容区是四个 :class:`RichControl`:会话记录、计划、状态栏与浮层。它们只在
8
+ 内容真正变化时重新渲染(缓存键含快照版本号),按键与光标移动不会触发 Rich
9
+ 重绘。agent 回合作后台任务运行,事件循环始终可读键,因此 Ctrl+C、Esc、
10
+ Ctrl+D 与窗口变化在生成过程中一样即时生效。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import os
17
+ import re
18
+ import time
19
+ from collections.abc import Callable, Hashable, Iterator
20
+ from contextlib import suppress
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING, Any
24
+
25
+ from prompt_toolkit.application import Application, get_app
26
+ from prompt_toolkit.buffer import Buffer
27
+ from prompt_toolkit.completion import CompleteEvent, Completer, Completion
28
+ from prompt_toolkit.document import Document
29
+ from prompt_toolkit.filters import Condition
30
+ from prompt_toolkit.input import Input as PtInput
31
+ from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent
32
+ from prompt_toolkit.layout import Layout
33
+ from prompt_toolkit.layout.containers import (
34
+ ConditionalContainer,
35
+ Float,
36
+ FloatContainer,
37
+ HSplit,
38
+ VSplit,
39
+ Window,
40
+ )
41
+ from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
42
+ from prompt_toolkit.layout.dimension import Dimension
43
+ from prompt_toolkit.output import Output as PtOutput
44
+ from prompt_toolkit.widgets import Frame
45
+
46
+ from braid_ai.cancel import CancelToken
47
+ from braid_ai.utils.clock import Clock, SystemClock
48
+ from braid_coding_agent import __version__
49
+ from braid_coding_agent.checkpoint.git import GitError
50
+ from braid_coding_agent.checkpoint.store import CheckpointError
51
+ from braid_coding_agent.permissions.command import (
52
+ PermissionCommandError,
53
+ execute_permission_command,
54
+ parse_permission_command,
55
+ )
56
+ from braid_coding_agent.permissions.engine import ApprovalAnswer, PermissionPrompt
57
+ from braid_coding_agent.questions import (
58
+ QuestionAnswer,
59
+ QuestionOption,
60
+ QuestionRequest,
61
+ )
62
+ from braid_coding_agent.render.batch import RenderBatcher
63
+ from braid_coding_agent.render.theme import LIGHT_THEME, Theme
64
+ from braid_coding_agent.session.agent_session import AgentSession
65
+ from braid_coding_agent.session.context_breakdown import ContextBreakdown
66
+ from braid_coding_agent.session.discovery import SessionSummary, list_sessions
67
+ from braid_coding_agent.session.lock import SessionLockedError
68
+ from braid_coding_agent.session.manager import SessionManager
69
+ from braid_coding_agent.session.plan_mode import (
70
+ PLAN_APPROVAL_APPROVE,
71
+ PLAN_APPROVAL_EXIT,
72
+ PLAN_APPROVAL_REVISE,
73
+ plan_command_intent,
74
+ )
75
+ from braid_coding_agent.session.rewind import (
76
+ RewindError,
77
+ RewindMode,
78
+ RewindTarget,
79
+ apply_rewind,
80
+ build_targets,
81
+ change_breakdown,
82
+ file_preview,
83
+ parse_mode_flags,
84
+ )
85
+ from braid_coding_agent.statusline import (
86
+ DEFAULT_STATUS_FIELDS,
87
+ STATUS_FIELDS,
88
+ parse_status_fields,
89
+ )
90
+ from braid_coding_agent.subagents.definitions import (
91
+ agent_template,
92
+ is_valid_agent_name,
93
+ )
94
+ from braid_coding_agent.subagents.registry import SubagentTask
95
+ from braid_coding_agent.subagents.runtime import SubagentRuntime
96
+
97
+ from .lifecycle import TerminationHandler, shutdown_session
98
+ from .repl_commands import CommandSpec
99
+ from .skill_commands import conflicting_skill_names, skill_completions, skill_specs
100
+ from .tui_control import RichControl
101
+ from .tui_model import (
102
+ TUI_COMMAND_NAMES,
103
+ CompletionItem,
104
+ TuiCommand,
105
+ TuiKeyMap,
106
+ TuiModel,
107
+ command_completions,
108
+ parse_tui_command,
109
+ )
110
+ from .tui_render import (
111
+ ActivityView,
112
+ PromptView,
113
+ RenderBlock,
114
+ TuiRenderState,
115
+ activity_block,
116
+ overlay_blocks,
117
+ plan_block,
118
+ status_block,
119
+ transcript_blocks,
120
+ )
121
+ from .tui_rich import FragmentLine, overlay_line_count, render_blocks
122
+ from .tui_style import build_style
123
+
124
+ if TYPE_CHECKING:
125
+ from braid_coding_agent.mcp import McpRuntime
126
+ from braid_coding_agent.mcp.tui_panel import McpPanel, McpPanelAction, McpPanelView
127
+ from braid_coding_agent.startup.monitor import StartupMonitor
128
+ from braid_coding_agent.startup.scheduler import BackgroundScheduler
129
+
130
+ __all__ = ["CompletionView", "Tui", "TuiOptions"]
131
+
132
+ #: 审批各档的中文标签。``project`` 只在引擎允许写入项目规则时出现。
133
+ _APPROVAL_LABELS: dict[str, str] = {
134
+ "once": "允许一次",
135
+ "session": "本会话内允许",
136
+ "project": "写入项目规则并允许",
137
+ "deny": "拒绝",
138
+ }
139
+
140
+ #: 执行中标识的 spinner 帧。与 Codex CLI、opencode 用的是同一组盲文点阵。
141
+ SPINNER_FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
142
+ #: spinner 与耗时的推进节拍。10 帧每秒既够顺滑,也不会让终端持续重绘。
143
+ ACTIVITY_TICK_SECONDS = 0.1
144
+
145
+ #: ``/sessions`` 浮层最多列几份会话。选择框放不下更多,更早的用行式 REPL 的路径形式。
146
+ _SESSION_LIST_LIMIT = 8
147
+ #: ``/rewind`` 清单一次显示几轮。窗口跟着选中项滚动,序号仍是完整清单里的序号。
148
+ _REWIND_LIST_LIMIT = 8
149
+
150
+ _HELP_MARKDOWN = r"""\
151
+ | 命令 | 说明 |
152
+ |---|---|
153
+ | `/help` | 列出命令与按键 |
154
+ | `/models` | 打开模型选择框(↑↓ 选择,Enter 确认) |
155
+ | `/model <provider/id>` | 直接切换模型 |
156
+ | `/resume [序号]` | 选择要恢复的会话;切换后显示那份会话的记录 |
157
+ | `/sessions` | `/resume` 的别名 |
158
+ | `/rewind` | 从历史提问里选一轮回退过去(可连同文件) |
159
+ | `/diff` | 本次会话的文件改动(带语法高亮) |
160
+ | `/plan [目标]` | 进入规划模式;`/plan show` 看计划,`/plan approve` 批准,`/plan off` 退出 |
161
+ | `/status` | 模型、上下文、费用与权限 |
162
+ | `/context` | 上下文明细:系统提示词、工具、MCP、技能、子代理、对话与压缩摘要 |
163
+ | `/mcp` | 打开 MCP 管理面板;`/mcp <子命令>` 直接查看服务器、工具、Schema 与调用历史 |
164
+ | `/statusline [字段,...\|reset]` | 查看或修改底部状态栏字段;不带参数列出全部可选字段 |
165
+ | `/permission [子命令]` | 查看或管理权限模式、规则与项目信任 |
166
+ | `/agents [list\|reload\|create\|show\|switch]` | 查看、创建、重载子代理定义,或切换到子会话 |
167
+ | `/tasks [list\|show\|cancel\|send\|clear]` | 查看与管理子代理任务 |
168
+ | `/background <任务描述>` | 把当前会话分离成后台 Agent,继续完成一项独立任务 |
169
+ | `/skills [关键词]` | 列出可用技能、来源与调用方式 |
170
+ | `/skill <名字>` | 只加载技能正文,不立即执行 |
171
+ | `/<技能名> [参数]` | 直接调用技能:正文进上下文并立刻开始一轮 |
172
+ | `/monitor [specs\|tasks]` | 查看启动检查点、派生指标与后台任务 |
173
+ | `/clear` | 开始一个新会话 |
174
+ | `/quit` | 退出 |
175
+
176
+ 按键:`Enter` 提交 · `↑↓` 滚动记录(有浮层时选择) · `PageUp/PageDown` 翻页 ·
177
+ `Tab` 接受补全 / 多选 · `Esc` 关闭浮层或拒绝审批 · `Ctrl+E` 展开最近一次工具 ·
178
+ `Ctrl+C` 中断当前回合 · `Ctrl+D` 退出。
179
+ """
180
+
181
+
182
+ @dataclass(slots=True, frozen=True)
183
+ class CompletionView:
184
+ """当前补全弹窗的只读投影。"""
185
+
186
+ items: tuple[CompletionItem, ...] = ()
187
+ selected: int = 0
188
+
189
+ @property
190
+ def active(self) -> bool:
191
+ return bool(self.items)
192
+
193
+ @property
194
+ def current(self) -> CompletionItem | None:
195
+ if not self.items:
196
+ return None
197
+ return self.items[min(self.selected, len(self.items) - 1)]
198
+
199
+
200
+ class TuiOptions:
201
+ """全屏 TUI 的显示与交互选项。"""
202
+
203
+ def __init__(
204
+ self,
205
+ *,
206
+ theme: Theme = LIGHT_THEME,
207
+ color: bool = True,
208
+ keymap: TuiKeyMap | None = None,
209
+ activity_height: int = 6,
210
+ banner: bool = True,
211
+ ) -> None:
212
+ self.theme = theme
213
+ self.color = color
214
+ self.keymap = keymap or TuiKeyMap()
215
+ self.activity_height = max(3, activity_height)
216
+ self.banner = banner
217
+
218
+
219
+ class _CommandCompleter(Completer):
220
+ """把 tui_model 的候选接到 prompt_toolkit 的 Buffer。"""
221
+
222
+ def __init__(self, source: Callable[[str], tuple[CompletionItem, ...]]) -> None:
223
+ self._source = source
224
+
225
+ def get_completions(
226
+ self, document: Document, complete_event: CompleteEvent
227
+ ) -> Iterator[Completion]:
228
+ del complete_event
229
+ for item in self._source(document.text):
230
+ yield Completion(
231
+ item.insert,
232
+ start_position=-len(document.text),
233
+ display=item.usage,
234
+ display_meta=item.summary,
235
+ )
236
+
237
+
238
+ @dataclass(slots=True)
239
+ class _ApprovalPending:
240
+ """等待用户裁决的一次权限请求。"""
241
+
242
+ prompt: PermissionPrompt
243
+ future: asyncio.Future[ApprovalAnswer]
244
+ selected: int = 0
245
+
246
+ @property
247
+ def options(self) -> tuple[str, ...]:
248
+ return self.prompt.options
249
+
250
+ def answer(self, scope: str) -> ApprovalAnswer:
251
+ if scope == "deny":
252
+ return ApprovalAnswer(scope="deny", note="用户在终端拒绝")
253
+ return ApprovalAnswer(scope=scope) # pyright: ignore[reportArgumentType]
254
+
255
+ def resolve(self, scope: str) -> None:
256
+ if not self.future.done():
257
+ self.future.set_result(self.answer(scope))
258
+
259
+
260
+ @dataclass(slots=True)
261
+ class _QuestionPending:
262
+ """等待用户回答的一次提问。"""
263
+
264
+ request: QuestionRequest
265
+ future: asyncio.Future[QuestionAnswer]
266
+ selected: int = 0
267
+ checked: set[int] = field(default_factory=set[int])
268
+
269
+ @property
270
+ def labels(self) -> tuple[str, ...]:
271
+ return tuple(option.label for option in self.request.options)
272
+
273
+ def toggle(self) -> None:
274
+ if not self.request.multiple:
275
+ return
276
+ if self.selected in self.checked:
277
+ self.checked.discard(self.selected)
278
+ else:
279
+ self.checked.add(self.selected)
280
+
281
+ def resolve(self, answer: QuestionAnswer) -> None:
282
+ if not self.future.done():
283
+ self.future.set_result(answer)
284
+
285
+
286
+ class Tui:
287
+ """一次全屏交互会话的 Application 装配器与生命周期驱动。
288
+
289
+ :param session: 初始会话,只通过公开动作使用。
290
+ :param build_session: 换会话(``/clear``、``/sessions`` 选一份旧会话)时的装配回调。
291
+ 与行式 REPL 同一个契约:给一个新的 ``SessionManager``,还一个新的 ``AgentSession``。
292
+ :param models: 模型目录,``/models`` 用它列清单。
293
+ :param keys: 可选的输入源(无头测试注入 ``create_pipe_input``)。
294
+ :param output: 可选的输出源(无头测试注入 ``DummyOutput``)。
295
+ :param options: 主题、颜色与快捷键。
296
+ """
297
+
298
+ def __init__(
299
+ self,
300
+ *,
301
+ session: AgentSession,
302
+ build_session: Callable[[SessionManager], AgentSession] | None = None,
303
+ models: Any,
304
+ keys: PtInput | None = None,
305
+ output: PtOutput | None = None,
306
+ options: TuiOptions | None = None,
307
+ clock: Any = None,
308
+ mcp: McpRuntime | None = None,
309
+ subagents: SubagentRuntime | None = None,
310
+ monitor: StartupMonitor | None = None,
311
+ scheduler: BackgroundScheduler | None = None,
312
+ on_ready: Callable[[], None] | None = None,
313
+ statusline_fields: tuple[str, ...] = DEFAULT_STATUS_FIELDS,
314
+ ) -> None:
315
+ self._session = session
316
+ self._build_session = build_session
317
+ self._models = models
318
+ self._mcp = mcp
319
+ self._mcp_panel: McpPanel | None = None
320
+ self._subagents = subagents
321
+ self._monitor = monitor
322
+ self._scheduler = scheduler
323
+ self._on_ready = on_ready
324
+ self._render_started = False
325
+ self._first_turn_marked = False
326
+ self._batch = RenderBatcher(self._flush_invalidate)
327
+ self._unsubscribe_scheduler: Callable[[], None] = (
328
+ scheduler.subscribe(lambda task: self._batch.request())
329
+ if scheduler is not None
330
+ else lambda: None
331
+ )
332
+ self._keys = keys
333
+ self._output = output
334
+ self._options = options if options is not None else TuiOptions()
335
+ self._clock: Clock = clock if clock is not None else SystemClock()
336
+ #: 最近一次 ``/sessions`` 列出的会话。序号只在这一次清单里有效。
337
+ self._session_choices: list[SessionSummary] = []
338
+ #: 当前会话文件的绝对路径,用于在清单里标出"哪一份是现在这份"。
339
+ self._session_current_path: str | None = None
340
+ #: 回退选择框里的位置与它的显示文本,序号与 ``/rewind <序号>`` 一致。
341
+ #: 显示文本随清单一次算好:每帧重建会和流式输出抢同一段时间。
342
+ self._rewind_menu: tuple[tuple[RewindTarget, str], ...] = ()
343
+ #: 已报过同名冲突的技能名。冲突只提示一次,避免每次敲命令都刷屏。
344
+ self._reported_skill_conflicts: set[str] = set()
345
+
346
+ self._model = TuiModel(
347
+ model=session.model,
348
+ theme=self._options.theme,
349
+ color=self._options.color,
350
+ permission_mode=self._permission_mode(),
351
+ statusline_fields=statusline_fields,
352
+ )
353
+ # 带着旧会话启动时(``-c`` / ``--session``),记录区一建立就是上一轮的末尾。
354
+ self._model.replay(session.agent.state.messages)
355
+ self._termination = TerminationHandler()
356
+ self._unsubscribe: Callable[[], None] | None = None
357
+ self._turn_task: asyncio.Task[None] | None = None
358
+ self._watch_task: asyncio.Task[None] | None = None
359
+ self._turn_started_at: float | None = None
360
+ self._spinner_index = 0
361
+ self._exit_code = 0
362
+ self._overlay: str | None = None
363
+ self._selected_model_index = 0
364
+ self._completion: tuple[CompletionItem, ...] = ()
365
+ self._completion_selected = 0
366
+ #: 记录区的滚动位置;``None`` 表示跟随末尾。``before_render`` 每帧把它
367
+ #: 写进窗口与内容控件的光标行,避免 prompt_toolkit 把位置拉回顶部。
368
+ self._scroll_top: int | None = None
369
+ self._faux = getattr(session.agent, "_faux", None)
370
+ self._approval: _ApprovalPending | None = None
371
+ self._question: _QuestionPending | None = None
372
+ self._banner = self._banner_lines() if self._options.banner else ()
373
+ # 上下文统计要遍历整棵会话树;流式增量每片都算会把事件循环拖住。
374
+ self._status_at = 0.0
375
+ #: 已经问过审批的那一版计划(版本号 + 提交时间)。换会话时重置。
376
+ state = session.plan_mode.state if session.plan_mode is not None else None
377
+ self._plan_prompted: tuple[int, str | None] | None = (
378
+ (state.revision, state.updated_at) if state is not None and state.has_plan else None
379
+ )
380
+
381
+ self._buffer = Buffer(
382
+ completer=_CommandCompleter(self._completions_for),
383
+ complete_while_typing=False,
384
+ multiline=False,
385
+ on_text_changed=self._on_input_changed,
386
+ )
387
+ self._buffer.accept_handler = self._on_buffer_accept
388
+ self._history_window: Window | None = None
389
+ self._history_control: RichControl | None = None
390
+ self._overlay_window: Window | None = None
391
+ self._input_window: Window | None = None
392
+ self._activity_control: RichControl | None = None
393
+ self._app: Application[int] | None = None
394
+
395
+ # ------------------------------------------------------------ 只读状态
396
+
397
+ def _permission_mode(self) -> str:
398
+ engine = self._session.permission_engine
399
+ if engine is None:
400
+ return "off"
401
+ return str(getattr(engine.settings, "mode", "off"))
402
+
403
+ def _banner_lines(self) -> tuple[str, ...]:
404
+ model = f"{self._session.model.provider}/{self._session.model.id}"
405
+ cwd = self._session.session.get_cwd()
406
+ return (
407
+ f"braid {__version__} · {model}",
408
+ cwd,
409
+ "/help 查看命令 · Ctrl+C 中断 · Ctrl+D 退出",
410
+ )
411
+
412
+ @property
413
+ def session(self) -> AgentSession:
414
+ return self._session
415
+
416
+ @property
417
+ def model(self) -> TuiModel:
418
+ return self._model
419
+
420
+ @property
421
+ def completion(self) -> CompletionView:
422
+ return CompletionView(items=self._completion, selected=self._completion_selected)
423
+
424
+ def notify(self, text: str, role: str = "warn") -> None:
425
+ """把后台诊断写进记录区,刷新交给渲染批处理。"""
426
+ self._model.on_notice(text, role=role)
427
+ self._invalidate()
428
+
429
+ @property
430
+ def application(self) -> Application[int]:
431
+ if self._app is None:
432
+ raise RuntimeError("Application 尚未装配,先调用 build_application()")
433
+ return self._app
434
+
435
+ # ------------------------------------------------------------ 控件树
436
+
437
+ def build_application(self) -> Application[int]:
438
+ """装配完整控件树,返回 Application。重复调用返回同一实例。"""
439
+ if self._app is not None:
440
+ return self._app
441
+ self._history_control = RichControl(self._history_source)
442
+ self._history_window = Window(
443
+ self._history_control,
444
+ wrap_lines=False,
445
+ allow_scroll_beyond_bottom=True,
446
+ height=Dimension(weight=1),
447
+ )
448
+ plan_window = Window(
449
+ RichControl(self._plan_source),
450
+ wrap_lines=False,
451
+ height=Dimension(min=1, max=self._options.activity_height),
452
+ )
453
+ status_window = Window(
454
+ RichControl(self._status_source),
455
+ wrap_lines=False,
456
+ height=1,
457
+ style="class:status",
458
+ )
459
+ # Codex CLI 风格:执行中的标识独占状态栏与输入框之间的一行,空闲时整行收起。
460
+ self._activity_control = RichControl(self._activity_source)
461
+ activity_window = Window(
462
+ self._activity_control,
463
+ wrap_lines=False,
464
+ height=1,
465
+ )
466
+ prompt_window = Window(
467
+ FormattedTextControl([("class:accent", "braid> ")], focusable=False),
468
+ width=7,
469
+ height=Dimension(min=1, max=1),
470
+ )
471
+ input_window = Window(
472
+ BufferControl(buffer=self._buffer),
473
+ height=Dimension(min=1, max=1),
474
+ )
475
+ self._input_window = input_window
476
+ # Claude Code 风格:输入框用可见边框圈起来,提示与内容都在框内。
477
+ input_box = Frame(
478
+ VSplit([prompt_window, input_window]),
479
+ title=" 消息 ",
480
+ height=3,
481
+ )
482
+ overlay_window = Window(
483
+ RichControl(self._overlay_source, focusable=True),
484
+ wrap_lines=False,
485
+ )
486
+ self._overlay_window = overlay_window
487
+ root = FloatContainer(
488
+ content=HSplit(
489
+ [
490
+ self._history_window,
491
+ ConditionalContainer(plan_window, filter=Condition(self._plan_visible)),
492
+ status_window,
493
+ ConditionalContainer(activity_window, filter=Condition(self._activity_visible)),
494
+ input_box,
495
+ ]
496
+ ),
497
+ floats=[
498
+ Float(
499
+ content=ConditionalContainer(
500
+ overlay_window, filter=Condition(self._overlay_active)
501
+ ),
502
+ # 输入框 3 行、状态栏 1 行;浮层画在它们上方,不遮挡焦点控件。
503
+ bottom=4,
504
+ left=1,
505
+ right=1,
506
+ height=self._overlay_height,
507
+ )
508
+ ],
509
+ )
510
+ self._app = Application(
511
+ layout=Layout(root, focused_element=input_window),
512
+ key_bindings=self._build_key_bindings(),
513
+ style=build_style(self._options.theme),
514
+ full_screen=True,
515
+ mouse_support=False,
516
+ erase_when_done=True,
517
+ min_redraw_interval=0.016,
518
+ max_render_postpone_time=0.01,
519
+ terminal_size_polling_interval=0.5,
520
+ before_render=self._before_render,
521
+ after_render=self._after_render,
522
+ input=self._keys,
523
+ output=self._output,
524
+ )
525
+ return self._app
526
+
527
+ # ------------------------------------------------------------ 内容来源
528
+
529
+ def _history_source(self, width: int) -> tuple[Hashable, list[FragmentLine]]:
530
+ snapshot = self._model.snapshot()
531
+ blocks = transcript_blocks(snapshot, banner=self._banner)
532
+ if snapshot.streaming_answer and blocks and blocks[-1].kind == "answer":
533
+ blocks = (
534
+ *blocks[:-1],
535
+ RenderBlock(kind="answer", text=blocks[-1].text, state="streaming"),
536
+ )
537
+ lines = render_blocks(
538
+ blocks, width=width, theme=self._options.theme, color=self._options.color
539
+ )
540
+ return (snapshot.revision, self._banner, width), lines
541
+
542
+ def _plan_source(self, width: int) -> tuple[Hashable, list[FragmentLine]]:
543
+ snapshot = self._model.snapshot()
544
+ block = plan_block(snapshot)
545
+ if block is None:
546
+ return (snapshot.revision, width), [[]]
547
+ lines = render_blocks(
548
+ (block,), width=width, theme=self._options.theme, color=self._options.color
549
+ )
550
+ return (snapshot.revision, width), lines
551
+
552
+ def _status_source(self, width: int) -> tuple[Hashable, list[FragmentLine]]:
553
+ snapshot = self._model.snapshot()
554
+ lines = render_blocks(
555
+ (status_block(snapshot),),
556
+ width=width,
557
+ theme=self._options.theme,
558
+ color=self._options.color,
559
+ )
560
+ return (snapshot.revision, width), lines
561
+
562
+ def _activity_source(self, width: int) -> tuple[Hashable, list[FragmentLine]]:
563
+ view = self._activity_view()
564
+ if view is None:
565
+ return ("idle",), [[]]
566
+ block = activity_block(view)
567
+ lines = render_blocks(
568
+ (block,), width=width, theme=self._options.theme, color=self._options.color
569
+ )
570
+ # 键里带 spinner 帧与秒级耗时:同一条阶段文案也会随节拍重绘。
571
+ return ((block.label, block.state, block.text), width), lines
572
+
573
+ def _activity_visible(self) -> bool:
574
+ return self._turn_task is not None and not self._turn_task.done()
575
+
576
+ def _activity_view(self) -> ActivityView | None:
577
+ if not self._activity_visible() or self._turn_started_at is None:
578
+ return None
579
+ return ActivityView(
580
+ frame=SPINNER_FRAMES[self._spinner_index % len(SPINNER_FRAMES)],
581
+ label=self._activity_label(),
582
+ elapsed_seconds=time.monotonic() - self._turn_started_at,
583
+ )
584
+
585
+ def _activity_label(self) -> str:
586
+ """按当前最具体的事实给出阶段文案,越靠前越能解释"在等什么"。"""
587
+ if self._approval is not None:
588
+ return "等待权限确认"
589
+ if self._question is not None:
590
+ return "等待回答"
591
+ snapshot = self._model.snapshot()
592
+ for card in reversed(snapshot.tool_cards):
593
+ if card.status == "running":
594
+ return f"执行 {card.label.split()[0]}"
595
+ if snapshot.thinking is not None:
596
+ return "思考中"
597
+ if snapshot.streaming_answer:
598
+ return "生成回答"
599
+ return "准备工作区"
600
+
601
+ def _overlay_source(self, width: int) -> tuple[Hashable, list[FragmentLine]]:
602
+ blocks = overlay_blocks(self._render_state())
603
+ lines = render_blocks(
604
+ blocks, width=width, theme=self._options.theme, color=self._options.color
605
+ )
606
+ return (blocks, width), lines
607
+
608
+ def _render_state(self) -> TuiRenderState:
609
+ return TuiRenderState(
610
+ color=self._options.color,
611
+ overlay=self._overlay,
612
+ completion=self._completion,
613
+ completion_selected=self._completion_selected,
614
+ completion_capacity=max(1, self._options.activity_height - 1),
615
+ model_options=tuple(self._model_options()),
616
+ session_options=tuple(self._session_options()),
617
+ rewind_options=tuple(self._rewind_options()),
618
+ rewind_capacity=_REWIND_LIST_LIMIT,
619
+ selection_selected=self._selected_model_index,
620
+ selection_current=(
621
+ f"{self._session.model.provider}/{self._session.model.id}"
622
+ if self._overlay == "models"
623
+ else ""
624
+ ),
625
+ prompt=self._prompt_view(),
626
+ mcp=self._mcp_view(),
627
+ banner=self._banner,
628
+ activity=self._activity_view(),
629
+ )
630
+
631
+ def _prompt_view(self) -> PromptView | None:
632
+ if self._approval is not None:
633
+ pending = self._approval
634
+ request = pending.prompt.request
635
+ target = ", ".join(request.paths) or request.command or request.host or "(无目标)"
636
+ lines = [
637
+ f"工具 {request.tool_name}:{pending.prompt.reason}",
638
+ f"命中规则 {pending.prompt.rule}",
639
+ f"目标 {target}",
640
+ ]
641
+ if pending.prompt.proposal is not None:
642
+ lines.append(f"写入项目规则:{pending.prompt.proposal.describe()} = allow")
643
+ return PromptView(
644
+ kind="approval",
645
+ title="权限请求",
646
+ lines=tuple(lines),
647
+ options=tuple(_APPROVAL_LABELS.get(scope, scope) for scope in pending.options),
648
+ selected=pending.selected,
649
+ hint="↑↓ 选择 · Enter 确认 · y 一次 / s 本会话 / p 项目规则 / n 拒绝 · Esc 拒绝",
650
+ )
651
+ if self._question is not None:
652
+ pending = self._question
653
+ request = pending.request
654
+ lines = [request.question]
655
+ if request.header:
656
+ lines.insert(0, request.header)
657
+ options: list[str] = []
658
+ for option in request.options:
659
+ label = option.label
660
+ if option.description:
661
+ label = f"{label}({option.description})"
662
+ options.append(label)
663
+ hint = (
664
+ "↑↓ 选择 · Tab 多选 · Enter 确认 · 直接输入文字回答 · Esc 取消"
665
+ if request.multiple
666
+ else "↑↓ 选择 · Enter 确认 · 直接输入文字回答 · Esc 取消"
667
+ )
668
+ return PromptView(
669
+ kind="question",
670
+ title="提问",
671
+ lines=tuple(lines),
672
+ options=tuple(options),
673
+ selected=pending.selected,
674
+ checked=tuple(sorted(pending.checked)),
675
+ multiple=request.multiple,
676
+ hint=hint,
677
+ )
678
+ return None
679
+
680
+ def _mcp_view(self) -> McpPanelView | None:
681
+ if self._overlay != "mcp" or self._mcp_panel is None:
682
+ return None
683
+ return self._mcp_panel.view(self._mcp_page_size())
684
+
685
+ def _mcp_page_size(self) -> int:
686
+ """浮层去掉边框、提示与消息行之后可用的正文行数。"""
687
+ _, rows = self._terminal_size()
688
+ return max(4, rows - 11)
689
+
690
+ def _plan_visible(self) -> bool:
691
+ return self._model.snapshot().plan is not None
692
+
693
+ def _overlay_active(self) -> bool:
694
+ return (
695
+ self._overlay is not None
696
+ or bool(self._completion)
697
+ or self._approval is not None
698
+ or self._question is not None
699
+ )
700
+
701
+ def _terminal_size(self) -> tuple[int, int]:
702
+ if self._app is None:
703
+ return (80, 24)
704
+ size = self._app.output.get_size()
705
+ return (size.columns, size.rows)
706
+
707
+ def _overlay_width(self) -> int:
708
+ columns, _ = self._terminal_size()
709
+ return max(8, columns - 2)
710
+
711
+ def _overlay_height(self) -> int:
712
+ """浮层高度取实际渲染行数,封顶在状态栏与输入框之上。"""
713
+ _, rows = self._terminal_size()
714
+ count = overlay_line_count(
715
+ self._render_state(),
716
+ width=self._overlay_width(),
717
+ theme=self._options.theme,
718
+ )
719
+ return max(1, min(count, max(1, rows - 5)))
720
+
721
+ def _before_render(self, app: Application[int]) -> None:
722
+ """每帧把记录区的滚动位置写进窗口与内容控件。
723
+
724
+ 跟随末尾时取当前内容的最后一行;否则用用户指定的位置。内容行数从
725
+ 控件当前帧取,窗口高度沿用上一帧:流式输出在同一帧里增长几十行时,
726
+ 只用上一帧的 ``content_height`` 会让视口停在旧底部。
727
+ """
728
+ window = self._history_window
729
+ control = self._history_control
730
+ if window is None or control is None:
731
+ return
732
+ info = window.render_info
733
+ if info is None:
734
+ app.invalidate()
735
+ return
736
+ content_height = control.line_count(info.window_width)
737
+ max_scroll = max(0, content_height - info.window_height)
738
+ if self._scroll_top is None:
739
+ target = max_scroll
740
+ else:
741
+ target = max(0, min(self._scroll_top, max_scroll))
742
+ if target >= max_scroll:
743
+ self._scroll_top = None
744
+ window.vertical_scroll = target
745
+ control.scroll_hint = target
746
+
747
+ def _scroll_by(self, delta: int) -> None:
748
+ window = self._history_window
749
+ control = self._history_control
750
+ if window is None or control is None:
751
+ return
752
+ info = window.render_info
753
+ if info is None:
754
+ return
755
+ content_height = control.line_count(info.window_width)
756
+ max_scroll = max(0, content_height - info.window_height)
757
+ current = info.vertical_scroll
758
+ target = max(0, min(max_scroll, current + delta))
759
+ self._scroll_top = None if target >= max_scroll else target
760
+ window.vertical_scroll = target
761
+ control.scroll_hint = target
762
+ self._invalidate()
763
+
764
+ def _invalidate(self) -> None:
765
+ self._batch.request()
766
+
767
+ def _flush_invalidate(self) -> None:
768
+ with suppress(RuntimeError):
769
+ get_app().invalidate()
770
+
771
+ def _after_render(self, app: Application[int]) -> None:
772
+ """第一帧画完后启动后台初始化,保证首次界面先出现。"""
773
+ del app
774
+ if self._render_started:
775
+ return
776
+ self._render_started = True
777
+ if self._monitor is not None:
778
+ self._monitor.mark("tui_first_render")
779
+ if self._on_ready is not None:
780
+ self._on_ready()
781
+
782
+ def _on_input_changed(self, buffer: Buffer) -> None:
783
+ """输入变化时刷新补全;审批等待中允许 y/s/n 直达。"""
784
+ if self._approval is not None:
785
+ spec = buffer.text.strip().lower()
786
+ if spec in ("y", "s", "n"):
787
+ buffer.text = ""
788
+ self._resolve_approval(spec)
789
+ return
790
+ items = self._completions_for(buffer.text)
791
+ if items == self._completion:
792
+ return
793
+ self._completion = items
794
+ self._completion_selected = 0
795
+ self._invalidate()
796
+
797
+ # ------------------------------------------------------------ 键绑定
798
+
799
+ def _build_key_bindings(self) -> KeyBindings:
800
+ kb = KeyBindings()
801
+ km = self._options.keymap
802
+
803
+ @kb.add("c-c", eager=True)
804
+ async def cancel(event: KeyPressEvent) -> None:
805
+ if self._approval is not None:
806
+ self._resolve_approval("n")
807
+ return
808
+ if self._question is not None:
809
+ self._cancel_question()
810
+ return
811
+ if self._turn_task is not None and not self._turn_task.done():
812
+ await self._session.abort()
813
+ else:
814
+ event.app.exit(result=0)
815
+
816
+ @kb.add("c-d", eager=True)
817
+ def exit_app(event: KeyPressEvent) -> None:
818
+ event.app.exit(result=0)
819
+
820
+ @kb.add("up", eager=True)
821
+ def scroll_up(event: KeyPressEvent) -> None:
822
+ del event
823
+ if self._move_selection(-1):
824
+ return
825
+ if self._overlay is not None:
826
+ self._overlay_move(-1)
827
+ return
828
+ if self._completion:
829
+ self._complete_move(-1)
830
+ return
831
+ self._scroll_by(-1)
832
+
833
+ @kb.add("down", eager=True)
834
+ def scroll_down(event: KeyPressEvent) -> None:
835
+ del event
836
+ if self._move_selection(1):
837
+ return
838
+ if self._overlay is not None:
839
+ self._overlay_move(1)
840
+ return
841
+ if self._completion:
842
+ self._complete_move(1)
843
+ return
844
+ self._scroll_by(1)
845
+
846
+ # 只在选择浮层打开时接管 Enter;无浮层时不匹配,让 Buffer 的
847
+ # accept_handler 照常提交消息(不能无条件绑定,否则会吞掉提交)。
848
+ @kb.add("enter", filter=Condition(self._overlay_selecting), eager=True)
849
+ def confirm_selection(event: KeyPressEvent) -> None:
850
+ event.app.create_background_task(self._overlay_confirm())
851
+
852
+ @kb.add("tab", eager=True)
853
+ def accept_completion(event: KeyPressEvent) -> None:
854
+ del event
855
+ if self._question is not None:
856
+ if self._question.request.multiple:
857
+ self._question.toggle()
858
+ self._invalidate()
859
+ return
860
+ if self._approval is not None:
861
+ self._resolve_approval("")
862
+ return
863
+ if self._overlay is not None:
864
+ self._overlay_confirm_sync()
865
+ return
866
+ if self._completion:
867
+ self._complete_accept()
868
+
869
+ @kb.add("pageup", eager=True)
870
+ def page_up(event: KeyPressEvent) -> None:
871
+ del event
872
+ if self._mcp_open():
873
+ self._mcp_page(-1)
874
+ return
875
+ self._scroll_by(-10)
876
+
877
+ @kb.add("pagedown", eager=True)
878
+ def page_down(event: KeyPressEvent) -> None:
879
+ del event
880
+ if self._mcp_open():
881
+ self._mcp_page(1)
882
+ return
883
+ self._scroll_by(10)
884
+
885
+ @kb.add("e", filter=Condition(self._mcp_open), eager=True)
886
+ def mcp_toggle(event: KeyPressEvent) -> None:
887
+ del event
888
+ self._mcp_shortcut("e")
889
+
890
+ @kb.add("r", filter=Condition(self._mcp_open), eager=True)
891
+ def mcp_reconnect(event: KeyPressEvent) -> None:
892
+ del event
893
+ self._mcp_shortcut("r")
894
+
895
+ @kb.add("f", filter=Condition(self._mcp_open), eager=True)
896
+ def mcp_refresh(event: KeyPressEvent) -> None:
897
+ del event
898
+ self._mcp_shortcut("f")
899
+
900
+ @kb.add("h", filter=Condition(self._mcp_open), eager=True)
901
+ def mcp_history(event: KeyPressEvent) -> None:
902
+ del event
903
+ self._mcp_shortcut("h")
904
+
905
+ @kb.add("l", filter=Condition(self._mcp_open), eager=True)
906
+ def mcp_load(event: KeyPressEvent) -> None:
907
+ del event
908
+ self._mcp_shortcut("l")
909
+
910
+ @kb.add("L", filter=Condition(self._mcp_open), eager=True)
911
+ def mcp_reload(event: KeyPressEvent) -> None:
912
+ del event
913
+ self._mcp_shortcut("L")
914
+
915
+ @kb.add("c-t", eager=True)
916
+ def toggle_thinking(event: KeyPressEvent) -> None:
917
+ del event
918
+ self._model.toggle_thinking()
919
+ # 展开或收起会改变记录高度;回到跟随末尾,末尾内容立即可见。
920
+ self._scroll_top = None
921
+ self._invalidate()
922
+
923
+ @kb.add(km.expand_tool, eager=True)
924
+ def expand_tool(event: KeyPressEvent) -> None:
925
+ del event
926
+ cards = self._model.snapshot().tool_cards
927
+ if cards:
928
+ self._model.toggle_tool(cards[-1].call_id)
929
+ self._scroll_top = None
930
+ self._invalidate()
931
+
932
+ @kb.add("escape", eager=True)
933
+ def dismiss(event: KeyPressEvent) -> None:
934
+ del event
935
+ if self._approval is not None:
936
+ self._resolve_approval("n")
937
+ return
938
+ if self._question is not None:
939
+ self._cancel_question()
940
+ return
941
+ if self._mcp_open():
942
+ if self._mcp_panel is not None and self._mcp_panel.back():
943
+ self._invalidate()
944
+ return
945
+ self._close_mcp_panel()
946
+ return
947
+ self._overlay = None
948
+ self._selected_model_index = 0
949
+ self._rewind_menu = ()
950
+ self._completion = ()
951
+ self._completion_selected = 0
952
+ self._invalidate()
953
+
954
+ return kb
955
+
956
+ def _move_selection(self, delta: int) -> bool:
957
+ """审批或提问等待中,↑↓ 移动高亮项。返回是否消费了按键。"""
958
+ if self._approval is not None:
959
+ total = len(self._approval.options)
960
+ if total:
961
+ self._approval.selected = (self._approval.selected + delta) % total
962
+ self._invalidate()
963
+ return True
964
+ if self._question is not None:
965
+ total = len(self._question.request.options)
966
+ if total:
967
+ self._question.selected = (self._question.selected + delta) % total
968
+ self._invalidate()
969
+ return True
970
+ return False
971
+
972
+ # ------------------------------------------------------------ 选择浮层
973
+
974
+ def _overlay_selecting(self) -> bool:
975
+ return self._overlay in ("models", "sessions", "rewind", "mcp")
976
+
977
+ def _overlay_options(self) -> tuple[str, ...]:
978
+ if self._overlay == "sessions":
979
+ return tuple(self._session_options())
980
+ if self._overlay == "rewind":
981
+ return tuple(self._rewind_options())
982
+ return tuple(self._model_options())
983
+
984
+ def _overlay_move(self, delta: int) -> None:
985
+ """在选择框内循环移动高亮项。"""
986
+ if self._mcp_open():
987
+ if self._mcp_panel is not None:
988
+ self._mcp_panel.move(delta)
989
+ self._invalidate()
990
+ return
991
+ options = self._overlay_options()
992
+ if not options:
993
+ return
994
+ self._selected_model_index = (self._selected_model_index + delta) % len(options)
995
+ self._invalidate()
996
+
997
+ async def _overlay_confirm(self) -> None:
998
+ """Enter:确认高亮项。模型框切模型,会话框切会话,回退框问范围再回退。"""
999
+ if self._mcp_open():
1000
+ if self._mcp_panel is None:
1001
+ return
1002
+ action = self._mcp_panel.activate()
1003
+ if action is None:
1004
+ self._invalidate()
1005
+ return
1006
+ await self._run_mcp_action(action)
1007
+ return
1008
+ options = self._overlay_options()
1009
+ if self._overlay == "models" and options:
1010
+ index = min(self._selected_model_index, len(options) - 1)
1011
+ await self._switch_model(options[index])
1012
+ elif self._overlay == "sessions" and self._session_choices:
1013
+ index = min(self._selected_model_index, len(self._session_choices) - 1)
1014
+ self._overlay = None
1015
+ self._selected_model_index = 0
1016
+ await self._resume_session(index + 1)
1017
+ return
1018
+ elif self._overlay == "rewind" and self._rewind_menu:
1019
+ index = min(self._selected_model_index, len(self._rewind_menu) - 1)
1020
+ target = self._rewind_menu[index][0]
1021
+ self._overlay = None
1022
+ self._selected_model_index = 0
1023
+ self._rewind_menu = ()
1024
+ self._invalidate()
1025
+ await self._rewind_to(target)
1026
+ return
1027
+ self._overlay = None
1028
+ self._selected_model_index = 0
1029
+ self._invalidate()
1030
+
1031
+ def _overlay_confirm_sync(self) -> None:
1032
+ """Tab:与 Enter 同义的确认。"""
1033
+ if self._overlay in ("models", "sessions", "rewind", "mcp"):
1034
+ self.application.create_background_task(self._overlay_confirm())
1035
+ else:
1036
+ self._overlay = None
1037
+ self._selected_model_index = 0
1038
+ self._invalidate()
1039
+
1040
+ # ------------------------------------------------------------ MCP 面板
1041
+
1042
+ def _mcp_open(self) -> bool:
1043
+ return self._overlay == "mcp" and self._mcp_panel is not None
1044
+
1045
+ def _open_mcp_panel(self) -> None:
1046
+ from braid_coding_agent.mcp.tui_panel import McpPanel
1047
+
1048
+ self._mcp_panel = McpPanel(self._mcp)
1049
+ self._overlay = "mcp"
1050
+ self._selected_model_index = 0
1051
+ self._completion = ()
1052
+ self._completion_selected = 0
1053
+ if self._overlay_window is not None:
1054
+ self.application.layout.focus(self._overlay_window)
1055
+ self._invalidate()
1056
+
1057
+ def _close_mcp_panel(self) -> None:
1058
+ self._mcp_panel = None
1059
+ self._overlay = None
1060
+ if self._input_window is not None:
1061
+ self.application.layout.focus(self._input_window)
1062
+ self._invalidate()
1063
+
1064
+ def _mcp_page(self, direction: int) -> None:
1065
+ if self._mcp_panel is not None:
1066
+ self._mcp_panel.page(direction, self._mcp_page_size())
1067
+ self._invalidate()
1068
+
1069
+ def _mcp_shortcut(self, key: str) -> None:
1070
+ if self._mcp_panel is None:
1071
+ return
1072
+ action = self._mcp_panel.shortcut(key)
1073
+ if action is not None:
1074
+ self.application.create_background_task(self._run_mcp_action(action))
1075
+ self._invalidate()
1076
+
1077
+ async def _run_mcp_action(self, action: McpPanelAction) -> None:
1078
+ panel = self._mcp_panel
1079
+ runtime = self._mcp
1080
+ if panel is None or runtime is None:
1081
+ return
1082
+ if action.verb == "reload":
1083
+ await runtime.reload()
1084
+ panel.refresh()
1085
+ panel.set_message("已重新读取配置")
1086
+ self._invalidate()
1087
+ return
1088
+ if action.server is None:
1089
+ raise ValueError("MCP 动作缺少服务器名")
1090
+ if action.verb == "toggle":
1091
+ current = runtime.status(action.server)
1092
+ if current.state == "disabled":
1093
+ status = await runtime.enable(action.server)
1094
+ else:
1095
+ status = await runtime.disable(action.server)
1096
+ elif action.verb == "reconnect":
1097
+ status = await runtime.reconnect(action.server)
1098
+ else:
1099
+ status = await runtime.refresh(action.server)
1100
+ panel.refresh()
1101
+ message = f"{status.name} → {status.state}"
1102
+ if action.verb == "toggle":
1103
+ message = f"{message}(仅本次会话)"
1104
+ if status.error:
1105
+ message = f"{message}({' '.join(status.error.split())})"
1106
+ panel.set_message(message)
1107
+ self._invalidate()
1108
+
1109
+ # ------------------------------------------------------------ 补全导航
1110
+
1111
+ def _complete_move(self, delta: int) -> None:
1112
+ """在候选间循环移动选中项,浮层高亮随之更新。"""
1113
+ if not self._completion:
1114
+ return
1115
+ self._completion_selected = (self._completion_selected + delta) % len(self._completion)
1116
+ self._invalidate()
1117
+
1118
+ def _complete_accept(self) -> None:
1119
+ """用选中候选替换当前行内命令 token,并把光标放到末尾。"""
1120
+ if not self._completion:
1121
+ return
1122
+ chosen = self._completion[self._completion_selected]
1123
+ self._buffer.text = chosen.insert
1124
+ self._buffer.cursor_position = len(self._buffer.text)
1125
+ self._completion = ()
1126
+ self._completion_selected = 0
1127
+ self._invalidate()
1128
+
1129
+ # ------------------------------------------------------------ 提交与回合
1130
+
1131
+ def _on_buffer_accept(self, buffer: Buffer) -> bool:
1132
+ text = buffer.text
1133
+ buffer.text = ""
1134
+ self._completion = ()
1135
+ self._completion_selected = 0
1136
+ if self._approval is not None:
1137
+ self._resolve_approval(text)
1138
+ return True
1139
+ if self._question is not None:
1140
+ self._resolve_question(text)
1141
+ return True
1142
+ if text.strip():
1143
+ self.application.create_background_task(self._submit(text))
1144
+ return True
1145
+
1146
+ async def _submit(self, value: str) -> None:
1147
+ text = value.strip()
1148
+ if text.startswith("/"):
1149
+ await self._handle_command(parse_tui_command(text))
1150
+ return
1151
+ # 用户消息只由 session 派发的 MessageStartEvent(UserMessage) 写入历史。
1152
+ await self._turn(text)
1153
+
1154
+ async def _turn(self, text: str, *, skill: tuple[str, str] | None = None) -> None:
1155
+ task = asyncio.current_task()
1156
+ self._turn_task = task
1157
+ self._turn_started_at = time.monotonic()
1158
+ self._spinner_index = 0
1159
+ if not self._first_turn_marked:
1160
+ self._first_turn_marked = True
1161
+ if self._monitor is not None:
1162
+ self._monitor.mark("first_turn_start")
1163
+ self._invalidate()
1164
+ try:
1165
+ if skill is None:
1166
+ await self._session.prompt(text)
1167
+ else:
1168
+ await self._session.invoke_skill(*skill)
1169
+ await self._ask_plan_decision()
1170
+ except asyncio.CancelledError:
1171
+ raise
1172
+ except Exception as exc:
1173
+ self._model.on_notice(str(exc) or type(exc).__name__, role="err")
1174
+ self._invalidate()
1175
+ finally:
1176
+ self._turn_task = None
1177
+ self._turn_started_at = None
1178
+ self._invalidate()
1179
+
1180
+ def _load_skill_command(self, name: str) -> None:
1181
+ """``/skill <名字>``:只把正文装进上下文,不立即执行。"""
1182
+ if not name:
1183
+ self._model.on_notice("用法:/skill <名字>,或 /<名字> 直接调用", role="err")
1184
+ return
1185
+ try:
1186
+ doc = self._session.load_skill(name)
1187
+ except (RuntimeError, ValueError, PermissionError) as exc:
1188
+ self._model.on_notice(str(exc), role="err")
1189
+ return
1190
+ self._model.on_notice(f"已加载技能 {doc.name},下一回合模型可见")
1191
+
1192
+ async def _invoke_skill(self, name: str, args: str) -> None:
1193
+ """``/<技能名>``:加载正文并立刻跑一次 run。"""
1194
+ if not name:
1195
+ self._model.on_notice("用法:/<技能名> [参数];/skills 查看清单", role="err")
1196
+ return
1197
+ self._model.on_notice(f"调用技能 {name}" + (f"({args})" if args else ""))
1198
+ await self._turn(args, skill=(name, args))
1199
+
1200
+ # ------------------------------------------------------------ 规划模式
1201
+
1202
+ async def _handle_plan(self, args: str) -> None:
1203
+ """``/plan`` 子命令:进入、查看、批准、退出,或带目标进入。"""
1204
+ mode = self._session.plan_mode
1205
+ if mode is None:
1206
+ self._model.on_notice("本次运行没有装配规划模式", role="warn")
1207
+ return
1208
+ if self._turn_task is not None:
1209
+ # TUI 在生成期间仍然读键;模式切换只在两次 run 之间成立。
1210
+ self._model.on_notice("正在运行,等这一轮结束再切换规划模式", role="warn")
1211
+ return
1212
+ text = args.strip()
1213
+ action = text.partition(" ")[0].lower()
1214
+ if action in ("off", "exit", "quit"):
1215
+ if not mode.active and not mode.state.has_plan:
1216
+ self._model.on_notice("当前不在规划模式")
1217
+ return
1218
+ state = await self._session.leave_plan_mode()
1219
+ self._model.on_notice(f"已退出规划模式,权限恢复为 {state.restore_mode}")
1220
+ return
1221
+ if action in ("approve", "ok"):
1222
+ if not mode.state.has_plan:
1223
+ self._model.on_notice("还没有可批准的计划", role="err")
1224
+ return
1225
+ state = await self._session.approve_plan()
1226
+ self._model.on_notice(
1227
+ f"已批准第 {state.revision} 版计划,权限恢复为 {state.restore_mode}", role="ok"
1228
+ )
1229
+ self.application.create_background_task(self._turn("计划已获批准,按计划开始实施。"))
1230
+ return
1231
+ if action == "show":
1232
+ if not mode.state.has_plan:
1233
+ self._model.on_notice("还没有计划")
1234
+ else:
1235
+ self._model.on_plan_mode(mode.state, "submitted")
1236
+ return
1237
+ goal = text
1238
+ state = await self._session.enter_plan_mode(goal)
1239
+ if goal:
1240
+ self._model.on_notice(f"已进入规划模式(只读):{goal}")
1241
+ self.application.create_background_task(self._turn(goal))
1242
+ else:
1243
+ self._model.on_notice("已进入规划模式(只读):直接说出目标,模型会探索后提交计划")
1244
+ self._model.on_plan_mode(state, "entered")
1245
+
1246
+ async def _ask_plan_decision(self) -> None:
1247
+ """回合结束后审批刚提交的计划。
1248
+
1249
+ 审批放在回合边界:批准会切换权限模式,而系统提示词里的规划段落按回合算,
1250
+ 同一次 run 里换模式会让提示词与权限打架。
1251
+ """
1252
+ mode = self._session.plan_mode
1253
+ if mode is None:
1254
+ return
1255
+ state = mode.state
1256
+ if not state.active or not state.has_plan:
1257
+ return
1258
+ key = (state.revision, state.updated_at)
1259
+ if key == self._plan_prompted:
1260
+ return
1261
+ self._plan_prompted = key
1262
+ request = QuestionRequest(
1263
+ question="以上计划是否批准?",
1264
+ header=f"实施计划(第 {state.revision} 版)",
1265
+ options=(
1266
+ QuestionOption(label=PLAN_APPROVAL_APPROVE, description="退出规划模式并开始实施"),
1267
+ QuestionOption(
1268
+ label=PLAN_APPROVAL_REVISE, description="保持规划模式,说明要改什么"
1269
+ ),
1270
+ QuestionOption(label=PLAN_APPROVAL_EXIT, description="不执行这份计划"),
1271
+ ),
1272
+ )
1273
+ answer = await self.request_question(request, None)
1274
+ if answer.cancelled:
1275
+ self._model.on_notice("计划保持待批;/plan approve 可批准,/plan off 可退出")
1276
+ return
1277
+ intent = plan_command_intent(answer.custom)
1278
+ if intent == "approve" or PLAN_APPROVAL_APPROVE in answer.selected:
1279
+ approved = await self._session.approve_plan()
1280
+ self._model.on_notice(
1281
+ f"已批准第 {approved.revision} 版计划,权限恢复为 {approved.restore_mode}",
1282
+ role="ok",
1283
+ )
1284
+ await self._turn("计划已获批准,按计划开始实施。")
1285
+ return
1286
+ if intent == "off" or PLAN_APPROVAL_EXIT in answer.selected:
1287
+ left = await self._session.leave_plan_mode()
1288
+ self._model.on_notice(f"已退出规划模式,权限恢复为 {left.restore_mode}")
1289
+ return
1290
+ if answer.custom.strip().startswith("/"):
1291
+ self._model.on_notice(
1292
+ "审批浮层只接受序号或修改意见;命令请在输入行执行(计划保持待批)", role="warn"
1293
+ )
1294
+ return
1295
+ note = answer.custom.strip()
1296
+ if not note:
1297
+ self._model.on_notice("保持规划模式;直接说出要改什么,或 /plan off 退出")
1298
+ return
1299
+ await mode.revise()
1300
+ await self._turn(f"计划需要修改:{note}")
1301
+
1302
+ # ------------------------------------------------------------ 审批与提问
1303
+
1304
+ async def request_approval(
1305
+ self, prompt: PermissionPrompt, signal: CancelToken | None
1306
+ ) -> ApprovalAnswer:
1307
+ """权限引擎的交互通道:浮层里裁决,返回批准范围。
1308
+
1309
+ 等待期间的取消来源有三处:界面的 y/s/n 与 Esc、Ctrl+C、以及回合被
1310
+ 终止时 ``signal`` 变为已取消。三者都只会 resolve 一次。
1311
+ """
1312
+ loop = asyncio.get_running_loop()
1313
+ pending = _ApprovalPending(prompt=prompt, future=loop.create_future())
1314
+ self._approval = pending
1315
+ self._overlay = "approval"
1316
+ self._invalidate()
1317
+ watcher = asyncio.create_task(self._watch_cancel(signal, lambda: pending.resolve("deny")))
1318
+ try:
1319
+ return await pending.future
1320
+ finally:
1321
+ watcher.cancel()
1322
+ await asyncio.gather(watcher, return_exceptions=True)
1323
+ if self._approval is pending:
1324
+ self._approval = None
1325
+ self._overlay = None
1326
+ self._invalidate()
1327
+
1328
+ async def request_question(
1329
+ self, request: QuestionRequest, signal: CancelToken | None
1330
+ ) -> QuestionAnswer:
1331
+ """提问工具的交互通道:选项中选,或直接输入文字作答。"""
1332
+ loop = asyncio.get_running_loop()
1333
+ pending = _QuestionPending(request=request, future=loop.create_future())
1334
+ self._question = pending
1335
+ self._overlay = "question"
1336
+ self._invalidate()
1337
+ watcher = asyncio.create_task(
1338
+ self._watch_cancel(signal, lambda: pending.resolve(QuestionAnswer(cancelled=True)))
1339
+ )
1340
+ try:
1341
+ return await pending.future
1342
+ finally:
1343
+ watcher.cancel()
1344
+ await asyncio.gather(watcher, return_exceptions=True)
1345
+ if self._question is pending:
1346
+ self._question = None
1347
+ self._overlay = None
1348
+ self._invalidate()
1349
+
1350
+ async def _watch_cancel(self, signal: CancelToken | None, action: Callable[[], None]) -> None:
1351
+ """轮询取消令牌。``CancelToken`` 只有标志位,没有事件回调。"""
1352
+ if signal is None:
1353
+ return
1354
+ while not signal.cancelled:
1355
+ await asyncio.sleep(0.05)
1356
+ action()
1357
+
1358
+ def _resolve_approval(self, text: str) -> None:
1359
+ pending = self._approval
1360
+ if pending is None:
1361
+ return
1362
+ spec = text.strip().lower()
1363
+ if spec in ("n", "no", "deny"):
1364
+ scope = "deny"
1365
+ elif spec in ("s", "session"):
1366
+ scope = "session"
1367
+ elif spec in ("p", "project") and "project" in pending.options:
1368
+ scope = "project"
1369
+ elif spec in ("y", "yes"):
1370
+ scope = pending.options[pending.selected] if pending.options else "once"
1371
+ else:
1372
+ scope = pending.options[pending.selected] if pending.options else "once"
1373
+ pending.resolve(scope)
1374
+ self._approval = None
1375
+ self._overlay = None
1376
+ self._invalidate()
1377
+
1378
+ def _resolve_question(self, text: str) -> None:
1379
+ pending = self._question
1380
+ if pending is None:
1381
+ return
1382
+ answer = self._parse_question(pending, text)
1383
+ pending.resolve(answer)
1384
+ self._question = None
1385
+ self._overlay = None
1386
+ self._invalidate()
1387
+
1388
+ def _cancel_question(self) -> None:
1389
+ pending = self._question
1390
+ if pending is None:
1391
+ return
1392
+ pending.resolve(QuestionAnswer(cancelled=True))
1393
+ self._question = None
1394
+ self._overlay = None
1395
+ self._invalidate()
1396
+
1397
+ @staticmethod
1398
+ def _parse_question(pending: _QuestionPending, text: str) -> QuestionAnswer:
1399
+ """解析提问回答,规则与行式 REPL 一致。
1400
+
1401
+ 全部是合法序号 → 按选项回答;其余非空输入 → 原样作为补充文本;
1402
+ 空输入 → 用高亮项(多选时用已勾选项),都没有就取消。
1403
+ """
1404
+ spec = text.strip()
1405
+ options = pending.request.options
1406
+ if spec:
1407
+ tokens = [token for token in re.split(r"[,,、\s]+", spec) if token]
1408
+ if tokens and all(token.isdigit() for token in tokens):
1409
+ values = [int(token) for token in tokens]
1410
+ if all(1 <= value <= len(options) for value in values):
1411
+ if not pending.request.multiple:
1412
+ values = values[:1]
1413
+ labels: list[str] = []
1414
+ for value in values:
1415
+ label = options[value - 1].label
1416
+ if label not in labels:
1417
+ labels.append(label)
1418
+ return QuestionAnswer(selected=tuple(labels))
1419
+ return QuestionAnswer(custom=spec)
1420
+ if pending.request.multiple and pending.checked:
1421
+ checked_labels = tuple(options[index].label for index in sorted(pending.checked))
1422
+ return QuestionAnswer(selected=checked_labels)
1423
+ if options:
1424
+ return QuestionAnswer(selected=(options[pending.selected].label,))
1425
+ return QuestionAnswer(cancelled=True)
1426
+
1427
+ # ------------------------------------------------------------ 事件
1428
+
1429
+ def _on_event(self, event: Any) -> None:
1430
+ self._model.handle_event(event)
1431
+ now = time.monotonic()
1432
+ if now - self._status_at >= 0.25:
1433
+ self._refresh_status()
1434
+ self._status_at = now
1435
+ self._invalidate()
1436
+
1437
+ def _refresh_status(self) -> None:
1438
+ status = self._session.context_status()
1439
+ background = 0
1440
+ if self._subagents is not None:
1441
+ background = len(self._subagents.registry.running_background())
1442
+ totals = status.totals
1443
+ prompt_tokens = totals.input + totals.cache_read + totals.cache_write
1444
+ self._model.on_context(
1445
+ percent=status.percent,
1446
+ cost=totals.cost_total,
1447
+ tool_count=status.tool_count,
1448
+ background=background,
1449
+ permission_mode=self._permission_mode(),
1450
+ used_tokens=status.tokens,
1451
+ context_remaining=max(status.context_window - status.tokens, 0),
1452
+ context_window=status.context_window,
1453
+ cache_hit=totals.cache_hit_rate if prompt_tokens else None,
1454
+ )
1455
+
1456
+ # ------------------------------------------------------------ 命令
1457
+
1458
+ async def _handle_command(self, command: TuiCommand | None) -> None:
1459
+ if command is None:
1460
+ self._model.on_notice("无法解析命令")
1461
+ self._invalidate()
1462
+ return
1463
+ name = command.name
1464
+ if name == "quit":
1465
+ self.application.exit(result=0)
1466
+ return
1467
+ if name == "help":
1468
+ self._model.on_markdown(_HELP_MARKDOWN)
1469
+ elif name in ("models", "model"):
1470
+ if name == "model" and command.args:
1471
+ await self._switch_model(command.args)
1472
+ else:
1473
+ self._overlay = "models"
1474
+ self._selected_model_index = 0
1475
+ elif name in ("sessions", "resume"):
1476
+ await self._handle_resume(command.args)
1477
+ elif name == "diff":
1478
+ await self._show_diff(command.args)
1479
+ elif name == "plan":
1480
+ await self._handle_plan(command.args)
1481
+ elif name == "mcp":
1482
+ if command.args.strip():
1483
+ from braid_coding_agent.mcp.panel import run_panel
1484
+
1485
+ self._model.on_markdown(await run_panel(self._mcp, command.args))
1486
+ else:
1487
+ self._open_mcp_panel()
1488
+ elif name == "monitor":
1489
+ from braid_coding_agent.startup.report import format_monitor_report
1490
+
1491
+ columns, _ = self._terminal_size()
1492
+ self._model.on_plain(
1493
+ format_monitor_report(
1494
+ self._monitor,
1495
+ self._scheduler,
1496
+ command.args,
1497
+ width=max(20, columns - 2),
1498
+ )
1499
+ )
1500
+ elif name == "status":
1501
+ self._refresh_status()
1502
+ self._model.on_markdown(self._status_markdown())
1503
+ elif name == "context":
1504
+ self._refresh_status()
1505
+ self._model.on_markdown(self._context_markdown())
1506
+ elif name == "statusline":
1507
+ self._run_statusline_command(command.args)
1508
+ elif name == "permission":
1509
+ self._run_permission_command(command.args)
1510
+ elif name == "agents":
1511
+ await self._show_agents(command.args)
1512
+ elif name == "tasks":
1513
+ await self._show_tasks(command.args)
1514
+ elif name == "background":
1515
+ await self._run_background(command.args)
1516
+ elif name == "clear":
1517
+ await self._clear_session()
1518
+ elif name == "rewind":
1519
+ await self._handle_rewind(command.args)
1520
+ elif name == "compact":
1521
+ self._model.on_notice("压缩请在 --simple 模式下使用")
1522
+ elif name == "skills":
1523
+ self._show_skills(command.args)
1524
+ elif name == "skill":
1525
+ self._load_skill_command(command.args.strip())
1526
+ elif name in self._skill_specs():
1527
+ await self._invoke_skill(name, command.args)
1528
+ else:
1529
+ self._model.on_notice(f"未知命令:/{name}")
1530
+ self._invalidate()
1531
+
1532
+ def _completions_for(self, text: str) -> tuple[CompletionItem, ...]:
1533
+ """输入行 → 补全候选:内建命令加上当前会话可见的技能。"""
1534
+ return command_completions(text, self._skill_items())
1535
+
1536
+ def _skill_items(self) -> tuple[CompletionItem, ...]:
1537
+ """技能的补全候选。技能名与 TUI 命令同名时不暴露成 ``/名字``。"""
1538
+ reserved = set(TUI_COMMAND_NAMES)
1539
+ return tuple(
1540
+ CompletionItem(candidate.insert.removeprefix("/"), candidate.hint, candidate.summary)
1541
+ for candidate in skill_completions(self._session.skills_loader, reserved)
1542
+ )
1543
+
1544
+ def _skill_specs(self) -> dict[str, CommandSpec]:
1545
+ reserved = set(TUI_COMMAND_NAMES)
1546
+ loader = self._session.skills_loader
1547
+ for name in conflicting_skill_names(loader, reserved):
1548
+ if name not in self._reported_skill_conflicts:
1549
+ self._reported_skill_conflicts.add(name)
1550
+ self._model.on_notice(
1551
+ f"技能 {name!r} 与已有命令同名,不能作为 /{name} 调用;改用 /skill {name}",
1552
+ role="err",
1553
+ )
1554
+ return skill_specs(loader, reserved)
1555
+
1556
+ def _show_skills(self, args: str) -> None:
1557
+ """``/skills``:把技能清单渲染成表格,来源、调用方式与约束各占一列。"""
1558
+ loader = self._session.skills_loader
1559
+ if loader is None:
1560
+ self._model.on_notice("本次运行没有装配 Skills", role="warn")
1561
+ return
1562
+ loader.refresh()
1563
+ docs = loader.documents
1564
+ if not docs:
1565
+ self._model.on_notice(
1566
+ "没有发现技能:在 ~/.braid/skills/<名字>/SKILL.md 或 "
1567
+ "<项目>/.braid/skills/<名字>/SKILL.md 放一份即可"
1568
+ )
1569
+ return
1570
+ keyword = args.strip().lower()
1571
+ reserved = set(TUI_COMMAND_NAMES)
1572
+ shown = [
1573
+ doc
1574
+ for doc in docs
1575
+ if not keyword or keyword in doc.name or keyword in doc.description.lower()
1576
+ ]
1577
+ if not shown:
1578
+ self._model.on_notice(f"没有匹配 {args.strip()!r} 的技能")
1579
+ return
1580
+ lines = ["| 技能 | 来源 | 调用 | 说明 |", "|---|---|---|---|"]
1581
+ for doc in shown:
1582
+ if not doc.user_invocable:
1583
+ how = "仅模型"
1584
+ elif doc.disable_model_invocation:
1585
+ how = "仅显式"
1586
+ elif doc.name in reserved:
1587
+ how = "`/skill`"
1588
+ else:
1589
+ how = f"`/{doc.name}`"
1590
+ description = doc.description.replace("|", "\\|")
1591
+ lines.append(f"| `{doc.name}` | {doc.source} | {how} | {description} |")
1592
+ self._model.on_markdown("\n".join(lines))
1593
+ if not keyword:
1594
+ self._model.on_notice(
1595
+ f"共 {len(docs)} 个技能:/名字 直接调用,/skill <名字> 只加载正文"
1596
+ )
1597
+ for warning in loader.diagnostics:
1598
+ role = "err" if warning.kind == "collision" else "warn"
1599
+ self._model.on_notice(f"{warning.kind}: {warning.message}", role=role)
1600
+
1601
+ def _run_permission_command(self, args: str) -> None:
1602
+ engine = self._session.permission_engine
1603
+ if engine is None:
1604
+ self._model.on_notice("本次运行没有装配权限引擎", role="err")
1605
+ return
1606
+ try:
1607
+ parsed = parse_permission_command(args)
1608
+ except PermissionCommandError as exc:
1609
+ self._model.on_notice(str(exc), role="err")
1610
+ return
1611
+ result = execute_permission_command(parsed, engine)
1612
+ for role, text in result.lines:
1613
+ if role == "error":
1614
+ self._model.on_notice(text, role="err")
1615
+ elif role == "dim":
1616
+ self._model.on_notice(text, role="muted")
1617
+ else:
1618
+ self._model.on_notice(text)
1619
+
1620
+ def _status_markdown(self) -> str:
1621
+ status = self._session.context_status()
1622
+ model = f"{self._session.model.provider}/{self._session.model.id}"
1623
+ session_dir = self._session.session.get_session_dir() or "内存会话"
1624
+ rows = [
1625
+ ("模型", f"`{model}`"),
1626
+ ("上下文", f"{status.percent:.1f}%"),
1627
+ ("费用", f"${status.totals.cost_total:.4f}"),
1628
+ ("缓存命中", f"{status.totals.cache_hit_rate:.1%}"),
1629
+ ("工具调用", str(status.tool_count)),
1630
+ ("权限模式", self._permission_mode()),
1631
+ ("会话", f"`{session_dir}`"),
1632
+ ]
1633
+ lines = ["| 项目 | 值 |", "|---|---|"]
1634
+ lines.extend(f"| {name} | {value} |" for name, value in rows)
1635
+ return "\n".join(lines)
1636
+
1637
+ def _context_markdown(self) -> str:
1638
+ """``/context``:把上下文总量拆成互不重叠的来源,并给出压缩余量。"""
1639
+ status = self._session.context_status()
1640
+ breakdown = self._session.context_breakdown(
1641
+ subagent_names=self._subagent_names(),
1642
+ mcp_servers=self._mcp_server_names(),
1643
+ )
1644
+ rows = self._breakdown_rows(breakdown)
1645
+ rows.append(
1646
+ (
1647
+ "上下文总量",
1648
+ f"{breakdown.total_tokens} tokens · {status.percent:.1f}%"
1649
+ f"(usage {status.usage_tokens} + 估算 {status.trailing_tokens})",
1650
+ )
1651
+ )
1652
+ rows.append(("上下文窗口", f"{status.context_window} tokens"))
1653
+ if status.threshold is not None and status.remaining_tokens is not None:
1654
+ rows.append(("自动压缩", f"触发线 {status.threshold} · 剩余 {status.remaining_tokens}"))
1655
+ if status.queue_length:
1656
+ rows.append(("待注入消息", str(status.queue_length)))
1657
+ lines = ["| 项目 | 值 |", "|---|---|"]
1658
+ lines.extend(f"| {name} | {value} |" for name, value in rows)
1659
+ return "\n".join(lines)
1660
+
1661
+ @staticmethod
1662
+ def _breakdown_rows(breakdown: ContextBreakdown) -> list[tuple[str, str]]:
1663
+ """把上下文明细翻成两列:分项名与 token、占窗口百分比及出处。"""
1664
+ rows: list[tuple[str, str]] = []
1665
+ if breakdown.part("system") is None:
1666
+ rows.append(("系统提示词", "0 tokens · 0.0%(尚未发送到模型)"))
1667
+ for part in breakdown.parts:
1668
+ detail = f" · {part.detail}" if part.detail else ""
1669
+ percent = breakdown.percent_of_window(part.tokens)
1670
+ rows.append((part.label, f"{part.tokens} tokens · {percent:.1f}%{detail}"))
1671
+ estimated_percent = breakdown.percent_of_window(breakdown.estimated_tokens)
1672
+ rows.append(
1673
+ ("合计", f"{breakdown.estimated_tokens} tokens · {estimated_percent:.1f}%(分项估算)")
1674
+ )
1675
+ residual_percent = breakdown.percent_of_window(breakdown.residual_tokens)
1676
+ residual_share = f"{residual_percent:+.1f}%" if breakdown.residual_tokens else "0.0%"
1677
+ rows.append(("服务端未归因", f"{breakdown.residual_tokens:+d} tokens · {residual_share}"))
1678
+ return rows
1679
+
1680
+ def _run_statusline_command(self, args: str) -> None:
1681
+ """查看可选字段,或把当前会话的状态栏改成给定字段与顺序。"""
1682
+ text = args.strip()
1683
+ if not text:
1684
+ lines = ["| 字段 | 说明 |", "|---|---|"]
1685
+ lines.extend(f"| `{field.key}` | {field.summary} |" for field in STATUS_FIELDS)
1686
+ self._model.on_markdown("\n".join(lines))
1687
+ current = " · ".join(self._model.statusline_fields)
1688
+ self._model.on_notice(f"当前状态栏字段:{current}")
1689
+ self._model.on_notice(
1690
+ "用法:/statusline model,cost · /statusline reset;"
1691
+ "写入 ~/.braid/settings.json 的 statusline.fields 可跨会话生效"
1692
+ )
1693
+ return
1694
+ if text.lower() == "reset":
1695
+ self._model.set_statusline_fields(DEFAULT_STATUS_FIELDS)
1696
+ self._model.on_notice(f"状态栏字段:已恢复默认({' · '.join(DEFAULT_STATUS_FIELDS)})")
1697
+ self._refresh_status()
1698
+ return
1699
+ try:
1700
+ fields = parse_status_fields(text)
1701
+ except ValueError as exc:
1702
+ self._model.on_notice(str(exc), role="err")
1703
+ return
1704
+ self._model.set_statusline_fields(fields)
1705
+ self._model.on_notice(f"状态栏字段:{' · '.join(fields)}")
1706
+ self._refresh_status()
1707
+
1708
+ def _subagent_names(self) -> tuple[str, ...]:
1709
+ if self._subagents is None:
1710
+ return ()
1711
+ return tuple(spec.name for spec in self._subagents.specs())
1712
+
1713
+ def _mcp_server_names(self) -> tuple[str, ...]:
1714
+ if self._mcp is None:
1715
+ return ()
1716
+ return tuple(status.name for status in self._mcp.statuses())
1717
+
1718
+ # -------------------------------------------------------- 子代理命令
1719
+
1720
+ async def _show_agents(self, args: str) -> None:
1721
+ runtime = self._subagents
1722
+ if runtime is None:
1723
+ self._model.on_notice("本次运行没有装配子代理运行时,/agents 不可用", role="warn")
1724
+ return
1725
+ text = args.strip()
1726
+ if text == "reload":
1727
+ try:
1728
+ scan = runtime.reload()
1729
+ except RuntimeError as exc:
1730
+ self._model.on_notice(str(exc), role="err")
1731
+ return
1732
+ self._model.on_notice(f"已重新扫描子代理定义,共 {len(scan.specs)} 个")
1733
+ elif text.startswith("create "):
1734
+ self._create_agent_definition(text[len("create ") :].strip())
1735
+ return
1736
+ elif text.startswith("switch "):
1737
+ await self._resume_path(os.path.expanduser(text[len("switch ") :].strip()))
1738
+ return
1739
+ elif text.startswith("show "):
1740
+ text = text[len("show ") :].strip()
1741
+ elif text and text != "list":
1742
+ task = runtime.registry.get(text)
1743
+ if task is None:
1744
+ self._model.on_notice(f"没有任务 {text};用 /tasks 查看任务号", role="err")
1745
+ return
1746
+ self._model.on_notice(task.result_text())
1747
+ return
1748
+ self._model.on_markdown(self._agents_markdown(runtime))
1749
+ if runtime.definition_diagnostics:
1750
+ self._model.on_markdown(self._diagnostics_markdown(runtime))
1751
+ tasks = runtime.registry.tasks()
1752
+ if tasks:
1753
+ self._model.on_markdown(self._tasks_markdown(runtime))
1754
+ else:
1755
+ self._model.on_notice(
1756
+ "还没有派生过子代理;模型用 task 工具派生,/background 分离整个会话"
1757
+ )
1758
+
1759
+ def _agents_markdown(self, runtime: SubagentRuntime) -> str:
1760
+ lines = ["| 子代理 | 工具 | 权限 | 说明 |", "|---|---|---|---|"]
1761
+ for spec in runtime.specs():
1762
+ tools = "继承父会话" if spec.tools is None else (", ".join(spec.tools) or "无")
1763
+ extras: list[str] = [tools]
1764
+ if spec.disallowed_tools:
1765
+ extras.append("排除 " + ", ".join(spec.disallowed_tools))
1766
+ if spec.skills:
1767
+ extras.append("技能 " + ", ".join(spec.skills))
1768
+ if spec.isolation != "inherit":
1769
+ extras.append(f"隔离 {spec.isolation}")
1770
+ description = spec.description.replace("|", "\\|")
1771
+ lines.append(
1772
+ f"| `{spec.name}` | {' · '.join(extras)} | "
1773
+ f"{spec.permission_mode or 'inherit'} | {description} |"
1774
+ )
1775
+ return "\n".join(lines)
1776
+
1777
+ def _diagnostics_markdown(self, runtime: SubagentRuntime) -> str:
1778
+ lines = ["| 定义问题 | 说明 |", "|---|---|"]
1779
+ for issue in runtime.definition_diagnostics:
1780
+ kind = "跳过" if issue.kind == "skipped" else "忽略"
1781
+ message = issue.message.replace("|", "\\|")
1782
+ lines.append(f"| `{issue.path}`({kind}) | {message} |")
1783
+ return "\n".join(lines)
1784
+
1785
+ def _tasks_markdown(self, runtime: SubagentRuntime) -> str:
1786
+ lines = ["| 任务 | 子代理 | 状态 | 结果 |", "|---|---|---|---|"]
1787
+ for task in runtime.registry.tasks():
1788
+ detail = task.error if task.status in ("failed", "cancelled") else task.summary
1789
+ detail = (detail or task.cwd).replace("\n", " ")[:60].replace("|", "\\|")
1790
+ location = "后台" if task.background else "同步"
1791
+ lines.append(f"| `{task.id}` | {task.agent} | {task.status}({location}) | {detail} |")
1792
+ return "\n".join(lines)
1793
+
1794
+ async def _show_tasks(self, args: str) -> None:
1795
+ runtime = self._subagents
1796
+ if runtime is None:
1797
+ self._model.on_notice("本次运行没有装配子代理运行时,/tasks 不可用", role="warn")
1798
+ return
1799
+ text = args.strip()
1800
+ if text and text != "list":
1801
+ await self._task_action(runtime, text)
1802
+ return
1803
+ tasks = runtime.registry.tasks()
1804
+ if not tasks:
1805
+ self._model.on_notice("还没有派生过子代理")
1806
+ return
1807
+ self._model.on_markdown(self._tasks_markdown(runtime))
1808
+ for task in tasks:
1809
+ if task.worktree:
1810
+ self._model.on_notice(
1811
+ f"{task.id} 工作树 {task.worktree}({task.branch or '未知'})"
1812
+ )
1813
+ if task.session_file:
1814
+ self._model.on_notice(f"{task.id} 子会话 {task.session_file}")
1815
+ self._model.on_notice(
1816
+ "/tasks show <任务号> 看完整结果,cancel 取消,send 追加消息,clear 清理已结束记录"
1817
+ )
1818
+
1819
+ async def _task_action(self, runtime: SubagentRuntime, text: str) -> None:
1820
+ command, _, rest = text.partition(" ")
1821
+ rest = rest.strip()
1822
+ if command == "show" or (command not in ("cancel", "send", "clear") and not rest):
1823
+ task_id = rest if command == "show" else command
1824
+ task = runtime.registry.get(task_id)
1825
+ if task is None:
1826
+ self._model.on_notice(f"没有任务 {task_id};用 /tasks 查看任务号", role="err")
1827
+ return
1828
+ self._model.on_notice(task.result_text())
1829
+ return
1830
+ if command == "cancel":
1831
+ self._model.on_notice(runtime.cancel(rest))
1832
+ return
1833
+ if command == "send":
1834
+ task_id, _, message = rest.partition(" ")
1835
+ if not task_id or not message.strip():
1836
+ self._model.on_notice("用法:/tasks send <任务号> <消息>", role="err")
1837
+ return
1838
+ self._model.on_notice(await runtime.send(task_id, message.strip()))
1839
+ return
1840
+ if command == "clear":
1841
+ removed = runtime.clear_finished()
1842
+ if removed:
1843
+ self._model.on_notice(f"已清理 {len(removed)} 条已结束的任务:{', '.join(removed)}")
1844
+ else:
1845
+ self._model.on_notice("没有可清理的已结束任务")
1846
+ return
1847
+ self._model.on_notice(
1848
+ "用法:/tasks [list|show <任务号>|cancel <任务号>|send <任务号> <消息>|clear]",
1849
+ role="err",
1850
+ )
1851
+
1852
+ def _create_agent_definition(self, name: str) -> None:
1853
+ if not is_valid_agent_name(name):
1854
+ self._model.on_notice(
1855
+ "名字只能用小写字母、数字、下划线与连字符,且以字母开头", role="err"
1856
+ )
1857
+ return
1858
+ from braid_coding_agent.config import PROJECT_CONFIG_DIR
1859
+
1860
+ directory = Path(self._session.session.get_cwd()) / PROJECT_CONFIG_DIR / "agents"
1861
+ path = directory / f"{name}.md"
1862
+ if path.exists():
1863
+ self._model.on_notice(f"{path} 已经存在;直接编辑它,或换一个名字", role="err")
1864
+ return
1865
+ directory.mkdir(parents=True, exist_ok=True)
1866
+ path.write_text(agent_template(name), encoding="utf-8")
1867
+ self._model.on_notice(f"已创建子代理定义 {path};编辑后执行 /agents reload")
1868
+
1869
+ async def _run_background(self, args: str) -> None:
1870
+ runtime = self._subagents
1871
+ if runtime is None:
1872
+ self._model.on_notice("本次运行没有装配子代理运行时,/background 不可用", role="warn")
1873
+ return
1874
+ prompt = args.strip()
1875
+ if not prompt:
1876
+ self._model.on_notice(
1877
+ "用法:/background <任务描述>;会把当前会话的完整转录克隆到后台继续执行",
1878
+ role="err",
1879
+ )
1880
+ return
1881
+
1882
+ async def notify(task: SubagentTask) -> None:
1883
+ if self._session.is_disposed:
1884
+ return
1885
+ await self._session.follow_up(
1886
+ f"[后台会话结果 · {task.id}]\n{task.result_text()}\n请把结果汇总给用户。"
1887
+ )
1888
+ self._model.on_notice(f"后台会话 {task.id} 已完成,结果已排队")
1889
+
1890
+ try:
1891
+ task = await runtime.start_detached(session=self._session, prompt=prompt, notify=notify)
1892
+ except (RuntimeError, ValueError) as exc:
1893
+ self._model.on_notice(str(exc), role="err")
1894
+ return
1895
+ self._model.on_notice(
1896
+ f"后台会话 {task.id} 已启动;共享工作目录,完成时结果会作为排队消息注入"
1897
+ )
1898
+
1899
+ async def _show_diff(self, args: str) -> None:
1900
+ """``/diff``:把会话基线到当前工作区的差异放进记录,交给 Rich 高亮。"""
1901
+ mode = args.strip()
1902
+ if mode:
1903
+ self._model.on_notice(f"/diff 只接受空参数(收到:{mode});完整 git 差异请用 --simple")
1904
+ return
1905
+ checkpoints = self._session.checkpoints
1906
+ if checkpoints is None:
1907
+ self._model.on_notice("检查点未启用:无法读取本次会话改动", role="warn")
1908
+ return
1909
+ try:
1910
+ diff = await checkpoints.diff(max_lines=TuiModel.DIFF_MAX_LINES)
1911
+ except (CheckpointError, GitError) as exc:
1912
+ self._model.on_notice(f"无法读取会话改动:{exc}", role="err")
1913
+ return
1914
+ if not diff.changes:
1915
+ self._model.on_notice("本次会话没有改动文件")
1916
+ return
1917
+ seen = "、".join(change.path for change in diff.changes[:4])
1918
+ suffix = f" 等 {len(diff.changes)} 个文件" if len(diff.changes) > 4 else ""
1919
+ self._model.on_diff(diff.patch, f"{len(diff.changes)} 个文件:{seen}{suffix}")
1920
+ self._scroll_top = None
1921
+
1922
+ async def _switch_model(self, spec: str) -> None:
1923
+ provider, _, model_id = spec.partition("/")
1924
+ if not model_id:
1925
+ model_id, provider = provider, self._session.model.provider
1926
+ try:
1927
+ await self._session.set_model(provider, model_id)
1928
+ self._model.on_model_changed(self._session.model)
1929
+ except (ValueError, KeyError) as exc:
1930
+ self._model.on_notice(str(exc), role="err")
1931
+
1932
+ async def _clear_session(self) -> None:
1933
+ """开始一个新会话:沿用当前会话的 cwd 与落盘策略。"""
1934
+ current = self._session.session
1935
+ if current.is_persisted():
1936
+ manager = SessionManager.create(
1937
+ current.get_cwd(), current.get_session_dir(), clock=self._clock
1938
+ )
1939
+ else:
1940
+ manager = SessionManager.in_memory(current.get_cwd(), clock=self._clock)
1941
+ await self._switch_session(manager)
1942
+
1943
+ async def _switch_session(self, manager: SessionManager) -> None:
1944
+ """换一棵会话树,并迁移事件订阅、模型状态与计划面板。"""
1945
+ if self._build_session is None:
1946
+ self._model.on_notice("当前入口不支持换会话", role="warn")
1947
+ return
1948
+ old = self._session
1949
+ new = self._build_session(manager)
1950
+ if self._unsubscribe is not None:
1951
+ self._unsubscribe()
1952
+ await old.dispose()
1953
+ self._session = new
1954
+ self._unsubscribe = new.subscribe(self._on_event)
1955
+ # 记录区按新会话的转录重画:切到一份旧会话之后,屏幕上要是那份会话的内容,
1956
+ # 新会话(``/clear``)的转录里只有基线系统消息,画出来就是空的。
1957
+ self._model.replay(new.agent.state.messages)
1958
+ self._model.on_model_changed(new.model)
1959
+ # 回退清单属于旧会话的轮次,换会话之后就失效了。
1960
+ self._rewind_menu = ()
1961
+ # 新会话有自己的规划模式状态:审批记录跟着会话走。
1962
+ state = new.plan_mode.state if new.plan_mode is not None else None
1963
+ self._plan_prompted = (
1964
+ (state.revision, state.updated_at) if state is not None and state.has_plan else None
1965
+ )
1966
+ if state is not None:
1967
+ self._model.reset_plan_mode(state)
1968
+ self._banner = self._banner_lines() if self._options.banner else ()
1969
+ self._scroll_top = None
1970
+ self._spinner_index = 0
1971
+ self._refresh_status()
1972
+ self._invalidate()
1973
+
1974
+ # ------------------------------------------------------------ 会话列表
1975
+
1976
+ async def _handle_resume(self, args: str) -> None:
1977
+ """``/resume [序号|会话文件]``:不带参数弹出清单,带参数直接切过去。
1978
+
1979
+ 序号只在刚列过清单之后有效:会话目录随时可能多出新的文件,"第 3 个"过一会儿
1980
+ 就指到别处去了,静默切错比要求重新列一遍代价大得多。
1981
+ """
1982
+ text = args.strip()
1983
+ if not text:
1984
+ await self._open_session_list()
1985
+ return
1986
+ if text.isdigit():
1987
+ if not self._session_choices:
1988
+ self._model.on_notice("先用 /resume 列出会话,再用序号选择", role="warn")
1989
+ return
1990
+ index = int(text)
1991
+ if not 1 <= index <= len(self._session_choices):
1992
+ self._model.on_notice(
1993
+ f"序号要在 1 到 {len(self._session_choices)} 之间", role="err"
1994
+ )
1995
+ return
1996
+ await self._resume_session(index)
1997
+ return
1998
+ await self._resume_path(os.path.expanduser(text))
1999
+
2000
+ async def _open_session_list(self) -> None:
2001
+ """``/resume`` 不带参数:列出会话目录里的会话,Enter 切过去。"""
2002
+ if not self._session.session.is_persisted():
2003
+ self._model.on_notice("内存会话没有会话目录,无法列出其他会话", role="warn")
2004
+ return
2005
+ session_dir = self._session.session.get_session_dir()
2006
+ if not session_dir:
2007
+ self._model.on_notice("内存会话没有会话目录,无法列出其他会话", role="warn")
2008
+ return
2009
+ try:
2010
+ listing = await asyncio.to_thread(list_sessions, session_dir, limit=_SESSION_LIST_LIMIT)
2011
+ except OSError as exc:
2012
+ self._model.on_notice(f"无法读取会话目录 {session_dir}:{exc}", role="err")
2013
+ return
2014
+ if not listing.sessions:
2015
+ self._model.on_notice(f"这个目录里还没有会话:{session_dir}")
2016
+ return
2017
+ current = self._session.session.get_session_file()
2018
+ current_path = os.path.abspath(current) if current is not None else None
2019
+ self._session_choices = list(listing.sessions)
2020
+ self._session_current_path = current_path
2021
+ self._overlay = "sessions"
2022
+ self._selected_model_index = 0
2023
+ if listing.skipped:
2024
+ self._model.on_notice(f"另有 {len(listing.skipped)} 个会话文件读不出来", role="muted")
2025
+ self._invalidate()
2026
+
2027
+ async def _resume_session(self, index: int) -> None:
2028
+ """切到清单里的第 ``index`` 份会话。"""
2029
+ if not 1 <= index <= len(self._session_choices):
2030
+ return
2031
+ choice = self._session_choices[index - 1]
2032
+ if self._session_current_path == choice.path:
2033
+ self._model.on_notice("已经是当前会话")
2034
+ return
2035
+ try:
2036
+ manager = SessionManager.open(choice.path)
2037
+ except SessionLockedError as exc:
2038
+ self._model.on_notice(str(exc), role="err")
2039
+ return
2040
+ except (OSError, ValueError) as exc:
2041
+ self._model.on_notice(f"无法打开会话 {choice.path}:{exc}", role="err")
2042
+ return
2043
+ await self._switch_session(manager)
2044
+ self._model.on_notice(f"已切换到 {choice.title()}")
2045
+ self._session_choices = []
2046
+
2047
+ async def _resume_path(self, path: str) -> None:
2048
+ """按文件路径切到另一份会话。"""
2049
+ if not Path(path).exists():
2050
+ self._model.on_notice(f"会话文件不存在:{path}", role="err")
2051
+ return
2052
+ current = self._session.session.get_session_file()
2053
+ if current is not None and os.path.abspath(path) == os.path.abspath(current):
2054
+ self._model.on_notice("已经是当前会话")
2055
+ return
2056
+ try:
2057
+ manager = SessionManager.open(path)
2058
+ except SessionLockedError as exc:
2059
+ self._model.on_notice(str(exc), role="err")
2060
+ return
2061
+ except (OSError, ValueError) as exc:
2062
+ self._model.on_notice(f"无法打开会话 {path}:{exc}", role="err")
2063
+ return
2064
+ await self._switch_session(manager)
2065
+ self._model.on_notice(f"已切换到 {Path(path).name}")
2066
+ # 序号属于上一份清单,换了会话之后不再成立。
2067
+ self._session_choices = []
2068
+
2069
+ # ------------------------------------------------------------ 回退
2070
+
2071
+ async def _handle_rewind(self, args: str) -> None:
2072
+ """``/rewind``:不带参数弹出可选择的轮次清单,带序号则直接回退到那一轮之前。
2073
+
2074
+ 清单与 ``/sessions`` 同一套按键:↑↓ 选、Enter 确认、Esc 取消。回退范围仍然
2075
+ 要问一次:整树恢复会删掉目标快照之后新增的文件,不能替用户默认。
2076
+ """
2077
+ if self._turn_task is not None and not self._turn_task.done():
2078
+ self._model.on_notice("正在运行,等这一轮结束再回退", role="warn")
2079
+ return
2080
+ targets = await build_targets(self._session)
2081
+ if not targets:
2082
+ self._model.on_notice("当前会话还没有可回退的用户提问")
2083
+ return
2084
+ text = args.strip()
2085
+ if not text:
2086
+ self._rewind_menu = tuple((target, target.menu_label()) for target in targets)
2087
+ self._overlay = "rewind"
2088
+ # 默认停在最近一轮:用户想撤掉的通常是他刚说完的那句。
2089
+ self._selected_model_index = len(targets) - 1
2090
+ self._invalidate()
2091
+ return
2092
+ tokens = text.split()
2093
+ try:
2094
+ mode = parse_mode_flags(tokens[1:])
2095
+ except ValueError as exc:
2096
+ self._model.on_notice(str(exc), role="err")
2097
+ return
2098
+ if not tokens[0].isdigit():
2099
+ self._model.on_notice(f"回退位置要给序号(1 到 {len(targets)})", role="err")
2100
+ return
2101
+ index = int(tokens[0])
2102
+ if not 1 <= index <= len(targets):
2103
+ self._model.on_notice(f"序号要在 1 到 {len(targets)} 之间", role="err")
2104
+ return
2105
+ await self._rewind_to(targets[index - 1], mode)
2106
+
2107
+ async def _rewind_to(self, target: RewindTarget, mode: RewindMode | None = None) -> None:
2108
+ """对选中的位置执行回退。没给范围时先问一次。"""
2109
+ if mode is None:
2110
+ mode = await self._ask_rewind_mode(target)
2111
+ if mode is None:
2112
+ self._model.on_notice("已取消,什么都没改")
2113
+ return
2114
+ elif mode in ("files", "all") and not target.can_restore_files:
2115
+ self._model.on_notice(
2116
+ f"第 {target.index} 轮没有文件快照,只能回退对话(--conversation)", role="err"
2117
+ )
2118
+ return
2119
+ try:
2120
+ outcome = await apply_rewind(self._session, target, mode=mode)
2121
+ except (RewindError, CheckpointError, GitError) as exc:
2122
+ self._model.on_notice(f"回退失败:{exc}", role="err")
2123
+ return
2124
+ # 记录区按回退后的转录重画:留着被放弃那几轮的内容,用户会以为它们还在。
2125
+ self._model.replay(self._session.agent.state.messages)
2126
+ self._model.on_notice(outcome.summary())
2127
+ self._model.on_notice("当前对话已按回退后的路径重建;被放弃的内容仍在会话文件里")
2128
+ self._scroll_top = None
2129
+ self._invalidate()
2130
+
2131
+ async def _ask_rewind_mode(self, target: RewindTarget) -> RewindMode | None:
2132
+ """问一次回退范围。返回 ``None`` 表示取消。"""
2133
+ self._model.on_notice(f"回退到第 {target.index} 轮提问之前({target.preview})")
2134
+ self._model.on_notice(f"放弃 {target.dropped_messages} 条消息")
2135
+ options = [QuestionOption("只回退对话")]
2136
+ if target.can_restore_files:
2137
+ changes = await file_preview(self._session, target)
2138
+ if changes:
2139
+ self._model.on_notice(f"文件:{len(changes)} 个会被改动{change_breakdown(changes)}")
2140
+ options.append(QuestionOption("对话与文件", "工作区恢复到那一轮开始前的快照"))
2141
+ answer = await self.request_question(
2142
+ QuestionRequest(question="回退范围", options=tuple(options), header="回退"),
2143
+ None,
2144
+ )
2145
+ if answer.cancelled or answer.is_empty:
2146
+ return None
2147
+ if answer.selected and answer.selected[0] == "对话与文件":
2148
+ return "all"
2149
+ if answer.selected and answer.selected[0] == "只回退对话":
2150
+ return "conversation"
2151
+ return None
2152
+
2153
+ # ------------------------------------------------------------ 选项来源
2154
+
2155
+ def _model_options(self) -> list[str]:
2156
+ options = [f"{m.provider}/{m.id}" for m in self._models.list_models()]
2157
+ current = f"{self._session.model.provider}/{self._session.model.id}"
2158
+ # 当前模型必须出现在选择框里并标 ●(活动状态可见),即便它来自脚本/
2159
+ # 会话记录而不在目录清单中。
2160
+ if current not in options:
2161
+ options.insert(0, current)
2162
+ return options
2163
+
2164
+ def _session_options(self) -> list[str]:
2165
+ if not self._session_choices:
2166
+ return ["(没有列出会话:先用 /sessions 打开列表)"]
2167
+ current = self._session_current_path
2168
+ options: list[str] = []
2169
+ for item in self._session_choices:
2170
+ marker = "●" if current == item.path else " "
2171
+ options.append(f"{marker} {item.describe()}")
2172
+ return options
2173
+
2174
+ def _rewind_options(self) -> list[str]:
2175
+ return [label for _, label in self._rewind_menu]
2176
+
2177
+ # ------------------------------------------------------------ 主循环与信号
2178
+
2179
+ async def run(self, initial: str | None = None) -> int:
2180
+ """跑到 EOF / ``/quit`` / 空闲 Ctrl+C。返回应用退出码。"""
2181
+ app = self.build_application()
2182
+ self._unsubscribe = self._session.subscribe(self._on_event)
2183
+ self._refresh_status()
2184
+ self._termination.install()
2185
+ if initial:
2186
+ app.create_background_task(self._turn(initial))
2187
+ if self._termination.installed:
2188
+ self._watch_task = app.create_background_task(self._watch_termination())
2189
+ # spinner 与耗时按固定节拍推进;空闲时只唤醒、不重绘。
2190
+ activity_task = app.create_background_task(self._tick_activity())
2191
+ try:
2192
+ self._exit_code = await app.run_async()
2193
+ finally:
2194
+ self._batch.close()
2195
+ self._unsubscribe_scheduler()
2196
+ activity_task.cancel()
2197
+ await asyncio.gather(activity_task, return_exceptions=True)
2198
+ if self._watch_task is not None:
2199
+ self._watch_task.cancel()
2200
+ await asyncio.gather(self._watch_task, return_exceptions=True)
2201
+ if self._turn_task is not None and not self._turn_task.done():
2202
+ self._turn_task.cancel()
2203
+ await asyncio.gather(self._turn_task, return_exceptions=True)
2204
+ await app.cancel_and_wait_for_background_tasks()
2205
+ self._termination.close()
2206
+ await shutdown_session(self._session, unsubscribe=self._unsubscribe)
2207
+ self._unsubscribe = None
2208
+ return self._exit_code
2209
+
2210
+ async def _tick_activity(self) -> None:
2211
+ """回合进行中推进 spinner 与耗时。回合外不触发重绘。"""
2212
+ while True:
2213
+ await asyncio.sleep(ACTIVITY_TICK_SECONDS)
2214
+ if not self._activity_visible():
2215
+ continue
2216
+ self._spinner_index = (self._spinner_index + 1) % len(SPINNER_FRAMES)
2217
+ self._invalidate()
2218
+
2219
+ async def _watch_termination(self) -> None:
2220
+ signum = await self._termination.wait()
2221
+ self._exit_code = self._termination.exit_code
2222
+ if self._turn_task is not None and not self._turn_task.done():
2223
+ await self._session.abort()
2224
+ self.application.exit(result=self._exit_code)
2225
+ # signum 已经记录到 TerminationHandler,这里只负责唤醒收尾。
2226
+ del signum