@armadra/agent 0.3.0 → 0.4.0

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 (198) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/README.md +93 -44
  3. package/dist/agent/retry.d.ts +1 -1
  4. package/dist/agent/retry.js +2 -1
  5. package/dist/agent/session-cache.js +1 -1
  6. package/dist/agent/session-classifier.d.ts +18 -0
  7. package/dist/agent/session-classifier.js +103 -0
  8. package/dist/agent/session-core.d.ts +13 -0
  9. package/dist/agent/session-tools.js +24 -3
  10. package/dist/agent/session.d.ts +3 -0
  11. package/dist/agent/session.js +12 -3
  12. package/dist/agent/tool-runner.js +15 -2
  13. package/dist/agent/types.d.ts +9 -1
  14. package/dist/ai/apis/anthropic-messages.js +3 -2
  15. package/dist/ai/apis/google-generative-ai.js +3 -2
  16. package/dist/ai/apis/openai-completions.js +3 -2
  17. package/dist/ai/apis/openai-responses.js +3 -2
  18. package/dist/ai/http.d.ts +28 -6
  19. package/dist/ai/http.js +41 -8
  20. package/dist/ai/providers/registry.d.ts +8 -1
  21. package/dist/ai/providers/registry.js +30 -22
  22. package/dist/ai/providers/suggest.d.ts +18 -0
  23. package/dist/ai/providers/suggest.js +72 -0
  24. package/dist/ai/sse.d.ts +6 -2
  25. package/dist/ai/sse.js +22 -2
  26. package/dist/ai/types.d.ts +9 -2
  27. package/dist/bundle/ama.cjs +15279 -10151
  28. package/dist/cli/args.d.ts +19 -4
  29. package/dist/cli/args.js +83 -10
  30. package/dist/cli/bootstrap.js +27 -3
  31. package/dist/cli/codemode-notice.d.ts +20 -0
  32. package/dist/cli/codemode-notice.js +55 -0
  33. package/dist/cli/compose-session.d.ts +5 -0
  34. package/dist/cli/compose-session.js +32 -1
  35. package/dist/cli/compose-store.d.ts +1 -1
  36. package/dist/cli/compose-store.js +3 -1
  37. package/dist/cli/compose.d.ts +14 -4
  38. package/dist/cli/compose.js +29 -10
  39. package/dist/cli/default-model.d.ts +38 -1
  40. package/dist/cli/default-model.js +96 -9
  41. package/dist/cli/deps.d.ts +36 -0
  42. package/dist/cli/exit-codes.d.ts +2 -0
  43. package/dist/cli/exit-codes.js +3 -0
  44. package/dist/cli/fake-visibility.d.ts +13 -0
  45. package/dist/cli/fake-visibility.js +26 -0
  46. package/dist/cli/from-prompt.d.ts +18 -0
  47. package/dist/cli/from-prompt.js +49 -0
  48. package/dist/cli/main.d.ts +9 -2
  49. package/dist/cli/main.js +77 -3
  50. package/dist/cli/proxy.d.ts +51 -0
  51. package/dist/cli/proxy.js +135 -0
  52. package/dist/cli/startup-screen.d.ts +29 -0
  53. package/dist/cli/startup-screen.js +47 -0
  54. package/dist/cli/startup-steps.d.ts +1 -1
  55. package/dist/cli/startup-steps.js +14 -12
  56. package/dist/cli/subcommands/config.d.ts +19 -3
  57. package/dist/cli/subcommands/config.js +108 -21
  58. package/dist/cli/subcommands/context.js +4 -1
  59. package/dist/cli/subcommands/doctor.js +12 -1
  60. package/dist/cli/subcommands/init.js +2 -1
  61. package/dist/cli/subcommands/models-discover.d.ts +15 -9
  62. package/dist/cli/subcommands/models-discover.js +53 -46
  63. package/dist/cli/subcommands/probe-runner.d.ts +96 -0
  64. package/dist/cli/subcommands/probe-runner.js +264 -0
  65. package/dist/cli/subcommands/providers-probe.d.ts +34 -0
  66. package/dist/cli/subcommands/providers-probe.js +87 -0
  67. package/dist/cli/subcommands/providers.d.ts +3 -2
  68. package/dist/cli/subcommands/providers.js +48 -45
  69. package/dist/cli/subcommands/sessions-export.d.ts +10 -0
  70. package/dist/cli/subcommands/sessions-export.js +59 -0
  71. package/dist/cli/subcommands/sessions-search.d.ts +13 -0
  72. package/dist/cli/subcommands/sessions-search.js +103 -0
  73. package/dist/cli/subcommands/sessions.d.ts +3 -2
  74. package/dist/cli/subcommands/sessions.js +22 -1
  75. package/dist/cli/subcommands/stats.d.ts +17 -0
  76. package/dist/cli/subcommands/stats.js +198 -0
  77. package/dist/cli/system-prompt-arg.d.ts +11 -0
  78. package/dist/cli/system-prompt-arg.js +34 -0
  79. package/dist/codemode/modes.d.ts +4 -11
  80. package/dist/codemode/modes.js +5 -27
  81. package/dist/codemode/tool.d.ts +18 -14
  82. package/dist/codemode/tool.js +71 -28
  83. package/dist/config/init.d.ts +6 -2
  84. package/dist/config/init.js +12 -5
  85. package/dist/config/json-schema.d.ts +1 -0
  86. package/dist/config/json-schema.js +36 -3
  87. package/dist/config/key-docs.d.ts +22 -0
  88. package/dist/config/key-docs.js +105 -0
  89. package/dist/config/merge.d.ts +9 -8
  90. package/dist/config/merge.js +22 -7
  91. package/dist/config/schema.d.ts +1 -1
  92. package/dist/config/schema.js +24 -5
  93. package/dist/config/types.d.ts +34 -6
  94. package/dist/config/types.js +17 -1
  95. package/dist/modes/commands-core.js +6 -5
  96. package/dist/modes/interactive/approval-dialog.d.ts +21 -5
  97. package/dist/modes/interactive/approval-dialog.js +106 -27
  98. package/dist/modes/interactive/commands.d.ts +11 -2
  99. package/dist/modes/interactive/commands.js +56 -16
  100. package/dist/modes/interactive/interactive-mode.d.ts +2 -1
  101. package/dist/modes/interactive/interactive-mode.js +65 -81
  102. package/dist/modes/interactive/key-dispatch.d.ts +3 -1
  103. package/dist/modes/interactive/key-dispatch.js +5 -6
  104. package/dist/modes/interactive/line/line-mode.d.ts +1 -0
  105. package/dist/modes/interactive/line/line-mode.js +6 -4
  106. package/dist/modes/interactive/line/line-render.d.ts +4 -0
  107. package/dist/modes/interactive/line/line-render.js +28 -6
  108. package/dist/modes/interactive/message-view.d.ts +48 -9
  109. package/dist/modes/interactive/message-view.js +238 -44
  110. package/dist/modes/interactive/panels.d.ts +18 -0
  111. package/dist/modes/interactive/panels.js +143 -0
  112. package/dist/modes/interactive/pickers.d.ts +23 -2
  113. package/dist/modes/interactive/pickers.js +48 -15
  114. package/dist/modes/interactive/run-indicator.d.ts +51 -0
  115. package/dist/modes/interactive/run-indicator.js +189 -0
  116. package/dist/modes/interactive/startup-header.d.ts +40 -0
  117. package/dist/modes/interactive/startup-header.js +169 -0
  118. package/dist/modes/interactive/status-bar.d.ts +18 -15
  119. package/dist/modes/interactive/status-bar.js +98 -56
  120. package/dist/modes/interactive/tool-summary.d.ts +46 -0
  121. package/dist/modes/interactive/tool-summary.js +218 -0
  122. package/dist/modes/interactive/tool-view.d.ts +48 -15
  123. package/dist/modes/interactive/tool-view.js +203 -145
  124. package/dist/modes/print/print-mode.d.ts +31 -4
  125. package/dist/modes/print/print-mode.js +116 -7
  126. package/dist/modes/rpc/commands.js +5 -0
  127. package/dist/permissions/auto-safe.d.ts +60 -0
  128. package/dist/permissions/auto-safe.js +529 -0
  129. package/dist/permissions/classifier.d.ts +64 -0
  130. package/dist/permissions/classifier.js +184 -0
  131. package/dist/permissions/dangerous.d.ts +5 -0
  132. package/dist/permissions/dangerous.js +1 -1
  133. package/dist/permissions/modes.d.ts +30 -0
  134. package/dist/permissions/modes.js +78 -0
  135. package/dist/permissions/pipeline.d.ts +31 -4
  136. package/dist/permissions/pipeline.js +196 -6
  137. package/dist/permissions/protected.d.ts +19 -0
  138. package/dist/permissions/protected.js +74 -0
  139. package/dist/permissions/rules.js +3 -0
  140. package/dist/permissions/types.d.ts +50 -3
  141. package/dist/permissions/types.js +3 -0
  142. package/dist/sdk.d.ts +9 -3
  143. package/dist/sdk.js +10 -2
  144. package/dist/session/export.d.ts +32 -0
  145. package/dist/session/export.js +187 -0
  146. package/dist/session/redact.d.ts +15 -0
  147. package/dist/session/redact.js +55 -0
  148. package/dist/session/reuse.d.ts +33 -0
  149. package/dist/session/reuse.js +86 -0
  150. package/dist/session/scan.d.ts +34 -0
  151. package/dist/session/scan.js +140 -0
  152. package/dist/session/search.d.ts +52 -0
  153. package/dist/session/search.js +211 -0
  154. package/dist/session/stats-aggregate.d.ts +63 -0
  155. package/dist/session/stats-aggregate.js +163 -0
  156. package/dist/session/stats-index.d.ts +26 -0
  157. package/dist/session/stats-index.js +91 -0
  158. package/dist/session/stats-scan.d.ts +54 -0
  159. package/dist/session/stats-scan.js +236 -0
  160. package/dist/tools/presets.d.ts +35 -8
  161. package/dist/tools/presets.js +56 -17
  162. package/dist/tui/component.d.ts +8 -2
  163. package/dist/tui/component.js +3 -1
  164. package/dist/tui/components/box.d.ts +6 -1
  165. package/dist/tui/components/box.js +16 -6
  166. package/dist/tui/components/card.d.ts +23 -0
  167. package/dist/tui/components/card.js +37 -0
  168. package/dist/tui/components/editor-history.d.ts +6 -0
  169. package/dist/tui/components/editor-history.js +45 -0
  170. package/dist/tui/components/editor-paste.d.ts +1 -1
  171. package/dist/tui/components/editor-paste.js +4 -4
  172. package/dist/tui/components/editor.d.ts +11 -5
  173. package/dist/tui/components/editor.js +52 -58
  174. package/dist/tui/components/key-value.d.ts +3 -0
  175. package/dist/tui/components/key-value.js +16 -6
  176. package/dist/tui/components/loader.d.ts +37 -7
  177. package/dist/tui/components/loader.js +84 -21
  178. package/dist/tui/components/markdown.d.ts +5 -1
  179. package/dist/tui/components/markdown.js +45 -21
  180. package/dist/tui/components/meter.d.ts +3 -3
  181. package/dist/tui/components/meter.js +13 -11
  182. package/dist/tui/components/select-list.d.ts +23 -1
  183. package/dist/tui/components/select-list.js +76 -13
  184. package/dist/tui/glyphs.d.ts +68 -0
  185. package/dist/tui/glyphs.js +114 -0
  186. package/dist/tui/theme.d.ts +30 -6
  187. package/dist/tui/theme.js +103 -17
  188. package/dist/tui.d.ts +4 -2
  189. package/dist/tui.js +3 -1
  190. package/docs/codemode.md +23 -9
  191. package/docs/hooks.md +10 -10
  192. package/docs/permissions.md +148 -0
  193. package/docs/providers.md +33 -10
  194. package/docs/rpc.md +36 -36
  195. package/docs/session-format.md +2 -1
  196. package/docs/sessions.md +134 -0
  197. package/docs/tui.md +139 -62
  198. package/package.json +3 -1
