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.
- braid_coding_agent/__init__.py +13 -0
- braid_coding_agent/assembly.py +460 -0
- braid_coding_agent/cancellation.py +25 -0
- braid_coding_agent/checkpoint/__init__.py +106 -0
- braid_coding_agent/checkpoint/git.py +305 -0
- braid_coding_agent/checkpoint/settings.py +26 -0
- braid_coding_agent/checkpoint/store.py +1261 -0
- braid_coding_agent/checkpoint/workspace.py +220 -0
- braid_coding_agent/cli.py +2168 -0
- braid_coding_agent/commands/__init__.py +50 -0
- braid_coding_agent/commands/auth.py +161 -0
- braid_coding_agent/commands/config.py +180 -0
- braid_coding_agent/commands/doctor.py +511 -0
- braid_coding_agent/commands/mcp.py +928 -0
- braid_coding_agent/commands/models.py +95 -0
- braid_coding_agent/commands/setup.py +89 -0
- braid_coding_agent/commands/uninstall.py +277 -0
- braid_coding_agent/commands/upgrade.py +381 -0
- braid_coding_agent/compaction/__init__.py +174 -0
- braid_coding_agent/compaction/prepare.py +430 -0
- braid_coding_agent/compaction/summarize.py +542 -0
- braid_coding_agent/compaction/tokens.py +204 -0
- braid_coding_agent/compaction/tool_results.py +196 -0
- braid_coding_agent/compaction/utils.py +181 -0
- braid_coding_agent/config.py +2776 -0
- braid_coding_agent/config_files.py +191 -0
- braid_coding_agent/credentials.py +252 -0
- braid_coding_agent/discovery.py +415 -0
- braid_coding_agent/extensions/__init__.py +77 -0
- braid_coding_agent/extensions/api.py +480 -0
- braid_coding_agent/extensions/runner.py +553 -0
- braid_coding_agent/formatting/__init__.py +62 -0
- braid_coding_agent/formatting/settings.py +87 -0
- braid_coding_agent/formatting/tool.py +179 -0
- braid_coding_agent/lsp/__init__.py +105 -0
- braid_coding_agent/lsp/client.py +546 -0
- braid_coding_agent/lsp/manager.py +187 -0
- braid_coding_agent/lsp/model.py +316 -0
- braid_coding_agent/lsp/protocol.py +105 -0
- braid_coding_agent/lsp/settings.py +120 -0
- braid_coding_agent/lsp/tool.py +429 -0
- braid_coding_agent/mcp/__init__.py +101 -0
- braid_coding_agent/mcp/cache.py +230 -0
- braid_coding_agent/mcp/catalog.py +108 -0
- braid_coding_agent/mcp/config.py +664 -0
- braid_coding_agent/mcp/config_store.py +142 -0
- braid_coding_agent/mcp/inspector.py +85 -0
- braid_coding_agent/mcp/panel.py +254 -0
- braid_coding_agent/mcp/runtime.py +1060 -0
- braid_coding_agent/mcp/tools.py +579 -0
- braid_coding_agent/mcp/trust.py +150 -0
- braid_coding_agent/mcp/tui_panel.py +444 -0
- braid_coding_agent/messages.py +152 -0
- braid_coding_agent/models_view.py +105 -0
- braid_coding_agent/modes/__init__.py +64 -0
- braid_coding_agent/modes/json_mode.py +480 -0
- braid_coding_agent/modes/lifecycle.py +217 -0
- braid_coding_agent/modes/print_mode.py +257 -0
- braid_coding_agent/modes/repl.py +2687 -0
- braid_coding_agent/modes/repl_commands.py +263 -0
- braid_coding_agent/modes/rpc.py +953 -0
- braid_coding_agent/modes/skill_commands.py +88 -0
- braid_coding_agent/modes/tui.py +2226 -0
- braid_coding_agent/modes/tui_control.py +90 -0
- braid_coding_agent/modes/tui_model.py +1043 -0
- braid_coding_agent/modes/tui_render.py +327 -0
- braid_coding_agent/modes/tui_rich.py +751 -0
- braid_coding_agent/modes/tui_style.py +42 -0
- braid_coding_agent/modes/wire.py +81 -0
- braid_coding_agent/netsafe.py +82 -0
- braid_coding_agent/network/__init__.py +20 -0
- braid_coding_agent/network/cache.py +77 -0
- braid_coding_agent/network/fetch.py +311 -0
- braid_coding_agent/network/html_text.py +160 -0
- braid_coding_agent/network/search.py +347 -0
- braid_coding_agent/network/settings.py +103 -0
- braid_coding_agent/network/urls.py +89 -0
- braid_coding_agent/observability/__init__.py +101 -0
- braid_coding_agent/observability/audit.py +124 -0
- braid_coding_agent/observability/collector.py +314 -0
- braid_coding_agent/observability/exporter.py +74 -0
- braid_coding_agent/observability/logging_setup.py +149 -0
- braid_coding_agent/observability/redaction.py +96 -0
- braid_coding_agent/observability/settings.py +29 -0
- braid_coding_agent/observability/spans.py +239 -0
- braid_coding_agent/permissions/__init__.py +185 -0
- braid_coding_agent/permissions/command.py +586 -0
- braid_coding_agent/permissions/engine.py +522 -0
- braid_coding_agent/permissions/evaluate.py +309 -0
- braid_coding_agent/permissions/matching.py +233 -0
- braid_coding_agent/permissions/model.py +278 -0
- braid_coding_agent/permissions/policy.py +99 -0
- braid_coding_agent/permissions/readonly.py +236 -0
- braid_coding_agent/permissions/store.py +379 -0
- braid_coding_agent/project_init.py +313 -0
- braid_coding_agent/prompt/__init__.py +98 -0
- braid_coding_agent/prompt/context_files.py +253 -0
- braid_coding_agent/prompt/project_context.py +172 -0
- braid_coding_agent/prompt/system_prompt.py +378 -0
- braid_coding_agent/questions.py +71 -0
- braid_coding_agent/render/__init__.py +56 -0
- braid_coding_agent/render/batch.py +66 -0
- braid_coding_agent/render/history.py +143 -0
- braid_coding_agent/render/stream.py +823 -0
- braid_coding_agent/render/theme.py +243 -0
- braid_coding_agent/sandbox/__init__.py +89 -0
- braid_coding_agent/sandbox/backend.py +184 -0
- braid_coding_agent/sandbox/bubblewrap.py +96 -0
- braid_coding_agent/sandbox/operations.py +301 -0
- braid_coding_agent/sandbox/policy.py +221 -0
- braid_coding_agent/sandbox/proxy.py +320 -0
- braid_coding_agent/sandbox/seatbelt.py +222 -0
- braid_coding_agent/sdk/__init__.py +31 -0
- braid_coding_agent/sdk/async_client.py +366 -0
- braid_coding_agent/sdk/client.py +386 -0
- braid_coding_agent/sdk/errors.py +52 -0
- braid_coding_agent/sdk/events.py +162 -0
- braid_coding_agent/sdk/types.py +63 -0
- braid_coding_agent/sdk/wire.py +59 -0
- braid_coding_agent/server/__init__.py +54 -0
- braid_coding_agent/server/errors.py +52 -0
- braid_coding_agent/server/http_server.py +419 -0
- braid_coding_agent/server/hub.py +530 -0
- braid_coding_agent/server/openapi.py +157 -0
- braid_coding_agent/server/registry.py +354 -0
- braid_coding_agent/server/router.py +275 -0
- braid_coding_agent/server/run.py +148 -0
- braid_coding_agent/server/schema.py +194 -0
- braid_coding_agent/server/service.py +975 -0
- braid_coding_agent/session/__init__.py +293 -0
- braid_coding_agent/session/agent_session.py +2706 -0
- braid_coding_agent/session/context_breakdown.py +302 -0
- braid_coding_agent/session/discovery.py +212 -0
- braid_coding_agent/session/entries.py +809 -0
- braid_coding_agent/session/evidence.py +295 -0
- braid_coding_agent/session/lock.py +176 -0
- braid_coding_agent/session/manager.py +1185 -0
- braid_coding_agent/session/plan.py +243 -0
- braid_coding_agent/session/plan_mode.py +423 -0
- braid_coding_agent/session/projection.py +262 -0
- braid_coding_agent/session/rewind.py +257 -0
- braid_coding_agent/session/status.py +240 -0
- braid_coding_agent/settings.py +94 -0
- braid_coding_agent/skills/__init__.py +70 -0
- braid_coding_agent/skills/loader.py +681 -0
- braid_coding_agent/startup/__init__.py +76 -0
- braid_coding_agent/startup/cache.py +72 -0
- braid_coding_agent/startup/diagnostics.py +37 -0
- braid_coding_agent/startup/monitor.py +245 -0
- braid_coding_agent/startup/phases.py +79 -0
- braid_coding_agent/startup/project.py +165 -0
- braid_coding_agent/startup/report.py +560 -0
- braid_coding_agent/startup/scheduler.py +347 -0
- braid_coding_agent/statusline.py +163 -0
- braid_coding_agent/subagents/__init__.py +22 -0
- braid_coding_agent/subagents/contract.py +75 -0
- braid_coding_agent/subagents/definitions.py +583 -0
- braid_coding_agent/subagents/registry.py +277 -0
- braid_coding_agent/subagents/runtime.py +610 -0
- braid_coding_agent/subagents/settings.py +156 -0
- braid_coding_agent/subagents/worktree.py +63 -0
- braid_coding_agent/tools/__init__.py +327 -0
- braid_coding_agent/tools/args.py +87 -0
- braid_coding_agent/tools/bash.py +359 -0
- braid_coding_agent/tools/edit.py +298 -0
- braid_coding_agent/tools/edit_diff.py +344 -0
- braid_coding_agent/tools/find.py +158 -0
- braid_coding_agent/tools/grep.py +305 -0
- braid_coding_agent/tools/ignore.py +198 -0
- braid_coding_agent/tools/ls.py +127 -0
- braid_coding_agent/tools/mutation_queue.py +90 -0
- braid_coding_agent/tools/operations.py +274 -0
- braid_coding_agent/tools/output_accumulator.py +282 -0
- braid_coding_agent/tools/output_store.py +244 -0
- braid_coding_agent/tools/path_utils.py +91 -0
- braid_coding_agent/tools/plan.py +141 -0
- braid_coding_agent/tools/prompt_notes.py +52 -0
- braid_coding_agent/tools/question.py +180 -0
- braid_coding_agent/tools/read.py +223 -0
- braid_coding_agent/tools/submit_plan.py +102 -0
- braid_coding_agent/tools/truncate.py +423 -0
- braid_coding_agent/tools/write.py +100 -0
- braid_coding_agent/untrusted.py +50 -0
- braid_coding_agent/verify/__init__.py +78 -0
- braid_coding_agent/verify/runner.py +260 -0
- braid_coding_agent/verify/settings.py +64 -0
- braid_coding_agent/verify/tool.py +143 -0
- braid_coding_agent-0.1.0.dist-info/METADATA +19 -0
- braid_coding_agent-0.1.0.dist-info/RECORD +192 -0
- braid_coding_agent-0.1.0.dist-info/WHEEL +4 -0
- braid_coding_agent-0.1.0.dist-info/entry_points.txt +3 -0
- braid_coding_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1043 @@
|
|
|
1
|
+
"""S44 全屏 TUI 的视图模型:会话事件归约成一组只读快照。
|
|
2
|
+
|
|
3
|
+
这一层是纯 Python(只依赖 braid_ai/braid_coding_agent 的类型与主题),不碰终端,
|
|
4
|
+
因此可以脱离真实 TTY 直接喂事件测试。它负责四件与界面直接相关的事:
|
|
5
|
+
|
|
6
|
+
1. 历史:用户消息、助手文本、折叠后的思考、工具摘要、通知;
|
|
7
|
+
2. 活动卡片:小思考卡(滚动保留末尾几行)与每个工具一张独立卡片;
|
|
8
|
+
3. 计划面板:``PlanUpdateEvent`` 一到就更新步骤与完成状态;
|
|
9
|
+
4. 状态栏:模型、上下文占用、费用、工具数、计划进度、权限模式、后台任务。
|
|
10
|
+
|
|
11
|
+
事件到动作的映射沿用 :mod:`braid_coding_agent.render.stream` 的语义:思考只渲染
|
|
12
|
+
滚动的小片段,工具生命周期由 ``tool_execution_*`` 播报,工具调用内容块本身不重复打印。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from collections.abc import Sequence
|
|
19
|
+
from dataclasses import dataclass, replace
|
|
20
|
+
from typing import Literal
|
|
21
|
+
|
|
22
|
+
from braid_agent.tools import AgentToolResult
|
|
23
|
+
from braid_agent.types import (
|
|
24
|
+
MessageEndEvent,
|
|
25
|
+
MessageStartEvent,
|
|
26
|
+
MessageUpdateEvent,
|
|
27
|
+
ToolExecutionEndEvent,
|
|
28
|
+
ToolExecutionStartEvent,
|
|
29
|
+
)
|
|
30
|
+
from braid_ai.types import (
|
|
31
|
+
AssistantMessage,
|
|
32
|
+
ContentBlock,
|
|
33
|
+
JsonValue,
|
|
34
|
+
Model,
|
|
35
|
+
TextContent,
|
|
36
|
+
TextDeltaEvent,
|
|
37
|
+
TextEndEvent,
|
|
38
|
+
TextStartEvent,
|
|
39
|
+
ThinkingDeltaEvent,
|
|
40
|
+
ThinkingEndEvent,
|
|
41
|
+
ThinkingStartEvent,
|
|
42
|
+
UserMessage,
|
|
43
|
+
)
|
|
44
|
+
from braid_coding_agent.render.history import history_entries
|
|
45
|
+
from braid_coding_agent.render.theme import LIGHT_THEME, Theme, paint
|
|
46
|
+
from braid_coding_agent.session.agent_session import (
|
|
47
|
+
AgentEndWithRetryEvent,
|
|
48
|
+
AgentSettledEvent,
|
|
49
|
+
AutoRetryEndEvent,
|
|
50
|
+
AutoRetryStartEvent,
|
|
51
|
+
CompactionEndEvent,
|
|
52
|
+
CompactionStartEvent,
|
|
53
|
+
CompletionEvidenceEvent,
|
|
54
|
+
ContextWarningEvent,
|
|
55
|
+
ExtensionErrorEvent,
|
|
56
|
+
ModelChangedEvent,
|
|
57
|
+
PlanModeEvent,
|
|
58
|
+
PlanUpdateEvent,
|
|
59
|
+
QueueUpdateEvent,
|
|
60
|
+
SessionEvent,
|
|
61
|
+
SummarizationRetryAttemptStartEvent,
|
|
62
|
+
SummarizationRetryFinishedEvent,
|
|
63
|
+
SummarizationRetryScheduledEvent,
|
|
64
|
+
ThinkingLevelChangedEvent,
|
|
65
|
+
ToolResultCleanupEvent,
|
|
66
|
+
)
|
|
67
|
+
from braid_coding_agent.session.plan import PlanState
|
|
68
|
+
from braid_coding_agent.session.plan_mode import PlanModeReason, PlanModeState
|
|
69
|
+
from braid_coding_agent.statusline import (
|
|
70
|
+
DEFAULT_STATUS_FIELDS,
|
|
71
|
+
STATUS_FIELD_KEYS,
|
|
72
|
+
StatusLineValues,
|
|
73
|
+
render_status_line,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
__all__ = [
|
|
77
|
+
"TUI_COMMAND_NAMES",
|
|
78
|
+
"ActivityEntry",
|
|
79
|
+
"CompletionItem",
|
|
80
|
+
"PlanView",
|
|
81
|
+
"StatusView",
|
|
82
|
+
"ToolCardView",
|
|
83
|
+
"TranscriptEntry",
|
|
84
|
+
"TuiCommand",
|
|
85
|
+
"TuiKeyMap",
|
|
86
|
+
"TuiModel",
|
|
87
|
+
"TuiSnapshot",
|
|
88
|
+
"command_completions",
|
|
89
|
+
"parse_tui_command",
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
# 思考与工具结果可能夹带终端控制序列(ANSI SGR、光标移动、OSC 等)与 \x00,
|
|
93
|
+
# 直接塞进 FormattedText 会渲染成乱码。这里统一剥掉,只留可见字符与换行。
|
|
94
|
+
_ANSI_RE = re.compile(
|
|
95
|
+
r"\x1b\[[0-?]*[ -/]*[@-~]" # CSI
|
|
96
|
+
r"|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)" # OSC
|
|
97
|
+
r"|\x1b[@-Z\\-_]" # 两字符 ESC 序列
|
|
98
|
+
)
|
|
99
|
+
_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _clean_text(text: str) -> str:
|
|
103
|
+
"""去掉终端控制字符与 ANSI 转义,保留换行和制表符,输出可读纯文本。"""
|
|
104
|
+
return _CONTROL_RE.sub("", _ANSI_RE.sub("", text))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ------------------------------------------------------------------ 配置
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(slots=True, frozen=True)
|
|
111
|
+
class TuiKeyMap:
|
|
112
|
+
"""快捷键。默认值与行式 REPL 的常见绑定一致,允许逐项覆盖。"""
|
|
113
|
+
|
|
114
|
+
cancel: str = "\x03" # Ctrl+C
|
|
115
|
+
exit: str = "\x04" # Ctrl+D
|
|
116
|
+
submit: str = "\r"
|
|
117
|
+
scroll_up: str = "\x1b[A"
|
|
118
|
+
scroll_down: str = "\x1b[B"
|
|
119
|
+
page_up: str = "\x1b[5~"
|
|
120
|
+
page_down: str = "\x1b[6~"
|
|
121
|
+
# Ctrl+E:可打印字母一律留给输入框,避免 "e" 被快捷键吞掉。
|
|
122
|
+
expand_tool: str = "\x05"
|
|
123
|
+
focus_input: str = "\x1b" # Esc
|
|
124
|
+
accept_completion: str = "\t" # Tab
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass(slots=True, frozen=True)
|
|
128
|
+
class TuiCommand:
|
|
129
|
+
"""解析后的 TUI 斜杠命令。"""
|
|
130
|
+
|
|
131
|
+
name: str
|
|
132
|
+
args: str = ""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
#: TUI 认识的命令名。技能名不能占用这些名字,否则会被解析成命令分词。
|
|
136
|
+
TUI_COMMAND_NAMES = (
|
|
137
|
+
"help",
|
|
138
|
+
"model",
|
|
139
|
+
"models",
|
|
140
|
+
"sessions",
|
|
141
|
+
"diff",
|
|
142
|
+
"plan",
|
|
143
|
+
"status",
|
|
144
|
+
"context",
|
|
145
|
+
"mcp",
|
|
146
|
+
"statusline",
|
|
147
|
+
"permission",
|
|
148
|
+
"agents",
|
|
149
|
+
"tasks",
|
|
150
|
+
"background",
|
|
151
|
+
"clear",
|
|
152
|
+
"resume",
|
|
153
|
+
"rewind",
|
|
154
|
+
"compact",
|
|
155
|
+
"skills",
|
|
156
|
+
"skill",
|
|
157
|
+
"monitor",
|
|
158
|
+
"quit",
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def parse_tui_command(text: str) -> TuiCommand | None:
|
|
163
|
+
"""行首 ``/`` 才当命令;命令名大小写不敏感,参数取第一个空格后的原文。"""
|
|
164
|
+
if not text.startswith("/"):
|
|
165
|
+
return None
|
|
166
|
+
body = text[1:].strip()
|
|
167
|
+
if not body:
|
|
168
|
+
return TuiCommand(name="help")
|
|
169
|
+
name, _, args = body.partition(" ")
|
|
170
|
+
name = name.lower()
|
|
171
|
+
if name not in TUI_COMMAND_NAMES:
|
|
172
|
+
return TuiCommand(name=name, args=args.strip())
|
|
173
|
+
return TuiCommand(name=name, args=args.strip())
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
# ------------------------------------------------------------------ 补全
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@dataclass(slots=True, frozen=True)
|
|
180
|
+
class CompletionItem:
|
|
181
|
+
"""一条命令候选项:命令名、用法提示与一句话说明。"""
|
|
182
|
+
|
|
183
|
+
name: str
|
|
184
|
+
usage: str
|
|
185
|
+
summary: str
|
|
186
|
+
|
|
187
|
+
@property
|
|
188
|
+
def insert(self) -> str:
|
|
189
|
+
"""接受补全时写进输入行的文本:只有命令名。
|
|
190
|
+
|
|
191
|
+
``usage`` 里的参数是占位说明,插进输入行之后按回车会被当成真的参数。
|
|
192
|
+
"""
|
|
193
|
+
return f"/{self.name}"
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
#: 补全候选。顺序即弹出列表顺序,与 :data:`TUI_COMMAND_NAMES` 对齐。
|
|
197
|
+
_COMPLETION_ITEMS: tuple[CompletionItem, ...] = (
|
|
198
|
+
CompletionItem("help", "/help", "列出可用命令"),
|
|
199
|
+
CompletionItem("model", "/model [provider/id]", "查看或切换模型"),
|
|
200
|
+
CompletionItem("models", "/models", "查看模型目录与当前选中项"),
|
|
201
|
+
CompletionItem("sessions", "/sessions", "查看并切换会话"),
|
|
202
|
+
CompletionItem("diff", "/diff", "查看本次会话的文件改动"),
|
|
203
|
+
CompletionItem("plan", "/plan [目标|show|approve|off]", "进入规划模式或查看、批准、退出"),
|
|
204
|
+
CompletionItem("status", "/status", "查看会话状态与用量"),
|
|
205
|
+
CompletionItem("context", "/context", "查看上下文占用与压缩阈值"),
|
|
206
|
+
CompletionItem("mcp", "/mcp [子命令]", "打开 MCP 管理面板或查看服务器、工具与历史"),
|
|
207
|
+
CompletionItem("statusline", "/statusline [字段,...|reset]", "查看或修改底部状态栏字段"),
|
|
208
|
+
CompletionItem("permission", "/permission [子命令]", "查看或管理权限模式与规则"),
|
|
209
|
+
CompletionItem("agents", "/agents [list|reload|create <名字>]", "查看、创建、重载子代理定义"),
|
|
210
|
+
CompletionItem("tasks", "/tasks [list|show|cancel|send|clear]", "查看与管理子代理任务"),
|
|
211
|
+
CompletionItem("background", "/background <任务描述>", "把当前会话分离成后台 Agent"),
|
|
212
|
+
CompletionItem("clear", "/clear", "开始一个新会话"),
|
|
213
|
+
CompletionItem("resume", "/resume [序号|会话文件]", "选择要恢复的会话并显示它的记录"),
|
|
214
|
+
CompletionItem(
|
|
215
|
+
"rewind", "/rewind [序号] [--conversation|--files|--all]", "选择一轮历史提问回退过去"
|
|
216
|
+
),
|
|
217
|
+
CompletionItem("compact", "/compact [要求]", "压缩当前上下文"),
|
|
218
|
+
CompletionItem("skills", "/skills [关键词]", "列出可用技能与调用方式"),
|
|
219
|
+
CompletionItem("skill", "/skill <名字>", "只加载技能正文,不立即执行"),
|
|
220
|
+
CompletionItem("monitor", "/monitor [specs|tasks]", "查看启动检查点、指标与后台任务"),
|
|
221
|
+
CompletionItem("quit", "/quit", "退出会话"),
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def command_completions(
|
|
226
|
+
value: str, extra: Sequence[CompletionItem] = ()
|
|
227
|
+
) -> tuple[CompletionItem, ...]:
|
|
228
|
+
"""当前输入行对应的命令候选。
|
|
229
|
+
|
|
230
|
+
只在输入以 ``/`` 开头、且命令名还没带空格参数时给出候选;普通文本与
|
|
231
|
+
已经在写参数的命令行(`"/model faux/..."`)都不弹补全,免得挡住输入。
|
|
232
|
+
命令名大小写不敏感,匹配按补全表顺序。
|
|
233
|
+
|
|
234
|
+
:param extra: 调用方追加的候选(技能)。排在命令之后,前缀匹配规则相同。
|
|
235
|
+
"""
|
|
236
|
+
if not value.startswith("/"):
|
|
237
|
+
return ()
|
|
238
|
+
token = value[1:]
|
|
239
|
+
if " " in token or "\t" in token:
|
|
240
|
+
return ()
|
|
241
|
+
prefix = token.lower()
|
|
242
|
+
return tuple(item for item in (*_COMPLETION_ITEMS, *extra) if item.name.startswith(prefix))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# ------------------------------------------------------------------ 视图值
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
@dataclass(slots=True, frozen=True)
|
|
249
|
+
class ActivityEntry:
|
|
250
|
+
"""思考活动卡片:标题 + 当前可见的若干行。"""
|
|
251
|
+
|
|
252
|
+
title: str
|
|
253
|
+
lines: tuple[str, ...]
|
|
254
|
+
max_lines: int
|
|
255
|
+
#: 全文行数;卡片折叠时只展示末尾几行,标题用它说明还有多少内容。
|
|
256
|
+
total_lines: int = 0
|
|
257
|
+
expanded: bool = False
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@dataclass(slots=True, frozen=True)
|
|
261
|
+
class ToolCardView:
|
|
262
|
+
"""工具卡片:调用 id 是稳定键,并发工具各占一张卡。"""
|
|
263
|
+
|
|
264
|
+
call_id: str
|
|
265
|
+
label: str
|
|
266
|
+
status: Literal["running", "done", "error"]
|
|
267
|
+
duration_ms: int | None = None
|
|
268
|
+
detail: str = ""
|
|
269
|
+
expanded: bool = False
|
|
270
|
+
|
|
271
|
+
@property
|
|
272
|
+
def marker(self) -> str:
|
|
273
|
+
return {"running": "⠋", "done": "✓", "error": "✗"}[self.status]
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
@dataclass(slots=True, frozen=True)
|
|
277
|
+
class PlanView:
|
|
278
|
+
"""计划面板的只读投影。
|
|
279
|
+
|
|
280
|
+
``document`` 是规划模式提交的实施计划正文(Markdown 按行切好),``steps`` 是执行
|
|
281
|
+
阶段的步骤表。两者可以同时存在:批准之后计划正文还在面板上,步骤表由
|
|
282
|
+
``update_plan`` 填。
|
|
283
|
+
"""
|
|
284
|
+
|
|
285
|
+
revision: int
|
|
286
|
+
total: int
|
|
287
|
+
completed: int
|
|
288
|
+
lines: tuple[str, ...]
|
|
289
|
+
document: tuple[str, ...] = ()
|
|
290
|
+
document_revision: int = 0
|
|
291
|
+
mode: str = ""
|
|
292
|
+
|
|
293
|
+
@classmethod
|
|
294
|
+
def from_state(cls, state: PlanState) -> PlanView:
|
|
295
|
+
return cls(
|
|
296
|
+
revision=state.revision,
|
|
297
|
+
total=state.total,
|
|
298
|
+
completed=state.completed,
|
|
299
|
+
lines=tuple(state.lines()),
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
@dataclass(slots=True, frozen=True)
|
|
304
|
+
class TranscriptEntry:
|
|
305
|
+
"""按 Claude Code 风格逐条呈现的会话记录。
|
|
306
|
+
|
|
307
|
+
``kind`` 决定前缀与渲染方式;``text`` 永远是干净的可读文本,不含 ANSI 转义。
|
|
308
|
+
``answer`` 的文本是整段 Markdown 源(可以含换行),交给渲染层做富文本;
|
|
309
|
+
其余种类按行存储,便于逐行核对。
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
kind: Literal["user", "thinking", "tool", "result", "answer", "notice", "plain", "diff"]
|
|
313
|
+
text: str
|
|
314
|
+
detail: str = ""
|
|
315
|
+
#: 结果与通知的角色:``ok`` / ``warn`` / ``err``,空串表示普通文本。
|
|
316
|
+
level: str = ""
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@dataclass(slots=True, frozen=True)
|
|
320
|
+
class StatusView:
|
|
321
|
+
"""状态栏的结构化字段。
|
|
322
|
+
|
|
323
|
+
渲染层按终端宽度决定保留哪些字段,``summary`` 保留拼接后的整串文本,
|
|
324
|
+
供测试与不支持富渲染的出口使用。
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
model: str
|
|
328
|
+
context_percent: float
|
|
329
|
+
cost: float
|
|
330
|
+
tool_count: int
|
|
331
|
+
permission: str
|
|
332
|
+
plan: str = ""
|
|
333
|
+
background: int = 0
|
|
334
|
+
used_tokens: int | None = None
|
|
335
|
+
context_remaining: int | None = None
|
|
336
|
+
context_window: int | None = None
|
|
337
|
+
cache_hit: float | None = None
|
|
338
|
+
fields: tuple[str, ...] = DEFAULT_STATUS_FIELDS
|
|
339
|
+
|
|
340
|
+
@property
|
|
341
|
+
def summary(self) -> str:
|
|
342
|
+
values = StatusLineValues(
|
|
343
|
+
model=self.model,
|
|
344
|
+
context_percent=self.context_percent,
|
|
345
|
+
cost=self.cost,
|
|
346
|
+
tool_count=self.tool_count,
|
|
347
|
+
permission=self.permission,
|
|
348
|
+
plan=self.plan,
|
|
349
|
+
background=self.background,
|
|
350
|
+
used_tokens=self.used_tokens,
|
|
351
|
+
context_remaining=self.context_remaining,
|
|
352
|
+
context_window=self.context_window,
|
|
353
|
+
cache_hit=self.cache_hit,
|
|
354
|
+
)
|
|
355
|
+
return render_status_line(values, self.fields, context_prefix="上下文 ")
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
@dataclass(slots=True, frozen=True)
|
|
359
|
+
class TuiSnapshot:
|
|
360
|
+
"""一次渲染所需的全部只读状态。"""
|
|
361
|
+
|
|
362
|
+
history_lines: tuple[str, ...] = ()
|
|
363
|
+
thinking: ActivityEntry | None = None
|
|
364
|
+
thinking_max_lines: int = 4
|
|
365
|
+
tool_cards: tuple[ToolCardView, ...] = ()
|
|
366
|
+
plan: PlanView | None = None
|
|
367
|
+
status: str = ""
|
|
368
|
+
#: 尚未提交的流式文本。TextEndEvent 到达时转入 history_lines 并清空。
|
|
369
|
+
streaming_answer: str = ""
|
|
370
|
+
#: 单一可滚动的会话记录(用户、思考、工具、结果、回答、通知按时间顺序)。
|
|
371
|
+
transcript: tuple[TranscriptEntry, ...] = ()
|
|
372
|
+
#: 状态版本号:任何字段变化都会递增,渲染层用它判断缓存是否失效。
|
|
373
|
+
revision: int = 0
|
|
374
|
+
#: 状态栏的结构化投影;``status`` 是它的纯文本形式。
|
|
375
|
+
status_view: StatusView | None = None
|
|
376
|
+
#: 思考卡片是否展开全文。折叠时只显示末尾几行。
|
|
377
|
+
thinking_expanded: bool = False
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
@dataclass(slots=True)
|
|
381
|
+
class _ToolState:
|
|
382
|
+
call_id: str
|
|
383
|
+
name: str
|
|
384
|
+
args_text: str
|
|
385
|
+
status: Literal["running", "done", "error"] = "running"
|
|
386
|
+
duration_ms: int | None = None
|
|
387
|
+
size: str = ""
|
|
388
|
+
output_path: str | None = None
|
|
389
|
+
expanded: bool = False
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# ------------------------------------------------------------------ 视图模型
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
class TuiModel:
|
|
396
|
+
"""把会话事件归约为 :class:`TuiSnapshot`。所有 ``on_*`` 都是幂等语义。"""
|
|
397
|
+
|
|
398
|
+
THINKING_TAIL_LINES = 4
|
|
399
|
+
HISTORY_MAX_LINES = 400
|
|
400
|
+
DIFF_MAX_LINES = 200
|
|
401
|
+
|
|
402
|
+
def __init__(
|
|
403
|
+
self,
|
|
404
|
+
*,
|
|
405
|
+
model: Model,
|
|
406
|
+
theme: Theme = LIGHT_THEME,
|
|
407
|
+
color: bool = False,
|
|
408
|
+
permission_mode: str = "full",
|
|
409
|
+
statusline_fields: tuple[str, ...] = DEFAULT_STATUS_FIELDS,
|
|
410
|
+
) -> None:
|
|
411
|
+
self._model = model
|
|
412
|
+
self._theme = theme
|
|
413
|
+
self._color = color
|
|
414
|
+
self._permission_mode = permission_mode
|
|
415
|
+
self._statusline_fields = tuple(statusline_fields)
|
|
416
|
+
self._history: list[str] = []
|
|
417
|
+
self._transcript: list[TranscriptEntry] = []
|
|
418
|
+
self._thinking_text: list[str] = []
|
|
419
|
+
self._thinking_buffer: list[str] = []
|
|
420
|
+
self._thinking_active = False
|
|
421
|
+
#: transcript 里那条思考卡片的位置;卡片随增量增长,不产生碎片条目。
|
|
422
|
+
self._thinking_entry: int | None = None
|
|
423
|
+
self._thinking_expanded = False
|
|
424
|
+
self._tools: dict[str, _ToolState] = {}
|
|
425
|
+
self._tool_order: list[str] = []
|
|
426
|
+
self._plan: PlanView | None = None
|
|
427
|
+
#: 规划模式状态。计划正文放在 ``_plan_mode.plan``,面板把它与步骤表一起画。
|
|
428
|
+
self._plan_mode = PlanModeState()
|
|
429
|
+
self._context_percent = 0.0
|
|
430
|
+
self._cost = 0.0
|
|
431
|
+
self._tool_count = 0
|
|
432
|
+
self._background = 0
|
|
433
|
+
self._used_tokens: int | None = None
|
|
434
|
+
self._context_remaining: int | None = None
|
|
435
|
+
self._context_window: int | None = None
|
|
436
|
+
self._cache_hit: float | None = None
|
|
437
|
+
self._answer: list[str] = []
|
|
438
|
+
self._answer_open = False
|
|
439
|
+
self._answer_entry_open = False
|
|
440
|
+
self._revision = 0
|
|
441
|
+
|
|
442
|
+
# ------------------------------------------------------------ 工具方法
|
|
443
|
+
|
|
444
|
+
def _bump(self) -> None:
|
|
445
|
+
"""标记状态已变化。渲染层以它作为缓存键,重复递增只会多失效一次。"""
|
|
446
|
+
self._revision += 1
|
|
447
|
+
|
|
448
|
+
def _paint(self, text: str, role: str, *, bold: bool = False) -> str:
|
|
449
|
+
return paint(text, role, self._theme, bold=bold) if self._color else text
|
|
450
|
+
|
|
451
|
+
def _history_append(self, text: str) -> None:
|
|
452
|
+
for line in text.splitlines() or [""]:
|
|
453
|
+
self._history.append(line)
|
|
454
|
+
if len(self._history) > self.HISTORY_MAX_LINES:
|
|
455
|
+
del self._history[: len(self._history) - self.HISTORY_MAX_LINES]
|
|
456
|
+
|
|
457
|
+
def _transcript_append(
|
|
458
|
+
self,
|
|
459
|
+
kind: Literal["user", "thinking", "tool", "result", "answer", "notice", "plain", "diff"],
|
|
460
|
+
text: str,
|
|
461
|
+
detail: str = "",
|
|
462
|
+
level: str = "",
|
|
463
|
+
) -> None:
|
|
464
|
+
"""追加一条会话记录;text 先清洗控制字符,天然防乱码。"""
|
|
465
|
+
for line in _clean_text(text).splitlines() or [""]:
|
|
466
|
+
self._transcript.append(
|
|
467
|
+
TranscriptEntry(kind=kind, text=line, detail=detail, level=level)
|
|
468
|
+
)
|
|
469
|
+
self._trim_transcript()
|
|
470
|
+
|
|
471
|
+
def _trim_transcript(self) -> None:
|
|
472
|
+
overflow = len(self._transcript) - self.HISTORY_MAX_LINES
|
|
473
|
+
if overflow <= 0:
|
|
474
|
+
return
|
|
475
|
+
del self._transcript[:overflow]
|
|
476
|
+
if self._thinking_entry is not None:
|
|
477
|
+
self._thinking_entry -= overflow
|
|
478
|
+
if self._thinking_entry < 0:
|
|
479
|
+
self._thinking_entry = None
|
|
480
|
+
|
|
481
|
+
def _transcript_whole(self, kind: Literal["thinking", "answer"], text: str) -> None:
|
|
482
|
+
"""整段追加一条记录,不按换行拆分。
|
|
483
|
+
|
|
484
|
+
思考与正文都以整段原文存放:拆行会让 Markdown 段落各自成块,折叠也失去意义。
|
|
485
|
+
"""
|
|
486
|
+
self._transcript.append(TranscriptEntry(kind, _clean_text(text)))
|
|
487
|
+
self._trim_transcript()
|
|
488
|
+
|
|
489
|
+
# ------------------------------------------------------------ 语义入口
|
|
490
|
+
|
|
491
|
+
def on_user(self, text: str) -> None:
|
|
492
|
+
first, *rest = (text.splitlines() or [""])[:50]
|
|
493
|
+
self._history_append(self._paint("▌ 用户 " + first, "user"))
|
|
494
|
+
for line in rest:
|
|
495
|
+
self._history_append(self._paint(" " + line, "user"))
|
|
496
|
+
self._transcript_append("user", text)
|
|
497
|
+
self._bump()
|
|
498
|
+
|
|
499
|
+
def on_thinking(self, delta: str) -> None:
|
|
500
|
+
"""追加思考增量。
|
|
501
|
+
|
|
502
|
+
整段思考只占一条记录,卡片随增量增长;卡片折叠时由渲染层取末尾几行,
|
|
503
|
+
展开时显示全文。这样既不会产生成百上千条碎片记录,也不会把长思考
|
|
504
|
+
全部挤进活动区。
|
|
505
|
+
"""
|
|
506
|
+
self._thinking_active = True
|
|
507
|
+
clean = _clean_text(delta)
|
|
508
|
+
if clean:
|
|
509
|
+
self._thinking_text.append(clean)
|
|
510
|
+
text = "".join(self._thinking_text)
|
|
511
|
+
if self._thinking_entry is not None and self._thinking_entry < len(self._transcript):
|
|
512
|
+
self._transcript[self._thinking_entry] = TranscriptEntry("thinking", text)
|
|
513
|
+
else:
|
|
514
|
+
self._transcript.append(TranscriptEntry("thinking", text))
|
|
515
|
+
self._thinking_entry = len(self._transcript) - 1
|
|
516
|
+
self._trim_transcript()
|
|
517
|
+
for line in clean.splitlines():
|
|
518
|
+
if line:
|
|
519
|
+
self._thinking_buffer.append(line)
|
|
520
|
+
if len(self._thinking_buffer) > self.THINKING_TAIL_LINES * 2:
|
|
521
|
+
del self._thinking_buffer[: len(self._thinking_buffer) - self.THINKING_TAIL_LINES]
|
|
522
|
+
self._bump()
|
|
523
|
+
|
|
524
|
+
def on_thinking_end(self) -> None:
|
|
525
|
+
chars = sum(len(chunk) for chunk in self._thinking_text)
|
|
526
|
+
if chars:
|
|
527
|
+
self._history_append(self._paint(f"◌ 思考 {chars} 字(已折叠)", "muted"))
|
|
528
|
+
# 卡片内容已固化在会话记录里,活动标记与尾部缓冲到此清除。
|
|
529
|
+
self._thinking_text = []
|
|
530
|
+
self._thinking_buffer = []
|
|
531
|
+
self._thinking_active = False
|
|
532
|
+
self._thinking_entry = None
|
|
533
|
+
self._bump()
|
|
534
|
+
|
|
535
|
+
def toggle_thinking(self) -> None:
|
|
536
|
+
"""展开或收起思考卡片。展开后全文进入记录,由记录区滚动查看。"""
|
|
537
|
+
self._thinking_expanded = not self._thinking_expanded
|
|
538
|
+
self._bump()
|
|
539
|
+
|
|
540
|
+
def on_text(self, delta: str) -> None:
|
|
541
|
+
self._answer_open = True
|
|
542
|
+
self._answer.append(delta)
|
|
543
|
+
# 流式回答即时可见:并入会话记录末条 answer,避免每片都成新行。
|
|
544
|
+
# answer 条目保存整段 Markdown 源,换行不能被拆成独立条目。
|
|
545
|
+
clean = _clean_text(delta)
|
|
546
|
+
if not clean:
|
|
547
|
+
self._bump()
|
|
548
|
+
return
|
|
549
|
+
if self._answer_entry_open and self._transcript and self._transcript[-1].kind == "answer":
|
|
550
|
+
last = self._transcript[-1]
|
|
551
|
+
self._transcript[-1] = TranscriptEntry("answer", last.text + clean, last.detail)
|
|
552
|
+
else:
|
|
553
|
+
self._transcript.append(TranscriptEntry("answer", clean))
|
|
554
|
+
self._answer_entry_open = True
|
|
555
|
+
self._trim_transcript()
|
|
556
|
+
self._bump()
|
|
557
|
+
|
|
558
|
+
def on_text_end(self) -> None:
|
|
559
|
+
if not self._answer:
|
|
560
|
+
return
|
|
561
|
+
text = "".join(self._answer)
|
|
562
|
+
# 权威全文到达时用校正后的内容覆盖会话记录里的同一条 answer。
|
|
563
|
+
if self._answer_entry_open and self._transcript and self._transcript[-1].kind == "answer":
|
|
564
|
+
self._transcript[-1] = TranscriptEntry("answer", _clean_text(text), "")
|
|
565
|
+
if text.strip():
|
|
566
|
+
self._history_append(self._paint(text.rstrip(), "fg"))
|
|
567
|
+
self._answer = []
|
|
568
|
+
self._answer_open = False
|
|
569
|
+
self._answer_entry_open = False
|
|
570
|
+
self._bump()
|
|
571
|
+
|
|
572
|
+
def on_tool_start(self, call_id: str, name: str, args: JsonValue) -> None:
|
|
573
|
+
args_text = _summarize_args(args)
|
|
574
|
+
previous = self._tools.get(call_id)
|
|
575
|
+
expanded = previous.expanded if previous is not None else False
|
|
576
|
+
self._tools[call_id] = _ToolState(
|
|
577
|
+
call_id=call_id, name=name, args_text=args_text, expanded=expanded
|
|
578
|
+
)
|
|
579
|
+
if call_id not in self._tool_order:
|
|
580
|
+
self._tool_order.append(call_id)
|
|
581
|
+
self._transcript_append("tool", f"{name} {args_text}".strip(), detail=call_id)
|
|
582
|
+
self._bump()
|
|
583
|
+
|
|
584
|
+
def on_tool_end(
|
|
585
|
+
self,
|
|
586
|
+
call_id: str,
|
|
587
|
+
*,
|
|
588
|
+
duration_ms: int | None = None,
|
|
589
|
+
size: str = "",
|
|
590
|
+
output_path: str | None = None,
|
|
591
|
+
is_error: bool = False,
|
|
592
|
+
) -> None:
|
|
593
|
+
state = self._tools.get(call_id)
|
|
594
|
+
if state is None:
|
|
595
|
+
self.on_notice(f"工具 {call_id} 结束事件缺少开始事件,结果已忽略", role="warn")
|
|
596
|
+
return
|
|
597
|
+
state.status = "error" if is_error else "done"
|
|
598
|
+
state.duration_ms = duration_ms
|
|
599
|
+
state.size = size
|
|
600
|
+
state.output_path = output_path
|
|
601
|
+
metrics = [
|
|
602
|
+
part for part in (f"{duration_ms}ms" if duration_ms is not None else "", size) if part
|
|
603
|
+
]
|
|
604
|
+
label = f"{state.name} {state.args_text}".strip()
|
|
605
|
+
mark = "✗" if is_error else "✓"
|
|
606
|
+
line = f"{mark} {label}" + (f" · {' · '.join(metrics)}" if metrics else "")
|
|
607
|
+
self._history_append(self._paint(line, "err" if is_error else "ok"))
|
|
608
|
+
# Claude Code 风格:调用行保留 ●,结果用 ⎿ 缩进展示摘要。
|
|
609
|
+
summary = " · ".join(filter(None, (*metrics, output_path or "", label)))
|
|
610
|
+
self._transcript_append(
|
|
611
|
+
"result", summary or "完成", detail=call_id, level="err" if is_error else "ok"
|
|
612
|
+
)
|
|
613
|
+
self._bump()
|
|
614
|
+
|
|
615
|
+
def toggle_tool(self, call_id: str) -> None:
|
|
616
|
+
state = self._tools.get(call_id)
|
|
617
|
+
if state is not None:
|
|
618
|
+
state.expanded = not state.expanded
|
|
619
|
+
self._bump()
|
|
620
|
+
|
|
621
|
+
def on_plan(self, state: PlanState) -> None:
|
|
622
|
+
self._plan = None if state.is_empty else PlanView.from_state(state)
|
|
623
|
+
self._bump()
|
|
624
|
+
|
|
625
|
+
def on_plan_mode(self, state: PlanModeState, reason: PlanModeReason) -> None:
|
|
626
|
+
"""规划模式变化:更新面板内容,并把状态变化写进记录。
|
|
627
|
+
|
|
628
|
+
计划正文进面板而不是记录:面板可以滚动、常驻,用户审批时它一直在屏幕上。
|
|
629
|
+
状态变化(进入 / 批准 / 退出)写进记录,因为它们要留在时间线上。
|
|
630
|
+
"""
|
|
631
|
+
self._plan_mode = state
|
|
632
|
+
labels = {
|
|
633
|
+
"entered": "已进入规划模式(只读)",
|
|
634
|
+
"submitted": f"实施计划(第 {state.revision} 版)已提交,等待批准",
|
|
635
|
+
"approved": f"已批准第 {state.revision} 版计划,规划模式退出",
|
|
636
|
+
"revised": "计划待修改,保持规划模式",
|
|
637
|
+
"left": "已退出规划模式",
|
|
638
|
+
}
|
|
639
|
+
text = labels.get(reason)
|
|
640
|
+
if text is not None:
|
|
641
|
+
role = "ok" if reason == "approved" else "warn" if reason == "revised" else "notice"
|
|
642
|
+
self._transcript.append(TranscriptEntry("notice", text, role))
|
|
643
|
+
self._trim_transcript()
|
|
644
|
+
self._bump()
|
|
645
|
+
|
|
646
|
+
def reset_plan_mode(self, state: PlanModeState) -> None:
|
|
647
|
+
"""换会话时静默接管新会话的规划模式状态:不往记录里补一条历史。"""
|
|
648
|
+
self._plan_mode = state
|
|
649
|
+
self._bump()
|
|
650
|
+
|
|
651
|
+
def on_diff(self, patch: str, summary: str = "") -> None:
|
|
652
|
+
"""把会话改动放进可滚动记录,由渲染层做 diff 语法高亮。"""
|
|
653
|
+
text = _clean_text(patch)
|
|
654
|
+
lines = text.splitlines()
|
|
655
|
+
if len(lines) > self.DIFF_MAX_LINES:
|
|
656
|
+
lines = lines[: self.DIFF_MAX_LINES]
|
|
657
|
+
lines.append(f"… 差异超过 {self.DIFF_MAX_LINES} 行,已截断")
|
|
658
|
+
self._transcript.append(TranscriptEntry("diff", "\n".join(lines), summary))
|
|
659
|
+
self._trim_transcript()
|
|
660
|
+
self._bump()
|
|
661
|
+
|
|
662
|
+
def on_model_changed(self, model: Model) -> None:
|
|
663
|
+
self._model = model
|
|
664
|
+
self._bump()
|
|
665
|
+
|
|
666
|
+
def on_context(
|
|
667
|
+
self,
|
|
668
|
+
*,
|
|
669
|
+
percent: float,
|
|
670
|
+
cost: float,
|
|
671
|
+
tool_count: int,
|
|
672
|
+
background: int = 0,
|
|
673
|
+
permission_mode: str | None = None,
|
|
674
|
+
used_tokens: int | None = None,
|
|
675
|
+
context_remaining: int | None = None,
|
|
676
|
+
context_window: int | None = None,
|
|
677
|
+
cache_hit: float | None = None,
|
|
678
|
+
) -> None:
|
|
679
|
+
self._context_percent = percent
|
|
680
|
+
self._cost = cost
|
|
681
|
+
self._tool_count = tool_count
|
|
682
|
+
self._background = background
|
|
683
|
+
self._used_tokens = used_tokens
|
|
684
|
+
self._context_remaining = context_remaining
|
|
685
|
+
self._context_window = context_window
|
|
686
|
+
self._cache_hit = cache_hit
|
|
687
|
+
if permission_mode is not None:
|
|
688
|
+
# 权限模式会在运行中被 /plan 与 /permission mode 改掉,状态栏必须跟着变。
|
|
689
|
+
self._permission_mode = permission_mode
|
|
690
|
+
self._bump()
|
|
691
|
+
|
|
692
|
+
def set_statusline_fields(self, fields: tuple[str, ...]) -> None:
|
|
693
|
+
"""换一组状态栏字段。未知字段直接报错,不把错误留到渲染阶段。"""
|
|
694
|
+
unknown = [name for name in fields if name not in STATUS_FIELD_KEYS]
|
|
695
|
+
if unknown:
|
|
696
|
+
raise ValueError(f"未知的状态栏字段:{'、'.join(unknown)}")
|
|
697
|
+
if not fields:
|
|
698
|
+
raise ValueError("状态栏至少保留一个字段")
|
|
699
|
+
self._statusline_fields = tuple(fields)
|
|
700
|
+
self._bump()
|
|
701
|
+
|
|
702
|
+
@property
|
|
703
|
+
def statusline_fields(self) -> tuple[str, ...]:
|
|
704
|
+
"""当前状态栏字段,按显示顺序。"""
|
|
705
|
+
return self._statusline_fields
|
|
706
|
+
|
|
707
|
+
def on_notice(self, text: str, *, role: str = "muted") -> None:
|
|
708
|
+
self._history_append(self._paint(f"· {text}", role))
|
|
709
|
+
self._transcript_append("notice", text, level=role)
|
|
710
|
+
self._bump()
|
|
711
|
+
|
|
712
|
+
def on_markdown(self, text: str) -> None:
|
|
713
|
+
"""把一段 Markdown(帮助、状态表)放进会话记录,由渲染层做富文本。"""
|
|
714
|
+
self._transcript.append(TranscriptEntry("answer", _clean_text(text)))
|
|
715
|
+
self._trim_transcript()
|
|
716
|
+
self._bump()
|
|
717
|
+
|
|
718
|
+
def on_plain(self, text: str) -> None:
|
|
719
|
+
"""把一段保留换行的纯文本放进会话记录。
|
|
720
|
+
|
|
721
|
+
表格、启动报告与缩进文本走这条通道,Markdown 渲染器不会把单换行合并成
|
|
722
|
+
空格,列宽对齐也不会被重新解释。
|
|
723
|
+
"""
|
|
724
|
+
self._transcript.append(TranscriptEntry("plain", _clean_text(text)))
|
|
725
|
+
self._trim_transcript()
|
|
726
|
+
self._bump()
|
|
727
|
+
|
|
728
|
+
def on_clear_history(self) -> None:
|
|
729
|
+
self._history = []
|
|
730
|
+
self._transcript = []
|
|
731
|
+
self._thinking_text = []
|
|
732
|
+
self._thinking_buffer = []
|
|
733
|
+
self._thinking_active = False
|
|
734
|
+
self._thinking_entry = None
|
|
735
|
+
self._thinking_expanded = False
|
|
736
|
+
self._tools = {}
|
|
737
|
+
self._tool_order = []
|
|
738
|
+
self._plan = None
|
|
739
|
+
self._answer = []
|
|
740
|
+
self._answer_open = False
|
|
741
|
+
self._answer_entry_open = False
|
|
742
|
+
self._bump()
|
|
743
|
+
|
|
744
|
+
def replay(self, messages: Sequence[object]) -> None:
|
|
745
|
+
"""把一段历史转录重画到记录区(切换会话、回退之后)。
|
|
746
|
+
|
|
747
|
+
条目由 :func:`~braid_coding_agent.render.history.history_entries` 统一切分,
|
|
748
|
+
因此恢复出来的记录与当时那一轮的形状一致:用户发言、思考卡、工具调用行、
|
|
749
|
+
工具结果行、正文都在。思考与正文保持整段原文(Markdown 与折叠由渲染层处理),
|
|
750
|
+
其余条目按行拆分。
|
|
751
|
+
"""
|
|
752
|
+
self.on_clear_history()
|
|
753
|
+
for entry in history_entries(messages):
|
|
754
|
+
if entry.kind == "user":
|
|
755
|
+
self.on_user(entry.text)
|
|
756
|
+
elif entry.kind == "thinking":
|
|
757
|
+
self._transcript_whole("thinking", entry.text)
|
|
758
|
+
elif entry.kind == "answer":
|
|
759
|
+
self._transcript_whole("answer", entry.text)
|
|
760
|
+
else:
|
|
761
|
+
self._transcript_append(entry.kind, entry.text, level=entry.level)
|
|
762
|
+
self._bump()
|
|
763
|
+
|
|
764
|
+
# ------------------------------------------------------------ 事件入口
|
|
765
|
+
|
|
766
|
+
def handle_event(self, event: SessionEvent) -> None:
|
|
767
|
+
"""作为 ``session.subscribe`` 的监听器:把真实事件翻成语义入口。"""
|
|
768
|
+
self._bump()
|
|
769
|
+
if isinstance(event, MessageStartEvent):
|
|
770
|
+
if isinstance(event.message, AssistantMessage):
|
|
771
|
+
# 新回合开始:上一回合未提交的内容已在 message_end 兜底提交。
|
|
772
|
+
self._answer = []
|
|
773
|
+
self._answer_open = True
|
|
774
|
+
self._answer_entry_open = False
|
|
775
|
+
self._thinking_text = []
|
|
776
|
+
self._thinking_buffer = []
|
|
777
|
+
self._thinking_active = False
|
|
778
|
+
# 新回合的思考是一张新卡片,不与上一条记录合并。
|
|
779
|
+
self._thinking_entry = None
|
|
780
|
+
elif isinstance(event.message, UserMessage):
|
|
781
|
+
self.on_user(_message_text(event.message))
|
|
782
|
+
return
|
|
783
|
+
if isinstance(event, MessageUpdateEvent):
|
|
784
|
+
inner = event.assistant_message_event
|
|
785
|
+
if isinstance(inner, ThinkingStartEvent):
|
|
786
|
+
self._thinking_active = True
|
|
787
|
+
elif isinstance(inner, ThinkingDeltaEvent):
|
|
788
|
+
self.on_thinking(inner.delta)
|
|
789
|
+
elif isinstance(inner, ThinkingEndEvent):
|
|
790
|
+
self.on_thinking_end()
|
|
791
|
+
elif isinstance(inner, TextStartEvent):
|
|
792
|
+
# 只有上一块已经提交、没有未提交内容时才清空;否则保留累积文本。
|
|
793
|
+
if not self._answer:
|
|
794
|
+
self._answer = []
|
|
795
|
+
self._answer_open = True
|
|
796
|
+
elif isinstance(inner, TextDeltaEvent):
|
|
797
|
+
self.on_text(inner.delta)
|
|
798
|
+
elif isinstance(inner, TextEndEvent):
|
|
799
|
+
# content 是权威全文:用它校正增量累积的偏差后再提交。
|
|
800
|
+
if inner.content:
|
|
801
|
+
self._answer = [inner.content]
|
|
802
|
+
self.on_text_end()
|
|
803
|
+
return
|
|
804
|
+
if isinstance(event, MessageEndEvent):
|
|
805
|
+
if isinstance(event.message, AssistantMessage) and self._answer_open:
|
|
806
|
+
self.on_text_end()
|
|
807
|
+
return
|
|
808
|
+
if isinstance(event, ToolExecutionStartEvent):
|
|
809
|
+
self.on_tool_start(event.tool_call_id, event.tool_name, event.args)
|
|
810
|
+
return
|
|
811
|
+
if isinstance(event, ToolExecutionEndEvent):
|
|
812
|
+
size = _result_size(event.result)
|
|
813
|
+
path = _output_path(event.result)
|
|
814
|
+
self.on_tool_end(
|
|
815
|
+
event.tool_call_id,
|
|
816
|
+
duration_ms=event.duration_ms,
|
|
817
|
+
size=size,
|
|
818
|
+
output_path=path,
|
|
819
|
+
is_error=event.is_error,
|
|
820
|
+
)
|
|
821
|
+
return
|
|
822
|
+
if isinstance(event, PlanUpdateEvent):
|
|
823
|
+
self.on_plan(event.state)
|
|
824
|
+
return
|
|
825
|
+
if isinstance(event, PlanModeEvent):
|
|
826
|
+
self.on_plan_mode(event.state, event.reason)
|
|
827
|
+
return
|
|
828
|
+
if isinstance(event, ModelChangedEvent):
|
|
829
|
+
self.on_model_changed(event.model)
|
|
830
|
+
self.on_notice(f"模型切换为 {event.model.provider}/{event.model.id}")
|
|
831
|
+
return
|
|
832
|
+
if isinstance(event, AgentSettledEvent):
|
|
833
|
+
self._thinking_active = False
|
|
834
|
+
self._thinking_buffer = []
|
|
835
|
+
return
|
|
836
|
+
if isinstance(event, ThinkingLevelChangedEvent):
|
|
837
|
+
self.on_notice(f"思考级别切换为 {event.level}")
|
|
838
|
+
return
|
|
839
|
+
if isinstance(event, SummarizationRetryScheduledEvent):
|
|
840
|
+
self.on_notice(
|
|
841
|
+
f"摘要重试 {event.attempt}/{event.max_attempts}({event.delay_ms}ms 后)",
|
|
842
|
+
role="warn",
|
|
843
|
+
)
|
|
844
|
+
return
|
|
845
|
+
if isinstance(event, SummarizationRetryAttemptStartEvent):
|
|
846
|
+
self.on_notice("摘要重试请求已发出", role="warn")
|
|
847
|
+
return
|
|
848
|
+
if isinstance(event, SummarizationRetryFinishedEvent):
|
|
849
|
+
self.on_notice("摘要重试已结束")
|
|
850
|
+
return
|
|
851
|
+
if isinstance(event, AgentEndWithRetryEvent) and event.will_retry:
|
|
852
|
+
self.on_notice("请求失败,准备自动重试…", role="warn")
|
|
853
|
+
return
|
|
854
|
+
if isinstance(event, AutoRetryStartEvent):
|
|
855
|
+
self.on_notice(
|
|
856
|
+
f"自动重试 {event.attempt}/{event.max_attempts}({event.delay_ms}ms 后)",
|
|
857
|
+
role="warn",
|
|
858
|
+
)
|
|
859
|
+
return
|
|
860
|
+
if isinstance(event, AutoRetryEndEvent):
|
|
861
|
+
self.on_notice(
|
|
862
|
+
f"重试成功(第 {event.attempt} 次)" if event.success else "重试放弃",
|
|
863
|
+
role="ok" if event.success else "err",
|
|
864
|
+
)
|
|
865
|
+
return
|
|
866
|
+
if isinstance(event, CompactionStartEvent):
|
|
867
|
+
self.on_notice("压缩中…", role="warn")
|
|
868
|
+
return
|
|
869
|
+
if isinstance(event, CompactionEndEvent):
|
|
870
|
+
if event.aborted:
|
|
871
|
+
self.on_notice("压缩已取消", role="err")
|
|
872
|
+
elif event.error_message:
|
|
873
|
+
self.on_notice(event.error_message, role="err")
|
|
874
|
+
else:
|
|
875
|
+
self.on_notice("压缩完成")
|
|
876
|
+
return
|
|
877
|
+
if isinstance(event, CompletionEvidenceEvent):
|
|
878
|
+
if event.unverified:
|
|
879
|
+
self.on_notice("改了文件但没有运行验证命令", role="warn")
|
|
880
|
+
return
|
|
881
|
+
if isinstance(event, ContextWarningEvent):
|
|
882
|
+
self.on_notice(
|
|
883
|
+
f"上下文接近上限:已用 {event.tokens}/{event.context_window} tokens",
|
|
884
|
+
role="warn",
|
|
885
|
+
)
|
|
886
|
+
return
|
|
887
|
+
if isinstance(event, ToolResultCleanupEvent):
|
|
888
|
+
saved = event.chars_before - event.chars_after
|
|
889
|
+
self.on_notice(f"已清理 {event.cleared} 条旧工具结果(省下 {saved} 字符)", role="warn")
|
|
890
|
+
return
|
|
891
|
+
if isinstance(event, ExtensionErrorEvent):
|
|
892
|
+
self.on_notice(f"扩展 {event.extension} 失败:{event.error}", role="err")
|
|
893
|
+
return
|
|
894
|
+
if isinstance(event, QueueUpdateEvent):
|
|
895
|
+
for text in (*event.steering, *event.follow_up):
|
|
896
|
+
self.on_notice(f"已排队:{text[:60]}")
|
|
897
|
+
return
|
|
898
|
+
|
|
899
|
+
# ---------------------------------------------------------------- 快照
|
|
900
|
+
|
|
901
|
+
def snapshot(self) -> TuiSnapshot:
|
|
902
|
+
thinking: ActivityEntry | None = None
|
|
903
|
+
if self._thinking_active and self._thinking_buffer:
|
|
904
|
+
tail = self._thinking_buffer[-self.THINKING_TAIL_LINES :]
|
|
905
|
+
full = "".join(self._thinking_text)
|
|
906
|
+
thinking = ActivityEntry(
|
|
907
|
+
title="✻ 思考",
|
|
908
|
+
# 纯文本,不上 ANSI:样式交给渲染层,避免乱码。
|
|
909
|
+
lines=tuple(_clean_text(line) for line in tail),
|
|
910
|
+
max_lines=self.THINKING_TAIL_LINES,
|
|
911
|
+
total_lines=len(full.splitlines()),
|
|
912
|
+
expanded=self._thinking_expanded,
|
|
913
|
+
)
|
|
914
|
+
cards = tuple(
|
|
915
|
+
ToolCardView(
|
|
916
|
+
call_id=state.call_id,
|
|
917
|
+
label=f"{state.name} {state.args_text}".strip(),
|
|
918
|
+
status=state.status,
|
|
919
|
+
duration_ms=state.duration_ms,
|
|
920
|
+
detail=self._tool_detail(state),
|
|
921
|
+
expanded=state.expanded,
|
|
922
|
+
)
|
|
923
|
+
for call_id in self._tool_order
|
|
924
|
+
if (state := self._tools.get(call_id)) is not None
|
|
925
|
+
)
|
|
926
|
+
status_view = self._status_view()
|
|
927
|
+
return TuiSnapshot(
|
|
928
|
+
history_lines=tuple(self._history),
|
|
929
|
+
thinking=thinking,
|
|
930
|
+
thinking_max_lines=self.THINKING_TAIL_LINES,
|
|
931
|
+
tool_cards=cards,
|
|
932
|
+
plan=self._plan_panel(),
|
|
933
|
+
status=status_view.summary,
|
|
934
|
+
streaming_answer="".join(self._answer),
|
|
935
|
+
transcript=tuple(self._transcript),
|
|
936
|
+
revision=self._revision,
|
|
937
|
+
status_view=status_view,
|
|
938
|
+
thinking_expanded=self._thinking_expanded,
|
|
939
|
+
)
|
|
940
|
+
|
|
941
|
+
def _plan_panel(self) -> PlanView | None:
|
|
942
|
+
"""面板内容:实施计划正文 + 执行步骤表。两者都没有时返回 ``None``。"""
|
|
943
|
+
document = tuple(self._plan_mode.plan.splitlines()) if self._plan_mode.has_plan else ()
|
|
944
|
+
steps = self._plan
|
|
945
|
+
if not document and steps is None:
|
|
946
|
+
return None
|
|
947
|
+
mode = ""
|
|
948
|
+
if self._plan_mode.active:
|
|
949
|
+
mode = "规划中"
|
|
950
|
+
elif self._plan_mode.has_plan:
|
|
951
|
+
mode = "已批准" if self._plan_mode.approved else "未批准"
|
|
952
|
+
if steps is None:
|
|
953
|
+
return PlanView(
|
|
954
|
+
revision=self._plan_mode.revision,
|
|
955
|
+
total=0,
|
|
956
|
+
completed=0,
|
|
957
|
+
lines=(),
|
|
958
|
+
document=document,
|
|
959
|
+
document_revision=self._plan_mode.revision,
|
|
960
|
+
mode=mode,
|
|
961
|
+
)
|
|
962
|
+
return replace(
|
|
963
|
+
steps,
|
|
964
|
+
document=document,
|
|
965
|
+
document_revision=self._plan_mode.revision,
|
|
966
|
+
mode=mode,
|
|
967
|
+
)
|
|
968
|
+
|
|
969
|
+
def _tool_detail(self, state: _ToolState) -> str:
|
|
970
|
+
if not state.expanded:
|
|
971
|
+
return ""
|
|
972
|
+
metrics = [
|
|
973
|
+
part
|
|
974
|
+
for part in (
|
|
975
|
+
f"{state.duration_ms}ms" if state.duration_ms is not None else "",
|
|
976
|
+
state.size,
|
|
977
|
+
)
|
|
978
|
+
if part
|
|
979
|
+
]
|
|
980
|
+
parts = [f"参数 {state.args_text}" if state.args_text else "参数(无)"]
|
|
981
|
+
if metrics:
|
|
982
|
+
parts.append(" · ".join(metrics))
|
|
983
|
+
if state.output_path:
|
|
984
|
+
parts.append(f"输出 {state.output_path}")
|
|
985
|
+
return " | ".join(parts)
|
|
986
|
+
|
|
987
|
+
def _status_view(self) -> StatusView:
|
|
988
|
+
return StatusView(
|
|
989
|
+
model=f"{self._model.provider}/{self._model.id}",
|
|
990
|
+
context_percent=self._context_percent,
|
|
991
|
+
cost=self._cost,
|
|
992
|
+
tool_count=self._tool_count,
|
|
993
|
+
permission=self._permission_mode,
|
|
994
|
+
plan=(f"计划 {self._plan.completed}/{self._plan.total}" if self._plan else ""),
|
|
995
|
+
background=self._background,
|
|
996
|
+
used_tokens=self._used_tokens,
|
|
997
|
+
context_remaining=self._context_remaining,
|
|
998
|
+
context_window=self._context_window,
|
|
999
|
+
cache_hit=self._cache_hit,
|
|
1000
|
+
fields=self._statusline_fields,
|
|
1001
|
+
)
|
|
1002
|
+
|
|
1003
|
+
|
|
1004
|
+
# ---------------------------------------------------------------- 工具函数
|
|
1005
|
+
|
|
1006
|
+
|
|
1007
|
+
_ARG_KEYS = ("path", "command", "pattern", "file_path", "query", "url")
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
def _summarize_args(args: JsonValue) -> str:
|
|
1011
|
+
if isinstance(args, dict):
|
|
1012
|
+
for key in _ARG_KEYS:
|
|
1013
|
+
value = args.get(key)
|
|
1014
|
+
if isinstance(value, str) and value.strip():
|
|
1015
|
+
text = " ".join(value.split())
|
|
1016
|
+
return text[:40] + ("…" if len(text) > 40 else "")
|
|
1017
|
+
return ""
|
|
1018
|
+
|
|
1019
|
+
|
|
1020
|
+
def _result_size(result: AgentToolResult) -> str:
|
|
1021
|
+
chars = sum(len(block.text) for block in result.content if isinstance(block, TextContent))
|
|
1022
|
+
if chars <= 0:
|
|
1023
|
+
return ""
|
|
1024
|
+
if chars < 1024:
|
|
1025
|
+
return f"{chars}B"
|
|
1026
|
+
return f"{chars / 1024:.1f}KB"
|
|
1027
|
+
|
|
1028
|
+
|
|
1029
|
+
def _output_path(result: AgentToolResult) -> str | None:
|
|
1030
|
+
details = result.details
|
|
1031
|
+
if isinstance(details, dict):
|
|
1032
|
+
for key in ("outputFile", "path", "file"):
|
|
1033
|
+
value = details.get(key)
|
|
1034
|
+
if isinstance(value, str) and value:
|
|
1035
|
+
return value
|
|
1036
|
+
return None
|
|
1037
|
+
|
|
1038
|
+
|
|
1039
|
+
def _message_text(message: UserMessage | AssistantMessage) -> str:
|
|
1040
|
+
content: Sequence[ContentBlock] | str = message.content
|
|
1041
|
+
if isinstance(content, str):
|
|
1042
|
+
return content
|
|
1043
|
+
return "".join(block.text for block in content if isinstance(block, TextContent))
|