@uncarved/jade 0.3.1 → 0.4.1

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 (206) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +490 -29
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +36 -14
  14. package/plugins/approval/policy.ts +15 -10
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +42 -9
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +47 -12
  50. package/plugins/models/index.ts +27 -1
  51. package/plugins/models/provider.ts +24 -0
  52. package/plugins/models/saved.ts +1 -1
  53. package/plugins/modes/index.ts +13 -2
  54. package/plugins/print/index.ts +7 -4
  55. package/plugins/prompts/index.ts +0 -0
  56. package/plugins/renderers/index.ts +10 -5
  57. package/plugins/repeats/index.ts +8 -8
  58. package/plugins/schedule/index.ts +5 -1
  59. package/plugins/screenshot/browser.ts +10 -0
  60. package/plugins/sessions/index.ts +48 -2
  61. package/plugins/shell/index.ts +27 -28
  62. package/plugins/shell/plugin.json +1 -1
  63. package/plugins/shell/renderers.ts +9 -7
  64. package/plugins/shell/shell.ts +3 -1
  65. package/plugins/skills/index.ts +28 -19
  66. package/plugins/skills/project.ts +12 -7
  67. package/plugins/steer/index.ts +5 -4
  68. package/plugins/task/index.ts +80 -50
  69. package/plugins/task/plugin.json +6 -2
  70. package/plugins/task/style.ts +13 -14
  71. package/plugins/task/subagent.ts +67 -184
  72. package/plugins/todo/index.ts +39 -9
  73. package/plugins/tools/index.ts +9 -2
  74. package/plugins/tui/frontend.ts +139 -89
  75. package/plugins/tui/index.ts +2 -3
  76. package/plugins/tui/mentions.ts +11 -80
  77. package/plugins/tui/plugin.json +1 -1
  78. package/plugins/tui/screen.ts +55 -5
  79. package/plugins/tui/transcript.ts +17 -7
  80. package/plugins/tui/tui.ts +337 -101
  81. package/plugins/tui/vendor.ts +1 -1
  82. package/plugins/undo/checkpoint.ts +8 -4
  83. package/plugins/undo/index.ts +170 -31
  84. package/plugins/undo/plugin.json +1 -0
  85. package/plugins/undo/snapshot.ts +87 -14
  86. package/plugins/undo/style.ts +13 -14
  87. package/plugins/web/index.ts +7 -18
  88. package/plugins/web/plugin.json +1 -1
  89. package/plugins-dist/approval/index.js +363 -418
  90. package/plugins-dist/approval/policy.js +391 -508
  91. package/plugins-dist/approval/review.js +132 -158
  92. package/plugins-dist/approval/schema.js +50 -55
  93. package/plugins-dist/ask/index.js +115 -129
  94. package/plugins-dist/budget/index.js +27 -31
  95. package/plugins-dist/checks/checks.js +293 -329
  96. package/plugins-dist/checks/index.js +119 -139
  97. package/plugins-dist/checks/plugin.json +2 -1
  98. package/plugins-dist/checks/project.js +57 -65
  99. package/plugins-dist/commands/index.js +47 -29
  100. package/plugins-dist/compact/compact.js +233 -249
  101. package/plugins-dist/compact/index.js +98 -95
  102. package/plugins-dist/compact/style.js +9 -14
  103. package/plugins-dist/completions/index.js +30 -0
  104. package/plugins-dist/completions/plugin.json +9 -0
  105. package/plugins-dist/continue/index.js +40 -52
  106. package/plugins-dist/copy/index.js +40 -0
  107. package/plugins-dist/copy/plugin.json +9 -0
  108. package/plugins-dist/cost/index.js +98 -115
  109. package/plugins-dist/custom-commands/index.js +55 -72
  110. package/plugins-dist/editor/index.js +64 -72
  111. package/plugins-dist/fs/diff.js +111 -124
  112. package/plugins-dist/fs/fs.js +426 -469
  113. package/plugins-dist/fs/grep.js +262 -253
  114. package/plugins-dist/fs/index.js +20 -34
  115. package/plugins-dist/fs/plugin.json +1 -2
  116. package/plugins-dist/fs/renderers.js +100 -112
  117. package/plugins-dist/fs/style.js +11 -15
  118. package/plugins-dist/fs/sys.js +31 -43
  119. package/plugins-dist/hooks/index.js +107 -127
  120. package/plugins-dist/keys/index.js +27 -31
  121. package/plugins-dist/mcp/index.js +271 -199
  122. package/plugins-dist/mcp/install.js +123 -137
  123. package/plugins-dist/mcp/mcp.js +638 -577
  124. package/plugins-dist/mcp/plugin.json +3 -1
  125. package/plugins-dist/mcp/project.js +98 -115
  126. package/plugins-dist/memory/index.js +83 -88
  127. package/plugins-dist/memory/memory.js +111 -128
  128. package/plugins-dist/memory/style.js +9 -14
  129. package/plugins-dist/mentions/attach.js +91 -99
  130. package/plugins-dist/mentions/candidates.js +49 -0
  131. package/plugins-dist/mentions/index.js +71 -81
  132. package/plugins-dist/mentions/plugin.json +2 -1
  133. package/plugins-dist/mentions/style.js +9 -14
  134. package/plugins-dist/models/config.js +29 -43
  135. package/plugins-dist/models/configure.js +421 -474
  136. package/plugins-dist/models/context.js +14 -22
  137. package/plugins-dist/models/index.js +182 -189
  138. package/plugins-dist/models/provider.js +263 -307
  139. package/plugins-dist/models/saved.js +60 -72
  140. package/plugins-dist/modes/index.js +138 -165
  141. package/plugins-dist/plugins/index.js +34 -34
  142. package/plugins-dist/print/index.js +192 -175
  143. package/plugins-dist/prompts/index.js +86 -89
  144. package/plugins-dist/prompts/notes.js +31 -37
  145. package/plugins-dist/prompts/prompts.js +155 -193
  146. package/plugins-dist/prompts/results.js +40 -53
  147. package/plugins-dist/prompts/sys.js +39 -50
  148. package/plugins-dist/renderers/index.js +32 -32
  149. package/plugins-dist/repeats/index.js +131 -174
  150. package/plugins-dist/schedule/cron.js +49 -56
  151. package/plugins-dist/schedule/index.js +230 -247
  152. package/plugins-dist/schedule/store.js +93 -109
  153. package/plugins-dist/scratch/index.js +12 -18
  154. package/plugins-dist/screenshot/browser.js +136 -154
  155. package/plugins-dist/screenshot/index.js +37 -46
  156. package/plugins-dist/screenshot/sys.js +53 -65
  157. package/plugins-dist/screenshot/tool.js +98 -126
  158. package/plugins-dist/sessions/index.js +149 -117
  159. package/plugins-dist/shell/index.js +117 -135
  160. package/plugins-dist/shell/plugin.json +1 -1
  161. package/plugins-dist/shell/renderers.js +28 -33
  162. package/plugins-dist/shell/service.js +17 -23
  163. package/plugins-dist/shell/shell.js +307 -362
  164. package/plugins-dist/shell/sys.js +64 -79
  165. package/plugins-dist/skills/index.js +193 -211
  166. package/plugins-dist/skills/install.js +122 -149
  167. package/plugins-dist/skills/project.js +65 -73
  168. package/plugins-dist/skills/skills.js +135 -171
  169. package/plugins-dist/steer/index.js +108 -125
  170. package/plugins-dist/suggest/index.js +235 -259
  171. package/plugins-dist/task/index.js +130 -117
  172. package/plugins-dist/task/plugin.json +5 -2
  173. package/plugins-dist/task/style.js +9 -14
  174. package/plugins-dist/task/subagent.js +156 -279
  175. package/plugins-dist/todo/index.js +79 -63
  176. package/plugins-dist/tools/index.js +36 -42
  177. package/plugins-dist/tui/editor.js +145 -160
  178. package/plugins-dist/tui/frontend.js +639 -678
  179. package/plugins-dist/tui/history.js +34 -37
  180. package/plugins-dist/tui/index.js +16 -18
  181. package/plugins-dist/tui/markdown.js +203 -247
  182. package/plugins-dist/tui/mascot.js +266 -355
  183. package/plugins-dist/tui/mentions.js +67 -144
  184. package/plugins-dist/tui/plugin.json +1 -2
  185. package/plugins-dist/tui/render.js +35 -45
  186. package/plugins-dist/tui/screen.js +197 -180
  187. package/plugins-dist/tui/transcript.js +436 -468
  188. package/plugins-dist/tui/tui.js +1554 -1656
  189. package/plugins-dist/tui/vendor.js +1088 -1388
  190. package/plugins-dist/undo/checkpoint.js +97 -118
  191. package/plugins-dist/undo/index.js +281 -192
  192. package/plugins-dist/undo/plugin.json +3 -0
  193. package/plugins-dist/undo/snapshot.js +134 -99
  194. package/plugins-dist/undo/style.js +9 -14
  195. package/plugins-dist/update/index.js +26 -28
  196. package/plugins-dist/web/env.js +55 -68
  197. package/plugins-dist/web/index.js +80 -110
  198. package/plugins-dist/web/plugin.json +1 -2
  199. package/plugins-dist/web/renderers.js +4 -5
  200. package/plugins-dist/web/web.js +514 -593
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +9 -2
  203. package/src/api.ts +1 -1
  204. package/src/host.ts +39 -4
  205. package/src/remote.ts +6 -1
  206. package/src/session.ts +496 -36