@@ -1,17 +1,159 @@
1
1
  /**
2
2
  * 消息区(设计 §12.5)。[B7]
3
3
  *
4
- * 一个纵向 `Container`,块与块之间空一行:
5
- * - 用户消息 `› 文本`;steer / followUp / 宿主注入按 `UserMessage.origin` 标 `↳ steer` / `↳ host` …;
4
+ * 一个纵向 `Container`,块与块之间空一行(终端界面视觉设计 v1 §1 原则 2:相邻工具调用之间不空行,
5
+ * `ui.compact` 时全部不空行):
6
+ * - 用户消息 `› 文本`(续行缩进 2 列);插话 / 之后 / 宿主注入按 `UserMessage.origin` 标
7
+ * `↳ 插话` / `↳ 之后` / `↳ 宿主`(整行 muted,其它 origin 原样显示);
6
8
  * - 助手消息按内容块渲染:文本走 `Markdown`(`ui.markdown: false` 时纯文本),流式时只改末块
7
- * (Markdown 自己按块缓存);思考块按 `ui.showThinking`:`collapsed`(缺省)一行 `思考 · N token`、
8
- * `full` 显示全文、`hidden` 不显示;
9
- * - 压缩摘要卡、重试提示、Hook 阻止提示、宿主 / 系统通知;
9
+ * (Markdown 自己按块缓存);思考块按 `ui.showThinking`:`collapsed`(缺省)一行 `✻ 思考 · N token`
10
+ * (流式中 `✻ 思考中…`),Ctrl+O 展开为标题 + 缩进 2 列的正文(最多 60 行);`full` 总是展开且不限行;
11
+ * `hidden` 不显示;
12
+ * - 压缩摘要卡(左竖条 Card)、重试提示、Hook 阻止提示、宿主 / 系统通知;字形取 `theme.glyphs`;
10
13
  * - `replay()` 把已有消息(恢复会话、切换会话、/tree 之后)重新画出来,工具调用交给调用方构造。
11
14
  *
12
15
  * 滚动交给终端回滚:消息区只追加,切换会话时整体清空重画。
13
16
  */