@@ -1,19 +1,19 @@
1
1
  // jade/tui 的前端:把会话接到终端界面上。旧 jade 的 main.ts 里属于界面的部分:
2
2
  // 输入排队、斜杠命令、esc 中断、换会话后重新显示对话、状态栏。
3
3
  //
4
- // 这里不认识任何具体功能:命令来自 commands@1,快捷键来自 keys@1,工具和事件怎么显示来自 renderers@1,
5
- // 模式来自 modes@1,模型名来自 models@1。
4
+ // 这里不认识任何具体功能:命令和它们的简写(例如 jade/shell 的 !)来自 commands@1,快捷键来自 keys@1,
5
+ // 输入框的补全(例如 jade/mentions 的 @)来自 completions@1,工具和事件怎么显示来自 renderers@1,模型名来自 models@1;
6
+ // 状态栏上的模式、压缩阈值是 jade/modes、jade/compact 自己的段落(ctx.status)。
6
7
 
7
8
  import { execFile } from "node:child_process";
8
9
  import { readFileSync } from "node:fs";
9
10
  import os from "node:os";
10
11
  import path from "node:path";
11
12
  import type { Block } from "uncarved";
12
- import type { Frontend, OpenOptions, Session, SessionManager, SessionUI, UI } from "@uncarved/jade-api";
13
- import type { CommandContext, Commands, Compact, Keys, Models, Modes, Renderers, SessionIndex, Steer } from "@uncarved/jade-api/services";
13
+ import type { Frontend, OpenOptions, Session, SessionManager, SessionUI, StatusSegment, Text, UI } from "@uncarved/jade-api";
14
+ import type { CommandContext, Commands, Completions, EventRenderer, Keys, Models, Renderers, SessionIndex, Steer, ToolRenderer } from "@uncarved/jade-api/services";
14
15
  import { InputHistory } from "./history.ts";
15
- import { mentionCandidates } from "./mentions.ts";
16
- import { dim, red, safeScreen, yellow, type CommandInfo, type Screen } from "./screen.ts";
16
+ import { ansi, dim, red, safeScreen, yellow, type CommandInfo, type CompletionInfo, type Screen } from "./screen.ts";
17
17
  import { transcript, type Transcript } from "./transcript.ts";
18
18
 
19
19
  /**
@@ -45,12 +45,51 @@ jade's own commands (plugins, update, --safe): jade help`;
45
45
  /** 前端自己的命令:帮助和退出。其余命令都来自 commands@1 */
46
46
  const OWN: CommandInfo[] = [
47
47
  { name: "help", about: "list the commands and keys" },
48
- { name: "copy", args: "[code]", about: "copy the last reply to the clipboard as it was written (code: only its last code block)" },
49
48
  { name: "exit", about: "quit (the session stays resumable)" },
50
49
  ];
51
50
 
52
- const KEYS =
53
- "Keys: enter send · !<command> runs a shell command yourself · ctrl+j, alt+enter or \\ then enter: new line · ↑↓ history · esc interrupt (twice to also move queued messages back to the input) · ↑ on the first line edits queued messages · ctrl+o expand · ctrl+c twice to exit";
51
+ const KEYS = [
52
+ "Keys:",
53
+ " send enter send · ctrl+j, alt+enter or \\ then enter: new line · tab completes /commands",
54
+ " input ↑↓ history · ctrl+r search history · ↑ on the first line edits queued messages · esc twice or ctrl+c clears the input",
55
+ " editing ctrl+←/→ or alt+b/f move by words · ctrl+w or alt+backspace delete a word · ctrl+a/e line start/end · ctrl+u/k delete to start/end",
56
+ " running esc interrupt (twice to also move queued messages back to the input) · ctrl+c twice to exit",
57
+ " transcript pgup/pgdn scroll · ctrl+home/end top/bottom · ctrl+o expands the latest item, a click the one under it · drag to select and copy · ctrl+l redraw",
58
+ ].join("\n");
59
+
60
+ /** Text 画成终端里的样子;没有就是没有 */
61
+ const paint = (v: Text | undefined | null): string | undefined => (v === undefined || v === null ? undefined : ansi(v));
62
+
63
+ /** 插件的显示方式给的是带样式的文字(Text):交给对话区之前画成终端里的样子,对话区只管字符串 */
64
+ function ansiTool(r: ToolRenderer): ToolRenderer {
65
+ const out: ToolRenderer = { tool: r.tool };
66
+ if (r.summary) out.summary = (i) => paint(r.summary!(i));
67
+ if (r.details) out.details = (i) => paint(r.details!(i));
68
+ if (r.call) out.call = (i) => paint(r.call!(i));
69
+ if (r.progress) out.progress = (u, c) => paint(r.progress!(u, c));
70
+ if (r.preview) out.preview = async (i) => paint(await r.preview!(i));
71
+ if (r.before) out.before = (i) => r.before!(i);
72
+ if (r.result)
73
+ out.result = (x) => {
74
+ const o = r.result!(x);
75
+ return o ? { line: ansi(o.line), ...(o.details !== undefined ? { details: ansi(o.details) } : {}) } : o;
76
+ };
77
+ return out;
78
+ }
79
+
80
+ function ansiEvent(r: EventRenderer): EventRenderer {
81
+ return {
82
+ event: r.event,
83
+ render: (data) => {
84
+ const o = r.render(data);
85
+ return o && { line: ansi(o.line), ...(o.details !== undefined ? { details: ansi(o.details) } : {}) };
86
+ },
87
+ };
88
+ }
89
+
90
+ /** 命令返回的是"作为用户消息发给模型"({ prompt }),不是要显示的文字 */
91
+ const isPrompt = (r: unknown): r is { prompt: string } =>
92
+ typeof r === "object" && r !== null && !Array.isArray(r) && typeof (r as { prompt?: unknown }).prompt === "string";
54
93
 
55
94
  /** 退出时最多等正在做的事这么久 */
56
95
  const QUIT_WAIT_MS = 3000;