14
- import { Box, Container, Markdown, Spacer, Text } from "../../tui.js";
17
+ import { Card, Container, Markdown, Spacer, Text, visibleWidth, wrapTextWithAnsi, } from "../../tui.js";
18
+ import { formatCost, formatTokens } from "./status-bar.js";
19
+ /** 退出摘要的时长:不足 1 分钟按秒,否则按分钟。 */
20
+ function sessionDuration(ms) {
21
+ const seconds = Math.max(0, Math.round(ms / 1000));
22
+ return seconds < 60 ? `${seconds} 秒` : `${Math.round(seconds / 60)} 分钟`;
23
+ }
24
+ /**
25
+ * 退出摘要(§3.14):`─ 会话 <id> · 时长 · N 回合 · ↑in ↓out · cache x% · $y(重计费 $z)` 与
26
+ * ` 恢复:ama --resume <id>`。整体 dim,会话 id 与恢复命令正文色;0 回合只到「回合」;会话没落盘不给恢复行。
27
+ */
28
+ export function exitSummaryLines(stats, elapsedMs, theme) {
29
+ const g = theme.glyphs;
30
+ const dim = (s) => theme.fg("dim", s);
31
+ const id = stats.sessionId.slice(0, 8);
32
+ const parts = [
33
+ dim(`${g.rule} 会话 `) + theme.fg("text", id),
34
+ dim(sessionDuration(elapsedMs)),
35
+ dim(`${stats.userMessages} 回合`),
36
+ ];
37
+ const t = stats.tokens;
38
+ const prompt = t.input + t.cacheRead + t.cacheWrite;
39
+ if (stats.userMessages > 0 && prompt + t.output > 0) {
40
+ parts.push(dim(`${g.arrowUp}${formatTokens(prompt)} ${g.arrowDown}${formatTokens(t.output)}`));
41
+ const rate = stats.cache?.hitRate ?? stats.cacheHitRate;
42
+ if (rate !== undefined)
43
+ parts.push(dim(`cache ${Math.round(rate * 100)}%`));
44
+ if (stats.cost !== undefined && stats.cost > 0) {
45
+ const rebill = stats.cache?.reBilledUsd;
46
+ const extra = rebill !== undefined && rebill > 0 ? `(重计费 ${formatCost(rebill)})` : "";
47
+ parts.push(dim(formatCost(stats.cost) + extra));
48
+ }
49
+ }
50
+ const lines = [parts.join(dim(" · "))];
51
+ if (stats.userMessages > 0 && stats.sessionFile !== undefined) {
52
+ lines.push(dim(" 恢复:") + theme.fg("text", `ama --resume ${id}`));
53
+ }
54
+ return lines;
55
+ }
56
+ /** 思考块展开时的正文行数上限(`full` 不限)。 */
57
+ export const THINKING_EXPANDED_LINES = 60;
58
+ /** origin → 中文标签(未知 origin 原样显示)。 */
59
+ export const ORIGIN_LABELS = {
60
+ steer: "插话",
61
+ followUp: "之后",
62
+ host: "宿主",
63
+ };
64
+ /** 首行带前缀、续行按 `indent` 缩进的文本(用户消息、排队消息)。 */
65
+ export class PrefixedText {
66
+ prefix;
67
+ body;
68
+ indent;
69
+ cache = null;
70
+ constructor(prefix, body, indent = 2) {
71
+ this.prefix = prefix;
72
+ this.body = body;
73
+ this.indent = indent;
74
+ }
75
+ render(width) {
76
+ if (this.cache?.width === width)
77
+ return this.cache.lines;
78
+ const prefixWidth = Math.max(this.indent, visibleWidth(this.prefix));
79
+ const pieces = wrapTextWithAnsi(this.body, Math.max(1, width - prefixWidth));
80
+ const pad = " ".repeat(this.indent);
81
+ const lines = pieces.map((line, i) => (i === 0 ? this.prefix + line : pad + line));
82
+ if (lines.length === 0)
83
+ lines.push(this.prefix);
84
+ this.cache = { width, lines };
85
+ return lines;
86
+ }
87
+ invalidate() {
88
+ this.cache = null;
89
+ }
90
+ }
91
+ /** 思考块:折叠一行 / 展开(标题 + 缩进正文)。 */
92
+ class ThinkingView {
93
+ theme;
94
+ display;
95
+ text = "";
96
+ tokens = 0;
97
+ streaming = true;
98
+ redacted = false;
99
+ expanded = false;
100
+ cache = null;
101
+ constructor(theme, display) {
102
+ this.theme = theme;
103
+ this.display = display;
104
+ }
105
+ set(text, tokens, streaming, redacted) {
106
+ if (text === this.text &&
107
+ tokens === this.tokens &&
108
+ streaming === this.streaming &&
109
+ redacted === this.redacted)
110
+ return;
111
+ this.text = text;
112
+ this.tokens = tokens;
113
+ this.streaming = streaming;
114
+ this.redacted = redacted;
115
+ this.cache = null;
116
+ }
117
+ setExpanded(expanded) {
118
+ if (expanded === this.expanded)
119
+ return;
120
+ this.expanded = expanded;
121
+ this.cache = null;
122
+ }
123
+ get open() {
124
+ return !this.redacted && (this.display === "full" || this.expanded);
125
+ }
126
+ render(width) {
127
+ if (this.cache?.width === width)
128
+ return this.cache.lines;
129
+ const t = this.theme;
130
+ const g = t.glyphs;
131
+ const style = (s) => t.fg("dim", t.italic(s));
132
+ const title = this.streaming
133
+ ? `${g.thinking} 思考中${g.ellipsis}`
134
+ : `${g.thinking} 思考 · ${formatTokens(this.tokens)} token`;
135
+ const lines = [
136
+ style(title) + (this.open && !this.streaming ? " " + t.fg("dim", g.collapse) : ""),
137
+ ];
138
+ if (this.open && this.text.trim() !== "") {
139
+ const all = this.text
140
+ .trim()
141
+ .split("\n")
142
+ .flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width - 2)));
143
+ const limit = this.display === "full" ? all.length : THINKING_EXPANDED_LINES;
144
+ for (const line of all.slice(0, limit))
145
+ lines.push(" " + t.fg("muted", t.italic(line)));
146
+ if (all.length > limit) {
147
+ lines.push(" " + t.fg("dim", `${g.ellipsis} 另 ${all.length - limit} 行`));
148
+ }
149
+ }
150
+ this.cache = { width, lines };
151
+ return lines;
152
+ }
153
+ invalidate() {
154
+ this.cache = null;
155
+ }
156
+ }
15
157
  /** 粗估 token(4 字符 ≈ 1 token),只用于思考块的流式计数。 */