@@ -84,10 +123,9 @@ export interface FrontendServices {
84
123
  commands: Commands;
85
124
  keys: Keys;
86
125
  renderers: Renderers;
87
- modes?: Modes;
88
126
  models?: Models;
89
- /** 自动压缩的阈值,状态栏显示 */
90
- compact?: Compact;
127
+ /** 输入框的补全(completions@1) */
128
+ completions?: Completions;
91
129
  /** 会话索引(jade/sessions),--continue 用 */
92
130
  index?: SessionIndex;
93
131
  /** 一轮中途说的话(jade/steer):有它时,模型工作中提交的消息在下一次请求模型时就交给它,不等这一轮结束 */
@@ -96,6 +134,10 @@ export interface FrontendServices {
96
134
 
97
135
  /** 状态栏上插件的一段最多显示这么多字符(超出的截断,换行并成空格) */
98
136
  const MAX_SEGMENT = 80;
137
+ /** 状态栏的一段(文字或带颜色、优先级的 StatusSegment) */
138
+ type Segment = string | StatusSegment;
139
+ /** 输入框上方插件的一块最多占几行 */
140
+ const MAX_PANEL_LINES = 10;
99
141
 
100
142
  /**
101
143
  * ui@1:界面出来之前的提示先攒着,出来之后显示;界面关掉之后写到 stderr。
@@ -107,8 +149,10 @@ export class ScreenBridge {
107
149
  /** 会话打开期间的提示:打开之后要清屏,先攒着,清屏之后再显示 */
108
150
  #held: string[] | undefined;
109
151
  #closed = false;
110
- /** 状态栏上各插件的一段:会话 id → 插件 id → 文字 */
111
- #segments = new Map<string, Map<string, string>>();
152
+ /** 状态栏上各插件的一段:会话 id → 插件 id → 段落 */
153
+ #segments = new Map<string, Map<string, Segment>>();
154
+ /** 输入框上方各插件的一块:会话 id → 插件 id → 文字 */
155
+ #panels = new Map<string, Map<string, string>>();
112
156
  /** 界面现在显示哪个会话;换会话时由前端调用 show */
113
157
  #session: string | undefined;
114
158
 
@@ -123,7 +167,7 @@ export class ScreenBridge {
123
167
  },
124
168
  select: async (req, signal) => {
125
169
  if (!this.screen) return undefined;
126
- return this.screen.select(req.title, req.options.map((o) => ({ label: o.label, value: o.value, ...(o.hint ? { hint: o.hint } : {}) })), { ...(req.detail ? { body: req.detail } : {}), ...(signal ? { signal } : {}) });
170
+ return this.screen.select(req.title, req.options.map((o) => ({ label: o.label, value: o.value, ...(o.hint ? { hint: o.hint } : {}) })), { ...(req.detail ? { body: ansi(req.detail) } : {}), ...(signal ? { signal } : {}) });
127
171
  },
128
172
  input: async (req, signal) => {
129
173
  if (!this.screen) return undefined;
@@ -173,7 +217,11 @@ export class ScreenBridge {
173
217
  #apply(): void {
174
218
  if (!this.screen) return;
175
219
  const segments = this.#session === undefined ? undefined : this.#segments.get(this.#session);
176
- this.screen.status({ plugins: [...(segments ?? [])].map(([plugin, text]) => ({ plugin, text })) });
220
+ const panels = this.#session === undefined ? undefined : this.#panels.get(this.#session);
221
+ this.screen.status({
222
+ plugins: [...(segments ?? [])].map(([plugin, text]) => ({ plugin, text })),
223
+ panels: [...(panels ?? [])].map(([plugin, text]) => ({ plugin, text })),
224
+ });
177
225
  }
178
226
 
179
227
  /** 一个插件在一个会话里的界面。作用域关闭时核心调用 dispose,这里把它的段落去掉 */
@@ -183,18 +231,20 @@ export class ScreenBridge {
183
231
  const apply = () => {
184
232
  if (bridge.#session === session) bridge.#apply();
185
233
  };
234
+ const put = <T>(all: Map<string, Map<string, T>>, text: T | undefined) => {
235
+ if (gone) return;
236
+ // 每次现取:别的插件 dispose 可能已经把空的 map 删了
237
+ let mine = all.get(session);
238
+ if (text === undefined) mine?.delete(plugin);
239
+ else {
240
+ if (!mine) all.set(session, (mine = new Map()));
241
+ mine.set(plugin, text);
242
+ }
243
+ apply();
244
+ };
186
245
  return {
187
- status(text) {
188
- if (gone) return;
189
- // 每次现取:别的插件 dispose 可能已经把空的 map 删了
190
- let segments = bridge.#segments.get(session);
191
- if (text === undefined) segments?.delete(plugin);
192
- else {
193
- if (!segments) bridge.#segments.set(session, (segments = new Map()));
194
- segments.set(plugin, clipSegment(text));
195
- }
196
- apply();
197
- },
246
+ status: (text) => put(bridge.#segments, text === undefined ? undefined : clipSegment(text)),
247
+ panel: (text) => put(bridge.#panels, text === undefined ? undefined : clipPanel(ansi(text))),
198
248
  draft: {
199
249
  text: () => bridge.screen?.draft?.text() ?? "",
200
250
  insert: (text) => bridge.screen?.draft?.insert(text),
@@ -203,19 +253,31 @@ export class ScreenBridge {
203
253
  },
204
254
  dispose() {
205
255
  gone = true;
206
- const segments = bridge.#segments.get(session);
207
- segments?.delete(plugin);
208
- if (segments?.size === 0) bridge.#segments.delete(session);
256
+ for (const all of [bridge.#segments, bridge.#panels]) {
257
+ const mine = all.get(session);
258
+ mine?.delete(plugin);
259
+ if (mine?.size === 0) all.delete(session);
260
+ }
209
261
  apply();
210
262
  },
211
263
  };
212
264
  }
213
265
  }
214
266
 
267
+ /** 输入框上方的一块最多这么多行,多出的最后一行写成还有几行;每行在界面里按宽度截断 */
268
+ function clipPanel(text: string): string {
269
+ const lines = String(text).replace(/\r\n?/g, "\n").replace(/\n+$/, "").split("\n");
270
+ return lines.length > MAX_PANEL_LINES ? [...lines.slice(0, MAX_PANEL_LINES - 1), ` … ${lines.length - MAX_PANEL_LINES + 1} more`].join("\n") : lines.join("\n");
271
+ }
272
+
215
273
  /** 状态栏的一段是一行:空白并成一个空格,长的截断 */
216
- function clipSegment(text: string): string {
217
- const one = String(text).replace(/\s+/g, " ").trim();
218
- return one.length > MAX_SEGMENT ? `${one.slice(0, MAX_SEGMENT - 1)}…` : one;
274
+ function clipSegment(segment: Segment): Segment {
275
+ const clip = (text: string) => {
276
+ const one = String(text).replace(/\s+/g, " ").trim();
277
+ return one.length > MAX_SEGMENT ? `${one.slice(0, MAX_SEGMENT - 1)}…` : one;
278
+ };
279
+ if (typeof segment === "string") return clip(segment);
280
+ return { ...segment, text: clip(segment.text), ...(segment.short !== undefined ? { short: clip(segment.short) } : {}) };
219
281
  }
220
282
 
221
283
  export function tuiFrontend(services: FrontendServices, bridge: ScreenBridge): Frontend {
@@ -259,7 +321,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
259
321
  return 2;
260
322
  }
261
323
 
262
- const { cwd, home, commands, keys, renderers, modes, models, compact, index, steer } = services;
324
+ const { cwd, home, commands, keys, renderers, models, completions, index, steer } = services;
263
325
  const sessions = opts.sessions;
264
326
  // --continue:这个目录里最近用过的会话(索引由 jade/sessions 在收到第一条消息时写)
265
327
  if (args.cont && !index) {
@@ -280,8 +342,16 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
280
342
  ...commands
281
343
  .list()
282
344
  .filter((c) => !OWN.some((o) => o.name === c.name))
283
- .map((c) => ({ name: c.name, ...(c.args ? { args: c.args } : {}), about: `${c.description ?? ""}${c.plugin.startsWith("jade/") ? "" : ` (plugin ${c.plugin})`}`.trim() })),
345
+ .map((c) => ({
346
+ name: c.name,
347
+ ...(c.args ? { args: c.args } : {}),
348
+ ...(c.prefix ? { prefix: c.prefix, ...(c.prefixHint ? { prefixHint: c.prefixHint } : {}) } : {}),
349
+ about: `${c.description ?? ""}${c.plugin.startsWith("jade/") ? "" : ` (plugin ${c.plugin})`}`.trim(),
350
+ })),
284
351
  ];
352
+ /** 输入框的补全:每次渲染时取(插件可能刚登记或撤销) */
353
+ const completionList = (): CompletionInfo[] =>
354
+ (completions?.list() ?? []).map(({ completion: c }) => ({ trigger: c.trigger, label: c.label, ...(c.hint ? { hint: c.hint } : {}) }));
285
355
 
286
356
  let ready = false;
287
357
  const early: string[] = [];
@@ -291,7 +361,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
291
361
  // 插件、工具输出和模型的文字都经过 safeScreen 显示:只留颜色,去掉能搅乱终端的控制序列
292
362
  const screen: Screen = safeScreen(
293
363
  tuiScreen({
294
- status: { cwd: shortPath(cwd), ...(branch ? { branch } : {}), model: models?.current()?.model ?? "(no model)", mode: modes?.current() ?? "" },
364
+ status: { cwd: shortPath(cwd), ...(branch ? { branch } : {}), model: models?.current()?.model ?? "(no model)" },
295
365
  version: VERSION,
296
366
  commands: commandList,
297
367
  history: past,
@@ -302,12 +372,12 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
302
372
  if (ready) onSubmit(text);
303
373
  else early.push(text);
304
374
  },
305
- // 输入 @ 时列工作目录里的文件
306
- files: () => mentionCandidates(cwd),
375
+ // 打了补全的触发字符(例如 @)时向登记它的插件要候选
376
+ completions: completionList,
377
+ complete: async (trigger) => (await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates()) ?? [],
307
378
  interrupt: () => ready && interrupt(),
308
379
  unqueue: () => takeBack(),
309
380
  exit: () => void quit(0),
310
- cycleMode: () => void key("shift+tab"),
311
381
  key: (spec) => key(spec),
312
382
  },
313
383
  }),
@@ -328,7 +398,6 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
328
398
  return true;
329
399
  }
330
400
 
331
- const offMode = modes?.subscribe((mode) => screen.status({ mode }));
332
401
  // /model 换了配置:状态栏跟着换
333
402
  const offModel = models?.subscribe?.(() => screen.status({ model: models.current()?.model ?? "(no model)" }));
334
403
 
@@ -343,10 +412,15 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
343
412
  cwd,
344
413
  contextWindow: () => models?.current()?.contextWindow ?? 0,
345
414
  maxTokens: () => models?.current()?.maxTokens,
346
- ...(compact ? { compactAt: () => compact.threshold() } : {}),
347
415
  canRetry,
348
- renderer: (tool) => renderers.forTool(tool),
349
- eventRenderer: (type) => renderers.forEvent(type),
416
+ renderer: (tool) => {
417
+ const found = renderers.forTool(tool);
418
+ return found && { plugin: found.plugin, renderer: ansiTool(found.renderer) };
419
+ },
420
+ eventRenderer: (type) => {
421
+ const found = renderers.forEvent(type);
422
+ return found && { plugin: found.plugin, renderer: ansiEvent(found.renderer) };
423
+ },
350
424
  });
351
425
 
352
426
  /** 换成另一个会话:清屏,恢复的会话重新显示之前的对话,然后继续日志里没做完的工作 */
@@ -391,7 +465,8 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
391
465
  bridge.hold();
392
466
  try {
393
467
  const s = await sessions.open(o);
394
- await adopt(s, o?.resume !== undefined);
468
+ // 复制出的会话(/rewind)和恢复的一样:重新显示已有的对话
469
+ await adopt(s, o?.resume !== undefined || o?.fork !== undefined);
395
470
  return s;
396
471
  } finally {
397
472
  bridge.release();
@@ -518,7 +593,6 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
518
593
  for (const ac of commandAborts) ac.abort(new Error("exiting"));
519
594
  await Promise.race([work?.catch(() => {}), new Promise((r) => setTimeout(r, QUIT_WAIT_MS))]);
520
595
  keyAbort.abort(new Error("exiting"));
521
- offMode?.();
522
596
  offModel?.();
523
597
  offSteer?.();
524
598
  unsubscribe?.();
@@ -553,23 +627,18 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
553
627
  const rest = input.slice(1).replace(/^\S+\s*/, "");
554
628
  if (name === "exit" || name === "quit") return false;
555
629
  if (name === "help") {
630
+ // 快捷键在前、命令在后:屏幕放不下时,紧挨着输入框的命令列表还看得见
631
+ // 命令的简写、输入框的补全来自插件,跟着列出来
632
+ const extras = [
633
+ ...commands.list().flatMap((c) => (c.prefix ? [`${c.prefix}${c.args ?? ""} is /${c.name}`] : [])),
634
+ ...completionList().map((c) => `${c.trigger} completes ${c.label}`),
635
+ ];
636
+ screen.log(dim(extras.length ? `${KEYS}\n plugins ${extras.join(" · ")}` : KEYS));
637
+ const pluginKeys = keys.list();
638
+ if (pluginKeys.length > 0) screen.log(dim(`Plugin keys: ${pluginKeys.map((k) => `${k.key}${k.description ? ` ${k.description}` : ""} (${k.plugin})`).join(" · ")}`));
556
639
  const all = commandList();
557
640
  const width = Math.max(...all.map((c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`.length)) + 2;
558
641
  screen.log(all.map((c) => `${`/${c.name}${c.args ? ` ${c.args}` : ""}`.padEnd(width)}${dim(c.about)}`).join("\n"));
559
- screen.log(dim(KEYS));
560
- const pluginKeys = keys.list();
561
- if (pluginKeys.length > 0) screen.log(dim(`Plugin keys: ${pluginKeys.map((k) => `${k.key}${k.description ? ` ${k.description}` : ""} (${k.plugin})`).join(" · ")}`));
562
- return true;
563
- }
564
- if (name === "copy") {
565
- const reply = lastReply(current?.state.messages ?? []);
566
- const text = rest.trim() === "code" ? reply && lastCodeBlock(reply) : reply;
567
- if (!text) screen.log(dim(rest.trim() === "code" ? "The last reply has no code block." : "There is no reply to copy yet."));
568
- else if (!screen.copy) screen.log(red("[error] this terminal cannot copy"));
569
- else {
570
- screen.copy(text);
571
- screen.log(dim(`[copied ${[...text].length} characters]`));
572
- }
573
642
  return true;
574
643
  }
575
644
  const found = commands.get(name);
@@ -580,7 +649,8 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
580
649
  const ac = new AbortController();
581
650
  commandAborts.add(ac);
582
651
  // 命令的临时显示:末尾几行,每行占进度区的一行
583
- const showLive = (text: string | undefined) => {
652
+ const showLive = (live: Text | undefined) => {
653
+ const text = live === undefined ? undefined : ansi(live);
584
654
  const lines = text?.replace(/\r\n?/g, "\n").trimEnd().split("\n").slice(-LIVE_ROWS) ?? [];
585
655
  for (let i = 0; i < LIVE_ROWS; i++) screen.progress(`command:${i}`, text !== undefined && i < lines.length ? dim(` │ ${lines[i]}`) : undefined);
586
656
  };
@@ -588,16 +658,15 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
588
658
  signal: ac.signal,
589
659
  ui: bridge.ui,
590
660
  sessions: manager,
591
- print: (t, o) => screen.log(t, o?.details ? { details: o.details } : undefined),
661
+ print: (t, o) => screen.log(ansi(t), o?.details ? { details: ansi(o.details) } : undefined),
592
662
  progress: showLive,
593
663
  };
594
664
  try {
595
665
  const result = await found.command.run(rest, ctx);
596
- if (typeof result === "string") screen.log(result);
597
- else if (result && typeof result === "object" && typeof result.prompt === "string") {
666
+ if (isPrompt(result)) {
598
667
  if (found.command.instant) screen.log(yellow(`[warning] /${name} is instant and cannot send a prompt`));
599
668
  else await say(result.prompt);
600
- }
669
+ } else if (result !== undefined && result !== null) screen.log(ansi(result));
601
670
  } catch (e) {
602
671
  if (!ac.signal.aborted) screen.log(red(`[error] /${name}: ${errorText(e)}`));
603
672
  } finally {
@@ -609,8 +678,10 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
609
678
 
610
679
  function onSubmit(text: string) {
611
680
  if (quitting) return;
612
- // !<命令> 是 /sh <命令> 的简写(jade/shell 提供):用户自己执行,不经过模型
613
- if (/^!\s*\S/.test(text)) text = `/sh ${text.slice(1).trim()}`;
681
+ // 命令的简写(例如 jade/shell 的 !<命令> 就是 /sh <命令>)
682
+ const short = [...text][0];
683
+ const byPrefix = short === undefined ? undefined : commands.byPrefix(short);
684
+ if (byPrefix && text.slice(short!.length).trim()) text = `/${byPrefix.command.name} ${text.slice(short!.length).trim()}`;
614
685
  const name = commandName(text);
615
686
  if (name !== undefined && instant(name)) {
616
687
  // 不碰会话的命令运行中也直接执行
@@ -681,12 +752,8 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
681
752
  } catch (e) {
682
753
  screen.log(red(`[error] ${errorText(e)}`));
683
754
  }
684
- if (!models?.current()) {
685
- // /model(jade/models 提供)当场就能配好,不用重启;没有这条命令时只能改文件
686
- const file = `put ANTHROPIC_API_KEY=... (or OPENAI_API_KEY=...) in ${path.join(home, ".env")}, then restart jade`;
687
- screen.log(yellow(commands.list().some((c) => c.name === "model") ? `No model is configured yet. Type /model to set one up, or ${file}.` : `No model is configured yet. To set one up, ${file}.`));
688
- }
689
- else if (!resumed) screen.log(dim("Type / for commands, esc to interrupt."));
755
+ // 没配模型时怎么配由模型插件自己说(jade/models 在会话打开时提示)
756
+ if (models?.current() && !resumed) screen.log(dim("Type / for commands, esc to interrupt."));
690
757
  ready = true;
691
758
  for (const text of [...(args.prompt ? [args.prompt] : []), ...early.splice(0)]) onSubmit(text);
692
759
 
@@ -694,23 +761,6 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
694
761
  }
695
762
 
696
763
  /** 当前分支;不在仓库里或没有 git 时 undefined */
697
- /** 最近一条有正文的助手消息的正文(模型写的原文,没有折行和排版) */
698
- export function lastReply(messages: readonly { role: string; content: readonly Block[] }[]): string | undefined {
699
- for (let i = messages.length - 1; i >= 0; i--) {
700
- const m = messages[i]!;
701
- if (m.role !== "assistant") continue;
702
- const text = m.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim();
703
- if (text) return text;
704
- }
705
- return undefined;
706
- }
707
-
708
- /** Markdown 里最后一个围栏代码块的内容 */
709
- export function lastCodeBlock(markdown: string): string | undefined {
710
- const blocks = [...markdown.matchAll(/^ {0,3}(`{3,}|~{3,})[^\n]*\n([\s\S]*?)^ {0,3}\1[`~]*[ \t]*$/gm)];
711
- return blocks.at(-1)?.[2]?.replace(/\n$/, "");
712
- }
713
-
714
764
  function gitBranch(cwd: string): Promise<string | undefined> {
715
765
  return new Promise((resolve) => {
716
766
  execFile("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd, timeout: 2000, windowsHide: true }, (err, stdout) => resolve(err ? undefined : stdout.trim() || undefined));
@@ -1,7 +1,7 @@
1
1
  // jade/tui:终端界面,默认的前端。提供 frontend@1 和 ui@1;命令、快捷键、显示方式都来自注册表插件。
2
2
 
3
3
  import { definePlugin } from "@uncarved/jade-api";
4
- import type { Commands, Compact, Keys, Models, Modes, Renderers, SessionIndex, Steer } from "@uncarved/jade-api/services";
4
+ import type { Commands, Completions, Keys, Models, Renderers, SessionIndex, Steer } from "@uncarved/jade-api/services";
5
5
  import { ScreenBridge, tuiFrontend } from "./frontend.ts";
6
6
 
7
7
  export default definePlugin({
@@ -17,9 +17,8 @@ export default definePlugin({
17
17
  commands: ctx.require<Commands>("commands@1"),
18
18
  keys: ctx.require<Keys>("keys@1"),
19
19
  renderers: ctx.require<Renderers>("renderers@1"),
20
- ...optional("modes", ctx.service<Modes>("modes@1")),
21
20
  ...optional("models", ctx.service<Models>("models@1")),
22
- ...optional("compact", ctx.service<Compact>("compact@1")),
21
+ ...optional("completions", ctx.service<Completions>("completions@1")),
23
22
  ...optional("index", ctx.service<SessionIndex>("sessions@1")),
24
23
  ...optional("steer", ctx.service<Steer>("steer@1")),
25
24
  },
@@ -1,22 +1,17 @@
1
- // @ 引用文件的补全:输入框里打 @ 时找出光标处正在输入的路径、给候选路径排序。
2
- // 候选从工作目录来(git 仓库里只看版本控制的,和 glob 一样),发送时附上文件内容由 jade/mentions 负责。
3
-
4
- import { execFile } from "node:child_process";
5
- import { readdir } from "node:fs/promises";
6
- import path from "node:path";
7
-
8
- /** 候选(文件加目录)最多这么多,再多也只是拖慢补全 */
9
- const MAX_CANDIDATES = 20_000;
10
-
11
- /** 光标正在输入的 @ 引用:@ 的下标和已经输入的部分;不在引用里时返回 undefined */
12
- export function mentionAt(value: string, cursor: number): { start: number; query: string } | undefined {
13
- const m = /(?:^|\s)@("?[^\s"]*)$/.exec(value.slice(0, cursor));
1
+ // 输入框里的补全(completions@1,例如 jade/mentions 的 @ 文件):找出光标处正在输入的那一段、给候选排序。
2
+ // 候选从登记的插件来,发送之后拿它做什么也归它;这里只认触发字符,不知道候选是什么。
3
+
4
+ /** 光标正在输入的补全:触发字符、它的下标和已经输入的部分;不在补全里时返回 undefined。triggers 是登记了的触发字符 */
5
+ export function mentionAt(value: string, cursor: number, triggers: readonly string[]): { trigger: string; start: number; query: string } | undefined {
6
+ if (triggers.length === 0) return undefined;
7
+ const chars = triggers.map((t) => t.replace(/[\\^\]\-]/g, "\\$&")).join("");
8
+ const m = new RegExp(`(?:^|\\s)([${chars}])("?[^\\s"]*)$`, "u").exec(value.slice(0, cursor));
14
9
  if (!m) return undefined;
15
- return { start: cursor - m[1]!.length - 1, query: m[1]!.replace(/^"/, "") };
10
+ return { trigger: m[1]!, start: cursor - m[2]!.length - m[1]!.length, query: m[2]!.replace(/^"/, "") };
16
11
  }
17
12
 
18
- /** 补全后的文本:@ 引用加一个空格,含空白的路径加引号 */
19
- export const mentionText = (p: string) => (/\s/.test(p) ? `@"${p}"` : `@${p}`);
13
+ /** 补全后的文本:触发字符加候选,含空白的加引号 */
14
+ export const mentionText = (trigger: string, p: string) => (/\s/.test(p) ? `${trigger}"${p}"` : `${trigger}${p}`);
20
15
 
21
16
  /** 候选路径预先算好的小写形式和文件名(目录去掉末尾的 /),每按一个键都要用,不重复算 */
22
17
  interface Prepared {
@@ -87,67 +82,3 @@ function subsequence(text: string, q: string): boolean {
87
82
  for (const ch of text) if (ch === q[i] && ++i === q.length) return true;
88
83
  return false;
89
84
  }
90
-
91
- /**
92
- * @ 补全的候选:工作目录里的文件(git 仓库里只看版本控制的)和它们所在的目录,目录以 / 结尾。
93
- * 5 秒还没列完就先给已经找到的(大仓库第一次列得慢,不该让输入框卡住)
94
- */
95
- export async function mentionCandidates(cwd: string, signal: AbortSignal = AbortSignal.timeout(5000)): Promise<string[]> {
96
- const files: string[] = [];
97
- const dirs = new Set<string>();
98
- try {
99
- for await (const full of await listFiles(cwd, signal)) {
100
- const rel = display(cwd, full);
101
- files.push(rel);
102
- for (let i = rel.lastIndexOf("/"); i > 0; i = rel.lastIndexOf("/", i - 1)) {
103
- const dir = rel.slice(0, i + 1);
104
- if (dirs.has(dir)) break;
105
- dirs.add(dir);
106
- }
107
- if (files.length + dirs.size >= MAX_CANDIDATES) break;
108
- }
109
- } catch {
110
- // 列到一半被中止(超时):用已经找到的
111
- }
112
- return [...dirs, ...files];
113
- }
114
-
115
- // 以下和 jade/fs 的 listFiles、display 相同:插件之间不共享代码(只能共享类型),所以这里留一份
116
-
117
- const SKIP_DIRS = new Set([".git", "node_modules"]);
118
-
119
- /** 显示用:工作目录内的路径用相对形式,统一为正斜杠 */
120
- function display(cwd: string, full: string): string {
121
- const rel = path.relative(cwd, full);
122
- const shown = rel && rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel) ? rel : full;
123
- return shown.split(path.sep).join("/");
124
- }
125
-
126
- /** git 仓库里的文件(版本控制的和没忽略的新文件);不是仓库、没有 git 时 undefined */
127
- function gitFiles(root: string): Promise<string[] | undefined> {
128
- return new Promise((resolve) => {
129
- execFile("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root, maxBuffer: 256 * 1024 * 1024, windowsHide: true }, (err, out) =>
130
- // 合并冲突中的文件会出现多次
131
- resolve(err ? undefined : [...new Set(out.split("\0").filter(Boolean))]),
132
- );
133
- });
134
- }
135
-
136
- async function listFiles(root: string, signal: AbortSignal): Promise<Iterable<string> | AsyncIterable<string>> {
137
- const tracked = await gitFiles(root);
138
- if (!tracked) return walk(root, signal);
139
- return tracked.filter((rel) => !rel.split("/").some((seg) => SKIP_DIRS.has(seg))).map((rel) => path.join(root, rel));
140
- }
141
-
142
- async function* walk(dir: string, signal: AbortSignal): AsyncIterable<string> {
143
- signal.throwIfAborted();
144
- const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
145
- for (const e of entries) {
146
- const full = path.join(dir, e.name);
147
- if (e.isDirectory()) {
148
- if (!SKIP_DIRS.has(e.name)) yield* walk(full, signal);
149
- } else if (e.isFile()) {
150
- yield full;
151
- }
152
- }
153
- }
@@ -5,6 +5,6 @@
5
5
  "entry": "./index.ts",
6
6
  "provides": ["frontend@1", "ui@1"],
7
7
  "requires": ["commands@1", "keys@1", "renderers@1"],
8
- "optional": ["modes@1", "models@1", "compact@1", "sessions@1", "steer@1"],
8
+ "optional": ["models@1", "completions@1", "sessions@1", "steer@1"],
9
9
  "frontend": { "name": "tui", "default": true }
10
10
  }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { createInterface, type Interface } from "node:readline/promises";
6
6
  import { stripVTControlCharacters } from "node:util";
7
+ import type { Span, StatusSegment, Text, TextStyle } from "@uncarved/jade-api";
7
8
 
8
9
  export interface Choice<T> {
9
10
  label: string;
@@ -14,14 +15,15 @@ export interface Choice<T> {
14
15
 
15
16
  export interface StatusInfo {
16
17
  /** 插件用 ctx.status 设置的段落(已经是一行、截断过) */
17
- plugins?: { plugin: string; text: string }[];
18
+ plugins?: { plugin: string; text: string | StatusSegment }[];
19
+ /** 插件用 ctx.panel 设置的、显示在输入框上方的块(可以多行,已经限制过行数) */
20
+ panels?: { plugin: string; text: string }[];
18
21
  cwd: string;
19
22
  branch?: string;
20
23
  model: string;
21
- mode: string;
22
24
  session?: string;
23
25
  /** 上一次请求的上下文用量,limit 是模型的上下文窗口 */
24
- context?: { used: number; limit: number; /** 超过这个 token 数会自动压缩 */ compactAt?: number };
26
+ context?: { used: number; limit: number };
25
27
  /** 本会话累计的用量(含子 Agent 和压缩) */
26
28
  spent?: { input: number; output: number };
27
29
  /** 上一次请求的输入中命中缓存的比例(0–1);服务不报告缓存用量时为 undefined */
@@ -34,6 +36,17 @@ export interface CommandInfo {
34
36
  name: string;
35
37
  args?: string;
36
38
  about: string;
39
+ /** 输入的简写(Command.prefix),例如 "!" */
40
+ prefix?: string;
41
+ /** 打了简写时输入框上写的说明 */
42
+ prefixHint?: string;
43
+ }
44
+
45
+ /** 输入框的一种补全(completions@1) */
46
+ export interface CompletionInfo {
47
+ trigger: string;
48
+ label: string;
49
+ hint?: string;
37
50
  }
38
51
 
39
52
  export interface Screen {
@@ -99,6 +112,38 @@ export const bold = paint("1", "22");
99
112
  export const italic = paint("3", "23");
100
113
  export const underline = paint("4", "24");
101
114
  export const strike = paint("9", "29");
115
+ const magenta = paint("35", "39");
116
+
117
+ /** 插件给的带语义样式的文字(jade-api 的 Text)怎么画 */
118
+ const STYLES: Record<TextStyle, (s: string) => string> = {
119
+ dim,
120
+ bold,
121
+ ok: green,
122
+ warn: yellow,
123
+ error: red,
124
+ accent: magenta,
125
+ code: cyan,
126
+ added: green,
127
+ removed: red,
128
+ };
129
+
130
+ /** 插件给的文字画成终端里的样子:片段按样式上色(字符串里原有的 ANSI 照留),嵌套的数组按顺序接起来 */
131
+ export function ansi(t: Text | undefined): string {
132
+ if (t === undefined || t === null) return "";
133
+ if (typeof t === "string") return t;
134
+ if (Array.isArray(t)) return (t as readonly Text[]).map(ansi).join("");
135
+ const span = t as Span;
136
+ const styles = (Array.isArray(span.style) ? span.style : [span.style]) as TextStyle[];
137
+ return styles.reduce((s, style) => STYLES[style]?.(s) ?? s, String(span.text ?? ""));
138
+ }
139
+
140
+ /** 只取文字:样式和字符串里的控制序列都去掉(不画颜色的地方用,例如 -p、测试) */
141
+ export function plain(t: Text | undefined): string {
142
+ if (t === undefined || t === null) return "";
143
+ if (typeof t === "string") return stripVTControlCharacters(t);
144
+ if (Array.isArray(t)) return (t as readonly Text[]).map(plain).join("");
145
+ return stripVTControlCharacters(String((t as Span).text ?? ""));
146
+ }
102
147
 
103
148
  // ---------- 过滤控制字符 ----------
104
149
 
@@ -153,8 +198,13 @@ export function safeScreen(screen: Screen): Screen {
153
198
  busy: (label) => screen.busy(opt(label)),
154
199
  status: (info) => {
155
200
  const out: Partial<StatusInfo> = { ...info };
156
- for (const k of ["cwd", "branch", "model", "mode", "session"] as const) if (typeof info[k] === "string") out[k] = s(info[k]);
157
- if (info.plugins) out.plugins = info.plugins.map((p) => ({ plugin: p.plugin, text: s(p.text) }));
201
+ for (const k of ["cwd", "branch", "model", "session"] as const) if (typeof info[k] === "string") out[k] = s(info[k]);
202
+ if (info.plugins)
203
+ out.plugins = info.plugins.map((p) => ({
204
+ plugin: p.plugin,
205
+ text: typeof p.text === "string" ? s(p.text) : { ...p.text, text: s(p.text.text), ...(p.text.short !== undefined ? { short: s(p.text.short) } : {}) },
206
+ }));
207
+ if (info.panels) out.panels = info.panels.map((p) => ({ plugin: p.plugin, text: s(p.text) }));
158
208
  screen.status(out);
159
209
  },
160
210
  queued: (items) => screen.queued(items.map(s)),