16
158
  export function estimateTokens(text) {
17
159
  return Math.ceil(text.length / 4);
@@ -29,10 +171,19 @@ export class AssistantView extends Container {
29
171
  parts = new Map();
30
172
  status = new Text("");
31
173
  streaming = true;
174
+ thinkingExpanded = false;
32
175
  constructor(options) {
33
176
  super();
34
177
  this.options = options;
35
178
  }
179
+ /** Ctrl+O:展开 / 折叠本消息的思考块(`collapsed` 模式下)。 */
180
+ setThinkingExpanded(expanded) {
181
+ this.thinkingExpanded = expanded;
182
+ for (const part of this.parts.values()) {
183
+ if (part instanceof ThinkingView)
184
+ part.setExpanded(expanded);
185
+ }
186
+ }
36
187
  update(message) {
37
188
  const { theme } = this.options;
38
189
  const display = this.options.showThinking ?? "collapsed";
@@ -43,18 +194,21 @@ export class AssistantView extends Container {
43
194
  if (block.type === "thinking") {
44
195
  if (display === "hidden" || (block.thinking === "" && block.redacted !== true))
45
196
  return;
46
- const text = this.part(index, () => new Text(""));
47
- if (display === "full" && block.redacted !== true) {
48
- text.setText(theme.fg("dim", theme.italic(block.thinking.trim())));
49
- }
50
- else {
51
- const single = message.content.filter((b) => b.type === "thinking").length === 1;
52
- const tokens = !this.streaming && single && message.usage.reasoning !== undefined
53
- ? message.usage.reasoning
54
- : estimateTokens(block.thinking);
55
- text.setText(theme.fg("dim", `${this.streaming ? "思考…" : "思考 ·"} ${tokens} token`));
56
- }
57
- order.push(text);
197
+ const view = this.part(index, () => {
198
+ const created = new ThinkingView(theme, display);
199
+ created.setExpanded(this.thinkingExpanded);
200
+ return created;
201
+ });
202
+ const single = message.content.filter((b) => b.type === "thinking").length === 1;
203
+ const tokens = !this.streaming && single && message.usage.reasoning !== undefined
204
+ ? message.usage.reasoning
205
+ : estimateTokens(block.thinking);
206
+ // 后面已经有正文 / 工具调用:这段思考已结束
207
+ const later = message.content
208
+ .slice(index + 1)
209
+ .some((b) => (b.type === "text" ? b.text !== "" : b.type === "toolCall"));
210
+ view.set(block.thinking, tokens, this.streaming && !later, block.redacted === true);
211
+ order.push(view);
58
212
  return;
59
213
  }
60
214
  if (block.text.trim() === "")
@@ -64,14 +218,15 @@ export class AssistantView extends Container {
64
218
  view.setText(block.text);
65
219
  order.push(view);
66
220
  });
221
+ const gap = this.options.compact !== true;
67
222
  this.clear();
68
223
  order.forEach((child, i) => {
69
- if (i > 0)
224
+ if (i > 0 && gap)
70
225
  this.addChild(new Spacer());
71
226
  this.addChild(child);
72
227
  });
73
228
  if (this.status.getText() !== "") {
74
- if (order.length > 0)
229
+ if (order.length > 0 && gap)
75
230
  this.addChild(new Spacer());
76
231
  this.addChild(this.status);
77
232
  }
@@ -81,7 +236,7 @@ export class AssistantView extends Container {
81
236
  this.streaming = false;
82
237
  const { theme } = this.options;
83
238
  if (message.stopReason === "error") {
84
- this.status.setText(theme.fg("error", `✗ ${message.errorMessage ?? "模型调用失败"}`));
239
+ this.status.setText(theme.fg("error", `${theme.glyphs.fail} ${message.errorMessage ?? "模型调用失败"}`));
85
240
  }
86
241
  else if (message.stopReason === "aborted") {
87
242
  this.status.setText(theme.fg("dim", "已中断"));
@@ -107,6 +262,10 @@ export class MessageView extends Container {
107
262
  options;
108
263
  current;
109
264
  blocks = [];
265
+ /** 工具调用块(相邻的不空行)。 */
266
+ toolBlocks = new WeakSet();
267
+ assistants = [];
268
+ thinkingExpanded = false;
110
269
  constructor(options) {
111
270
  super();
112
271
  this.options = options;
@@ -114,9 +273,19 @@ export class MessageView extends Container {
114
273
  get theme() {
115
274
  return this.options.theme;
116
275
  }
117
- /** 追加一块(与上一块之间空一行)。 */
276
+ /** 追加一块(与上一块之间空一行;`compact` 不空行)。 */
118
277
  add(component) {
119
- if (this.blocks.length > 0)
278
+ this.push(component, this.options.compact !== true);
279
+ }
280
+ /** 追加工具调用块:紧跟在另一个工具调用后面时不空行。 */
281
+ addTool(component) {
282
+ const last = this.blocks[this.blocks.length - 1];
283
+ const gap = this.options.compact !== true && !(last !== undefined && this.toolBlocks.has(last));
284
+ this.toolBlocks.add(component);
285
+ this.push(component, gap);
286
+ }
287
+ push(component, gap) {
288
+ if (this.blocks.length > 0 && gap)
120
289
  this.addChild(new Spacer());
121
290
  this.blocks.push(component);
122
291
  this.addChild(component);
@@ -141,12 +310,19 @@ export class MessageView extends Container {
141
310
  reset() {
142
311
  this.clear();
143
312
  this.blocks.length = 0;
313
+ this.assistants.length = 0;
144
314
  this.current = undefined;
145
315
  }
146
316
  get blockCount() {
147
317
  return this.blocks.length;
148
318
  }
149
- /** 启动画面:首行加粗,其余变暗。 */
319
+ /** Ctrl+O:所有助手消息的思考块一起展开 / 折叠(之后的新消息沿用)。 */
320
+ setThinkingExpanded(expanded) {
321
+ this.thinkingExpanded = expanded;
322
+ for (const view of this.assistants)
323
+ view.setThinkingExpanded(expanded);
324
+ }
325
+ /** 纯文本启动画面(line 模式风格):首行加粗,其余变暗。交互模式用 StartupHeader。 */
150
326
  addHeader(lines) {
151
327
  if (lines.length === 0)
152
328
  return;
@@ -155,15 +331,24 @@ export class MessageView extends Container {
155
331
  this.add(new Text(text.join("\n")));
156
332
  }
157
333
  addUser(message) {
334
+ const t = this.theme;
158
335
  const text = contentText(message.content).replace(/\s+$/, "");
159
336
  const origin = message.origin;
160
- const label = origin === undefined || origin === "user"
161
- ? this.theme.fg("user", "› ")
162
- : this.theme.fg("dim", `↳ ${origin} `);
163
- this.add(new Text(label + text));
337
+ if (origin === undefined || origin === "user") {
338
+ this.add(new PrefixedText(t.fg("user", t.bold(t.glyphs.prompt)) + " ", text));
339
+ return;
340
+ }
341
+ const label = ORIGIN_LABELS[origin] ?? origin;
342
+ this.add(new PrefixedText(t.fg("dim", t.glyphs.queued) + " " + t.fg("muted", `${label} `), t.fg("muted", text)));
164
343
  }
165
- startAssistant(message) {
344
+ newAssistant() {
166
345
  const view = new AssistantView(this.options);
346
+ view.setThinkingExpanded(this.thinkingExpanded);
347
+ this.assistants.push(view);
348
+ return view;
349
+ }
350
+ startAssistant(message) {
351
+ const view = this.newAssistant();
167
352
  view.update(message);
168
353
  this.current = view;
169
354
  this.add(view);
@@ -184,39 +369,48 @@ export class MessageView extends Container {
184
369
  this.remove(view);
185
370
  }
186
371
  addNotice(level, message) {
372
+ const g = this.theme.glyphs;
187
373
  const color = level === "error" ? "error" : level === "warn" ? "warning" : "dim";
188
- const mark = level === "error" ? "✗ " : level === "warn" ? "! " : "";
374
+ const mark = level === "error" ? `${g.fail} ` : level === "warn" ? `${g.warn} ` : "";
189
375
  this.add(new Text(this.theme.fg(color, mark + message)));
190
376
  }
191
377
  addHookBlocked(reason) {
192
- this.add(new Text(this.theme.fg("warning", `⛔ Hook 阻止:${reason}`)));
378
+ const glyph = this.theme.glyphs.blocked;
379
+ this.add(new Text(this.theme.fg("warning", `${glyph} Hook 阻止:${reason}`)));
193
380
  }
194
381
  addRetry(attempt, maxAttempts, delayMs, error) {
195
382
  const seconds = Math.max(1, Math.round(delayMs / 1000));
196
- this.add(new Text(this.theme.fg("warning", `↻ 重试 ${attempt}/${maxAttempts}(${seconds}s 后):${error}`)));
383
+ const glyph = this.theme.glyphs.retry;
384
+ this.add(new Text(this.theme.fg("warning", `${glyph} 重试 ${attempt}/${maxAttempts}(${seconds}s 后):${error}`)));
385
+ }
386
+ /** 退出前追加的会话摘要(留在终端回滚里)。 */
387
+ addExitSummary(lines) {
388
+ this.add(new Text(lines.join("\n")));
197
389
  }
198
390
  addRetryFailed(error) {
199
391
  this.addNotice("error", `重试失败${error !== undefined ? `:${error}` : ""}`);
200
392
  }
201
- /** 压缩 / 分支摘要卡:token 变化(有则显示)+ 摘要前 3 行。 */
393
+ /** 压缩 / 分支摘要卡(左竖条):标题 + token 变化(有则显示)+ 摘要前 3 行。 */
202
394
  addSummaryCard(summary, options = {}) {
203
- const dim = (s) => this.theme.fg("dim", s);
395
+ const t = this.theme;
204
396
  const lines = summary
205
397
  .trim()
206
398
  .split("\n")
207
399
  .filter((l) => l.trim() !== "");
208
400
  const head = lines.slice(0, 3);
209
- const body = [];
401
+ const body = head.map((l) => t.fg("muted", l));
402
+ if (lines.length > head.length) {
403
+ body.push(t.fg("dim", `${t.glyphs.ellipsis} 另 ${lines.length - head.length} 行`));
404
+ }
405
+ let subtitle;
210
406
  if (options.tokensBefore !== undefined) {
211
- const after = options.tokensAfter !== undefined ? ` → ${options.tokensAfter}` : "";
212
- body.push(dim(`${options.tokensBefore}${after} token`));
407
+ const after = options.tokensAfter !== undefined ? ` → ${formatTokens(options.tokensAfter)}` : "";
408
+ subtitle = `${formatTokens(options.tokensBefore)}${after} token`;
213
409
  }
214
- body.push(...head.map(dim));
215
- if (lines.length > head.length)
216
- body.push(dim(`…(另 ${lines.length - head.length} 行)`));
217
- this.add(new Box(new Text(body.join("\n")), {
410
+ this.add(new Card(new Text(body.join("\n")), {
411
+ theme: t,
218
412
  title: options.title ?? "上下文已压缩",
219
- theme: this.theme,
413
+ ...(subtitle !== undefined ? { subtitle } : {}),
220
414
  }));
221
415
  }
222
416
  addCompaction(result) {
@@ -238,7 +432,7 @@ export class MessageView extends Container {
238
432
  this.addUser(message);
239
433
  break;
240
434
  case "assistant": {
241
- const view = new AssistantView(this.options);
435
+ const view = this.newAssistant();
242
436
  view.finish(message);
243
437
  if (!view.isEmpty)
244
438
  this.add(view);
@@ -247,7 +441,7 @@ export class MessageView extends Container {
247
441
  continue;
248
442
  const tool = hooks.tool(block, results.get(block.id));
249
443
  if (tool !== undefined)
250
- this.add(tool);
444
+ this.addTool(tool);
251
445
  }
252
446
  break;
253
447
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * 消息区面板(终端界面视觉设计 v1 §3.13):`/session`、`/cache`、`/permissions` 用左竖条卡片 + 键值表
3
+ * 渲染,而不是把纯文本拍进通知。line 模式与 RPC 仍用 session-report 的文本版。
4
+ *
5
+ * - `/session`:标题 `会话 <id 前 8 位> · <文件>`;模型 / 消息 / 用量 / 上下文(余量表,阈值着色),
6
+ * 空一行后「缓存」段(与 `/cache` 共用 `cacheRows`);
7
+ * - `/permissions`:权限模式、判定顺序(折行对齐值列)、规则(allow success、deny error、来源 dim)、
8
+ * 最近的 auto 判定。
9
+ */
10
+ import type { AgentSession } from "../../agent/types.js";
11
+ import type { Runtime } from "../../cli/runtime.js";
12
+ import { type Component, type Theme } from "../../tui.js";
13
+ export declare function sessionPanel(session: AgentSession, theme: Theme, options?: {
14
+ now?: number;
15
+ home?: string;
16
+ }): Component;
17
+ export declare function cachePanel(session: AgentSession, theme: Theme, now?: number): Component;
18
+ export declare function permissionsPanel(runtime: Pick<Runtime, "permission">, session: AgentSession, theme: Theme): Component;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * 消息区面板(终端界面视觉设计 v1 §3.13):`/session`、`/cache`、`/permissions` 用左竖条卡片 + 键值表
3
+ * 渲染,而不是把纯文本拍进通知。line 模式与 RPC 仍用 session-report 的文本版。
4
+ *
5
+ * - `/session`:标题 `会话 <id 前 8 位> · <文件>`;模型 / 消息 / 用量 / 上下文(余量表,阈值着色),
6
+ * 空一行后「缓存」段(与 `/cache` 共用 `cacheRows`);
7
+ * - `/permissions`:权限模式、判定顺序(折行对齐值列)、规则(allow success、deny error、来源 dim)、
8
+ * 最近的 auto 判定。
9
+ */
10
+ import { AUTO_LAYER_TEXT, permissionModeLabel } from "../../permissions/modes.js";
11
+ import { Card, KeyValue, Meter, } from "../../tui.js";
12
+ import { cacheRows, formatTokenCount, formatUsd } from "../session-report.js";
13
+ import { tildePath } from "../../cli/startup-screen.js";
14
+ /** 多段内容按顺序拼起来(段之间不加空行,由调用方放空串)。 */
15
+ class Stack {
16
+ parts;
17
+ constructor(parts) {
18
+ this.parts = parts;
19
+ }
20
+ render(width) {
21
+ return this.parts.flatMap((part) => (typeof part === "string" ? [part] : part.render(width)));
22
+ }
23
+ invalidate() {
24
+ for (const part of this.parts)
25
+ if (typeof part !== "string")
26
+ part.invalidate();
27
+ }
28
+ }
29
+ /** 缩进若干列的子组件。 */
30
+ class Indent {
31
+ child;
32
+ columns;
33
+ constructor(child, columns) {
34
+ this.child = child;
35
+ this.columns = columns;
36
+ }
37
+ render(width) {
38
+ const pad = " ".repeat(this.columns);
39
+ return this.child
40
+ .render(Math.max(1, width - this.columns))
41
+ .map((line) => (line === "" ? "" : pad + line));
42
+ }
43
+ invalidate() {
44
+ this.child.invalidate();
45
+ }
46
+ }
47
+ function keyValue(rows, theme, wrap = false) {
48
+ return new KeyValue(rows, { theme, maxKeyRatio: 0.3, ...(wrap ? { wrap: true } : {}) });
49
+ }
50
+ function cacheSection(session, theme, now) {
51
+ return [theme.bold("缓存"), new Indent(keyValue(cacheRows(session, now), theme), 2)];
52
+ }
53
+ export function sessionPanel(session, theme, options = {}) {
54
+ const now = options.now ?? Date.now();
55
+ const state = session.state;
56
+ const stats = session.getStats();
57
+ const t = stats.tokens;
58
+ const sep = theme.fg("dim", " · ");
59
+ const model = state.model === undefined ? "?" : `${state.model.provider}/${state.model.id}`;
60
+ const ratio = stats.contextPercent === undefined ? undefined : stats.contextPercent / 100;
61
+ const meter = new Meter(ratio, { theme }).render(40)[0] ?? "";
62
+ const window = stats.contextTokens === undefined && stats.contextWindow === undefined
63
+ ? ""
64
+ : sep +
65
+ `${stats.contextTokens === undefined ? "?" : formatTokenCount(stats.contextTokens)} / ` +
66
+ `${stats.contextWindow === undefined ? "?" : formatTokenCount(stats.contextWindow)}`;
67
+ const rows = [
68
+ {
69
+ key: "模型",
70
+ value: theme.fg("accent", model) +
71
+ sep +
72
+ `思考 ${state.thinkingLevel}` +
73
+ sep +
74
+ `权限 ${permissionModeLabel(state.permissionMode)}`,
75
+ },
76
+ {
77
+ key: "消息",
78
+ value: [
79
+ `用户 ${stats.userMessages}`,
80
+ `助手 ${stats.assistantMessages}`,
81
+ `工具调用 ${stats.toolCalls}`,
82
+ ].join(sep),
83
+ },
84
+ {
85
+ key: "用量",
86
+ value: [
87
+ `输入 ${formatTokenCount(t.input)}`,
88
+ `输出 ${formatTokenCount(t.output)}`,
89
+ `缓存读 ${formatTokenCount(t.cacheRead)}`,
90
+ `缓存写 ${formatTokenCount(t.cacheWrite)}`,
91
+ formatUsd(stats.cost),
92
+ ].join(sep),
93
+ },
94
+ { key: "上下文", value: meter + window },
95
+ ];
96
+ const file = state.sessionFile === undefined ? "未落盘" : tildePath(state.sessionFile, options.home);
97
+ return new Card(new Stack([keyValue(rows, theme), "", ...cacheSection(session, theme, now)]), {
98
+ theme,
99
+ title: `会话 ${state.sessionId.slice(0, 8)}`,
100
+ subtitle: file,
101
+ });
102
+ }
103
+ export function cachePanel(session, theme, now = Date.now()) {
104
+ return new Card(keyValue(cacheRows(session, now), theme), { theme, title: "缓存" });
105
+ }
106
+ const DECISION_COLOR = {
107
+ allow: "success",
108
+ deny: "error",
109
+ ask: "warning",
110
+ };
111
+ export function permissionsPanel(runtime, session, theme) {
112
+ const rules = runtime.permission.rules;
113
+ const mode = session.state.permissionMode;
114
+ const order = mode === "auto"
115
+ ? "deny 规则 → Hook deny → 危险命令确认 → 规则层(受保护路径、项目外写入、网络、删除类)→ Hook ask → allow 规则 / Hook allow / 本会话记忆 → 静态判定(只读、项目内写入、安全名单)→ 模型分类器 → 询问"
116
+ : mode === "allowlist"
117
+ ? "deny 规则 → Hook deny → 危险命令(拒绝)→ 只读工具 / allow 规则 / Hook allow 放行 → 其余拒绝(从不询问)"
118
+ : "deny 规则 → Hook deny → 危险命令确认 → 权限模式 → allow 规则 / Hook allow / 本会话记忆 → 询问";
119
+ const effect = (decision) => theme.fg(DECISION_COLOR[decision] ?? "text", decision.padEnd(5));
120
+ const parts = [
121
+ keyValue([
122
+ { key: "权限模式", value: `${permissionModeLabel(mode)}${theme.fg("dim", `(${mode})`)}` },
123
+ { key: "判定顺序", value: order },
124
+ ], theme, true),
125
+ theme.bold(rules.length === 0 ? "规则(无)" : `规则(${rules.length})`),
126
+ ];
127
+ if (rules.length > 0) {
128
+ parts.push(new Indent(keyValue(rules.map((r) => ({
129
+ key: effect(r.effect),
130
+ value: `${r.raw} ${theme.fg("dim", `[${r.source}]`)}`,
131
+ })), theme), 2));
132
+ }
133
+ const recent = runtime.permission.autoDecisions?.() ?? [];
134
+ if (recent.length > 0) {
135
+ parts.push(theme.bold(`最近的 auto 判定(${recent.length})`));
136
+ parts.push(new Indent(keyValue(recent.map((d) => ({
137
+ key: AUTO_LAYER_TEXT[d.layer],
138
+ value: `${effect(d.decision)} ${d.toolName} ${d.summary} — ${d.reason}` +
139
+ (d.cached === true ? theme.fg("dim", "(缓存)") : ""),
140
+ })), theme), 2));
141
+ }
142
+ return new Card(new Stack(parts), { theme });
143
+ }
@@ -4,8 +4,11 @@
4
4
  * - 模型:按供应商分组并标 key 状态(`modelItems`,与启动期共用),当前模型预选;
5
5
  * - 会话:名字或首条提示、相对时间、消息数(`sessionItems`);
6
6
  * - 树:会话文件里全部用户消息,按分叉缩进,`●` 标出当前分支;选中项回填编辑器(由 commands.ts 处理);
7
- * - 权限模式(从严到宽)与思考级别。
7
+ * - 权限模式(标题「权限模式」,界面顺序 1–6,当前模式 ✓ / Default dim / Recommended accent,底部按键提示,
8
+ * 上下留白,见 permissionItems)与思考级别;
9
+ * - 所有选择器底部一行按键提示(dim),模型选择器带 (i/n) 并给当前模型打 ✓。
8
10
  */
11
+ import type { PermissionMode } from "../../permissions/types.js";
9
12
  import type { SessionEntry } from "../../session/types.js";
10
13
  import { type Keybindings, type OverlayHandle, type OverlayOptions, type SelectItem, type Theme, type Component } from "../../tui.js";
11
14
  export { modelItems, sessionItems } from "./startup-ui.js";
@@ -23,10 +26,28 @@ export interface PickerSpec {
23
26
  filterable?: boolean;
24
27
  maxVisible?: number;
25
28
  emptyText?: string;
29
+ /** 右侧序号 1–9,按数字直接选中。 */
30
+ numberKeys?: boolean;
31
+ /** 说明放在标签下一行。 */
32
+ stacked?: boolean;
33
+ /** 当前值(标 ✓)。 */
34
+ currentValue?: string;
35
+ /** 列表下的按键提示,缺省「↑↓ 选择 · Enter 确认 · Esc 取消」。 */
36
+ footer?: string;
37
+ /** 提示行前带 (i/n)。 */
38
+ showCount?: boolean;
39
+ /** 框内上下留白行数。 */
40
+ paddingY?: number;
26
41
  }
42
+ export declare const PICKER_FOOTER = "\u2191\u2193 \u9009\u62E9 \u00B7 Enter \u786E\u8BA4 \u00B7 Esc \u53D6\u6D88";
27
43
  /** 打开一个居中选择器;Enter 返回选中项,Esc / Ctrl+C 返回 undefined。 */
28
44
  export declare function openPicker(host: PickerHost, spec: PickerSpec): Promise<SelectItem | undefined>;
29
- export declare function permissionItems(): SelectItem[];
45
+ /**
46
+ * 模式选择器(标题「权限模式」):界面顺序、当前模式打勾(`currentValue`)、配置里的缺省模式标
47
+ * `Default`、Auto 标 `Recommended`,右侧数字快捷键 1–6,说明在下一行。
48
+ */
49
+ export declare function permissionItems(_current: PermissionMode, configDefault?: PermissionMode): SelectItem[];
50
+ export declare function permissionPickerSpec(current: PermissionMode, configDefault?: PermissionMode): PickerSpec;
30
51
  export declare function thinkingItems(reasoning: boolean): SelectItem[];
31
52
  export interface TreeNode {
32
53
  entry: SessionEntry;