@uncarved/jade 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 (207) 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 +482 -27
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +49 -24
  14. package/plugins/approval/policy.ts +48 -25
  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 +55 -12
  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 +10 -9
  50. package/plugins/models/index.ts +31 -4
  51. package/plugins/models/provider.ts +12 -1
  52. package/plugins/modes/index.ts +13 -2
  53. package/plugins/print/index.ts +7 -4
  54. package/plugins/prompts/index.ts +0 -0
  55. package/plugins/renderers/index.ts +10 -5
  56. package/plugins/repeats/index.ts +39 -9
  57. package/plugins/schedule/index.ts +2 -0
  58. package/plugins/screenshot/browser.ts +231 -0
  59. package/plugins/screenshot/index.ts +3 -2
  60. package/plugins/screenshot/tool.ts +27 -51
  61. package/plugins/sessions/index.ts +48 -2
  62. package/plugins/shell/index.ts +75 -22
  63. package/plugins/shell/plugin.json +1 -2
  64. package/plugins/shell/renderers.ts +9 -7
  65. package/plugins/shell/shell.ts +93 -34
  66. package/plugins/skills/index.ts +28 -19
  67. package/plugins/skills/project.ts +12 -7
  68. package/plugins/steer/index.ts +5 -4
  69. package/plugins/task/index.ts +81 -81
  70. package/plugins/task/plugin.json +5 -2
  71. package/plugins/task/style.ts +13 -14
  72. package/plugins/task/subagent.ts +67 -184
  73. package/plugins/todo/index.ts +39 -9
  74. package/plugins/tools/index.ts +57 -0
  75. package/plugins/tools/plugin.json +7 -0
  76. package/plugins/tui/frontend.ts +161 -87
  77. package/plugins/tui/index.ts +2 -3
  78. package/plugins/tui/mascot.ts +8 -7
  79. package/plugins/tui/mentions.ts +11 -80
  80. package/plugins/tui/plugin.json +1 -1
  81. package/plugins/tui/screen.ts +55 -5
  82. package/plugins/tui/transcript.ts +17 -7
  83. package/plugins/tui/tui.ts +356 -104
  84. package/plugins/tui/vendor.ts +1 -1
  85. package/plugins/undo/checkpoint.ts +5 -3
  86. package/plugins/undo/index.ts +43 -14
  87. package/plugins/undo/style.ts +13 -14
  88. package/plugins/web/index.ts +7 -18
  89. package/plugins/web/plugin.json +1 -1
  90. package/plugins-dist/approval/index.js +363 -414
  91. package/plugins-dist/approval/policy.js +395 -497
  92. package/plugins-dist/approval/review.js +132 -158
  93. package/plugins-dist/approval/schema.js +50 -55
  94. package/plugins-dist/ask/index.js +115 -129
  95. package/plugins-dist/budget/index.js +27 -31
  96. package/plugins-dist/checks/checks.js +293 -329
  97. package/plugins-dist/checks/index.js +119 -139
  98. package/plugins-dist/checks/plugin.json +2 -1
  99. package/plugins-dist/checks/project.js +57 -65
  100. package/plugins-dist/commands/index.js +47 -29
  101. package/plugins-dist/compact/compact.js +233 -249
  102. package/plugins-dist/compact/index.js +98 -95
  103. package/plugins-dist/compact/style.js +9 -14
  104. package/plugins-dist/completions/index.js +30 -0
  105. package/plugins-dist/completions/plugin.json +9 -0
  106. package/plugins-dist/continue/index.js +40 -52
  107. package/plugins-dist/copy/index.js +40 -0
  108. package/plugins-dist/copy/plugin.json +9 -0
  109. package/plugins-dist/cost/index.js +98 -115
  110. package/plugins-dist/custom-commands/index.js +55 -72
  111. package/plugins-dist/editor/index.js +64 -72
  112. package/plugins-dist/fs/diff.js +111 -124
  113. package/plugins-dist/fs/fs.js +426 -469
  114. package/plugins-dist/fs/grep.js +262 -244
  115. package/plugins-dist/fs/index.js +20 -34
  116. package/plugins-dist/fs/plugin.json +1 -2
  117. package/plugins-dist/fs/renderers.js +100 -112
  118. package/plugins-dist/fs/style.js +11 -15
  119. package/plugins-dist/fs/sys.js +31 -43
  120. package/plugins-dist/hooks/index.js +107 -127
  121. package/plugins-dist/keys/index.js +27 -31
  122. package/plugins-dist/mcp/index.js +271 -199
  123. package/plugins-dist/mcp/install.js +123 -137
  124. package/plugins-dist/mcp/mcp.js +638 -577
  125. package/plugins-dist/mcp/plugin.json +3 -1
  126. package/plugins-dist/mcp/project.js +98 -115
  127. package/plugins-dist/memory/index.js +83 -88
  128. package/plugins-dist/memory/memory.js +111 -128
  129. package/plugins-dist/memory/style.js +9 -14
  130. package/plugins-dist/mentions/attach.js +91 -99
  131. package/plugins-dist/mentions/candidates.js +49 -0
  132. package/plugins-dist/mentions/index.js +71 -81
  133. package/plugins-dist/mentions/plugin.json +2 -1
  134. package/plugins-dist/mentions/style.js +9 -14
  135. package/plugins-dist/models/config.js +29 -43
  136. package/plugins-dist/models/configure.js +392 -473
  137. package/plugins-dist/models/context.js +14 -22
  138. package/plugins-dist/models/index.js +182 -188
  139. package/plugins-dist/models/provider.js +243 -295
  140. package/plugins-dist/models/saved.js +59 -71
  141. package/plugins-dist/modes/index.js +138 -165
  142. package/plugins-dist/plugins/index.js +34 -34
  143. package/plugins-dist/print/index.js +192 -175
  144. package/plugins-dist/prompts/index.js +81 -89
  145. package/plugins-dist/prompts/notes.js +31 -37
  146. package/plugins-dist/prompts/prompts.js +155 -193
  147. package/plugins-dist/prompts/results.js +40 -53
  148. package/plugins-dist/prompts/sys.js +39 -50
  149. package/plugins-dist/renderers/index.js +32 -32
  150. package/plugins-dist/repeats/index.js +134 -151
  151. package/plugins-dist/schedule/cron.js +49 -56
  152. package/plugins-dist/schedule/index.js +229 -247
  153. package/plugins-dist/schedule/store.js +93 -109
  154. package/plugins-dist/scratch/index.js +12 -18
  155. package/plugins-dist/screenshot/browser.js +169 -0
  156. package/plugins-dist/screenshot/index.js +37 -45
  157. package/plugins-dist/screenshot/sys.js +53 -65
  158. package/plugins-dist/screenshot/tool.js +101 -151
  159. package/plugins-dist/sessions/index.js +149 -117
  160. package/plugins-dist/shell/index.js +117 -74
  161. package/plugins-dist/shell/plugin.json +1 -2
  162. package/plugins-dist/shell/renderers.js +28 -33
  163. package/plugins-dist/shell/service.js +17 -23
  164. package/plugins-dist/shell/shell.js +317 -320
  165. package/plugins-dist/shell/sys.js +64 -79
  166. package/plugins-dist/skills/index.js +193 -211
  167. package/plugins-dist/skills/install.js +122 -149
  168. package/plugins-dist/skills/project.js +65 -73
  169. package/plugins-dist/skills/skills.js +135 -171
  170. package/plugins-dist/steer/index.js +108 -125
  171. package/plugins-dist/suggest/index.js +235 -259
  172. package/plugins-dist/task/index.js +130 -148
  173. package/plugins-dist/task/plugin.json +5 -4
  174. package/plugins-dist/task/style.js +9 -14
  175. package/plugins-dist/task/subagent.js +156 -279
  176. package/plugins-dist/todo/index.js +79 -63
  177. package/plugins-dist/tools/index.js +43 -0
  178. package/plugins-dist/tools/plugin.json +9 -0
  179. package/plugins-dist/tui/editor.js +145 -160
  180. package/plugins-dist/tui/frontend.js +641 -655
  181. package/plugins-dist/tui/history.js +34 -37
  182. package/plugins-dist/tui/index.js +16 -18
  183. package/plugins-dist/tui/markdown.js +203 -247
  184. package/plugins-dist/tui/mascot.js +266 -353
  185. package/plugins-dist/tui/mentions.js +67 -144
  186. package/plugins-dist/tui/plugin.json +1 -2
  187. package/plugins-dist/tui/render.js +35 -45
  188. package/plugins-dist/tui/screen.js +197 -180
  189. package/plugins-dist/tui/transcript.js +436 -468
  190. package/plugins-dist/tui/tui.js +1554 -1645
  191. package/plugins-dist/tui/vendor.js +1388 -1088
  192. package/plugins-dist/undo/checkpoint.js +95 -118
  193. package/plugins-dist/undo/index.js +185 -192
  194. package/plugins-dist/undo/snapshot.js +83 -99
  195. package/plugins-dist/undo/style.js +9 -14
  196. package/plugins-dist/update/index.js +26 -28
  197. package/plugins-dist/web/env.js +55 -68
  198. package/plugins-dist/web/index.js +80 -110
  199. package/plugins-dist/web/plugin.json +1 -2
  200. package/plugins-dist/web/renderers.js +4 -5
  201. package/plugins-dist/web/web.js +514 -593
  202. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  203. package/sdk/python/jade_plugin.py +9 -2
  204. package/src/api.ts +1 -1
  205. package/src/host.ts +39 -4
  206. package/src/remote.ts +6 -1
  207. package/src/session.ts +489 -34
@@ -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,57 @@ 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 · 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";
93
+
94
+ /** 退出时最多等正在做的事这么久 */
95
+ const QUIT_WAIT_MS = 3000;
96
+
97
+ /** 命令运行中的临时显示(CommandContext.progress)最多占几行 */
98
+ const LIVE_ROWS = 8;
54
99
 
55
100
  /** 第二次 esc 算作"再按一次"的时间窗口 */
56
101
  const SECOND_ESC_MS = 3000;
@@ -78,10 +123,9 @@ export interface FrontendServices {
78
123
  commands: Commands;
79
124
  keys: Keys;
80
125
  renderers: Renderers;
81
- modes?: Modes;
82
126
  models?: Models;
83
- /** 自动压缩的阈值,状态栏显示 */
84
- compact?: Compact;
127
+ /** 输入框的补全(completions@1) */
128
+ completions?: Completions;
85
129
  /** 会话索引(jade/sessions),--continue 用 */
86
130
  index?: SessionIndex;
87
131
  /** 一轮中途说的话(jade/steer):有它时,模型工作中提交的消息在下一次请求模型时就交给它,不等这一轮结束 */
@@ -90,6 +134,10 @@ export interface FrontendServices {
90
134
 
91
135
  /** 状态栏上插件的一段最多显示这么多字符(超出的截断,换行并成空格) */
92
136
  const MAX_SEGMENT = 80;
137
+ /** 状态栏的一段(文字或带颜色、优先级的 StatusSegment) */
138
+ type Segment = string | StatusSegment;
139
+ /** 输入框上方插件的一块最多占几行 */
140
+ const MAX_PANEL_LINES = 10;
93
141
 
94
142
  /**
95
143
  * ui@1:界面出来之前的提示先攒着,出来之后显示;界面关掉之后写到 stderr。
@@ -101,8 +149,10 @@ export class ScreenBridge {
101
149
  /** 会话打开期间的提示:打开之后要清屏,先攒着,清屏之后再显示 */
102
150
  #held: string[] | undefined;
103
151
  #closed = false;
104
- /** 状态栏上各插件的一段:会话 id → 插件 id → 文字 */
105
- #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>>();
106
156
  /** 界面现在显示哪个会话;换会话时由前端调用 show */
107
157
  #session: string | undefined;
108
158
 
@@ -117,7 +167,7 @@ export class ScreenBridge {
117
167
  },
118
168
  select: async (req, signal) => {
119
169
  if (!this.screen) return undefined;
120
- 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 } : {}) });
121
171
  },
122
172
  input: async (req, signal) => {
123
173
  if (!this.screen) return undefined;
@@ -167,7 +217,11 @@ export class ScreenBridge {
167
217
  #apply(): void {
168
218
  if (!this.screen) return;
169
219
  const segments = this.#session === undefined ? undefined : this.#segments.get(this.#session);
170
- 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
+ });
171
225
  }
172
226
 
173
227
  /** 一个插件在一个会话里的界面。作用域关闭时核心调用 dispose,这里把它的段落去掉 */
@@ -177,18 +231,20 @@ export class ScreenBridge {
177
231
  const apply = () => {
178
232
  if (bridge.#session === session) bridge.#apply();
179
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
+ };
180
245
  return {
181
- status(text) {
182
- if (gone) return;
183
- // 每次现取:别的插件 dispose 可能已经把空的 map 删了
184
- let segments = bridge.#segments.get(session);
185
- if (text === undefined) segments?.delete(plugin);
186
- else {
187
- if (!segments) bridge.#segments.set(session, (segments = new Map()));
188
- segments.set(plugin, clipSegment(text));
189
- }
190
- apply();
191
- },
246
+ status: (text) => put(bridge.#segments, text === undefined ? undefined : clipSegment(text)),
247
+ panel: (text) => put(bridge.#panels, text === undefined ? undefined : clipPanel(ansi(text))),
192
248
  draft: {
193
249
  text: () => bridge.screen?.draft?.text() ?? "",
194
250
  insert: (text) => bridge.screen?.draft?.insert(text),
@@ -197,19 +253,31 @@ export class ScreenBridge {
197
253
  },
198
254
  dispose() {
199
255
  gone = true;
200
- const segments = bridge.#segments.get(session);
201
- segments?.delete(plugin);
202
- 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
+ }
203
261
  apply();
204
262
  },
205
263
  };
206
264
  }
207
265
  }
208
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
+
209
273
  /** 状态栏的一段是一行:空白并成一个空格,长的截断 */
210
- function clipSegment(text: string): string {
211
- const one = String(text).replace(/\s+/g, " ").trim();
212
- 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) } : {}) };
213
281
  }
214
282
 
215
283
  export function tuiFrontend(services: FrontendServices, bridge: ScreenBridge): Frontend {
@@ -253,7 +321,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
253
321
  return 2;
254
322
  }
255
323
 
256
- const { cwd, home, commands, keys, renderers, modes, models, compact, index, steer } = services;
324
+ const { cwd, home, commands, keys, renderers, models, completions, index, steer } = services;
257
325
  const sessions = opts.sessions;
258
326
  // --continue:这个目录里最近用过的会话(索引由 jade/sessions 在收到第一条消息时写)
259
327
  if (args.cont && !index) {
@@ -274,8 +342,16 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
274
342
  ...commands
275
343
  .list()
276
344
  .filter((c) => !OWN.some((o) => o.name === c.name))
277
- .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
+ })),
278
351
  ];
352
+ /** 输入框的补全:每次渲染时取(插件可能刚登记或撤销) */
353
+ const completionList = (): CompletionInfo[] =>
354
+ (completions?.list() ?? []).map(({ completion: c }) => ({ trigger: c.trigger, label: c.label, ...(c.hint ? { hint: c.hint } : {}) }));
279
355
 
280
356
  let ready = false;
281
357
  const early: string[] = [];
@@ -285,7 +361,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
285
361
  // 插件、工具输出和模型的文字都经过 safeScreen 显示:只留颜色,去掉能搅乱终端的控制序列
286
362
  const screen: Screen = safeScreen(
287
363
  tuiScreen({
288
- 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)" },
289
365
  version: VERSION,
290
366
  commands: commandList,
291
367
  history: past,
@@ -296,12 +372,12 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
296
372
  if (ready) onSubmit(text);
297
373
  else early.push(text);
298
374
  },
299
- // 输入 @ 时列工作目录里的文件
300
- files: () => mentionCandidates(cwd),
375
+ // 打了补全的触发字符(例如 @)时向登记它的插件要候选
376
+ completions: completionList,
377
+ complete: async (trigger) => (await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates()) ?? [],
301
378
  interrupt: () => ready && interrupt(),
302
379
  unqueue: () => takeBack(),
303
380
  exit: () => void quit(0),
304
- cycleMode: () => void key("shift+tab"),
305
381
  key: (spec) => key(spec),
306
382
  },
307
383
  }),
@@ -322,7 +398,6 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
322
398
  return true;
323
399
  }
324
400
 
325
- const offMode = modes?.subscribe((mode) => screen.status({ mode }));
326
401
  // /model 换了配置:状态栏跟着换
327
402
  const offModel = models?.subscribe?.(() => screen.status({ model: models.current()?.model ?? "(no model)" }));
328
403
 
@@ -337,10 +412,15 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
337
412
  cwd,
338
413
  contextWindow: () => models?.current()?.contextWindow ?? 0,
339
414
  maxTokens: () => models?.current()?.maxTokens,
340
- ...(compact ? { compactAt: () => compact.threshold() } : {}),
341
415
  canRetry,
342
- renderer: (tool) => renderers.forTool(tool),
343
- 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
+ },
344
424
  });
345
425
 
346
426
  /** 换成另一个会话:清屏,恢复的会话重新显示之前的对话,然后继续日志里没做完的工作 */
@@ -385,7 +465,8 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
385
465
  bridge.hold();
386
466
  try {
387
467
  const s = await sessions.open(o);
388
- await adopt(s, o?.resume !== undefined);
468
+ // 复制出的会话(/rewind)和恢复的一样:重新显示已有的对话
469
+ await adopt(s, o?.resume !== undefined || o?.fork !== undefined);
389
470
  return s;
390
471
  } finally {
391
472
  bridge.release();
@@ -508,9 +589,10 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
508
589
  if (quitting) return;
509
590
  quitting = true;
510
591
  if (running) current?.abort(new Error("exiting"));
511
- await work?.catch(() => {});
592
+ // 正在做的事停不下来时(例如命令杀不掉)不一直等:退出不能被它卡住
593
+ for (const ac of commandAborts) ac.abort(new Error("exiting"));
594
+ await Promise.race([work?.catch(() => {}), new Promise((r) => setTimeout(r, QUIT_WAIT_MS))]);
512
595
  keyAbort.abort(new Error("exiting"));
513
- offMode?.();
514
596
  offModel?.();
515
597
  offSteer?.();
516
598
  unsubscribe?.();
@@ -545,23 +627,18 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
545
627
  const rest = input.slice(1).replace(/^\S+\s*/, "");
546
628
  if (name === "exit" || name === "quit") return false;
547
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(" · ")}`));
548
639
  const all = commandList();
549
640
  const width = Math.max(...all.map((c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`.length)) + 2;
550
641
  screen.log(all.map((c) => `${`/${c.name}${c.args ? ` ${c.args}` : ""}`.padEnd(width)}${dim(c.about)}`).join("\n"));
551
- screen.log(dim(KEYS));
552
- const pluginKeys = keys.list();
553
- if (pluginKeys.length > 0) screen.log(dim(`Plugin keys: ${pluginKeys.map((k) => `${k.key}${k.description ? ` ${k.description}` : ""} (${k.plugin})`).join(" · ")}`));
554
- return true;
555
- }
556
- if (name === "copy") {
557
- const reply = lastReply(current?.state.messages ?? []);
558
- const text = rest.trim() === "code" ? reply && lastCodeBlock(reply) : reply;
559
- if (!text) screen.log(dim(rest.trim() === "code" ? "The last reply has no code block." : "There is no reply to copy yet."));
560
- else if (!screen.copy) screen.log(red("[error] this terminal cannot copy"));
561
- else {
562
- screen.copy(text);
563
- screen.log(dim(`[copied ${[...text].length} characters]`));
564
- }
565
642
  return true;
566
643
  }
567
644
  const found = commands.get(name);
@@ -571,17 +648,29 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
571
648
  }
572
649
  const ac = new AbortController();
573
650
  commandAborts.add(ac);
574
- const ctx: CommandContext = { signal: ac.signal, ui: bridge.ui, sessions: manager, print: (t) => screen.log(t) };
651
+ // 命令的临时显示:末尾几行,每行占进度区的一行
652
+ const showLive = (live: Text | undefined) => {
653
+ const text = live === undefined ? undefined : ansi(live);
654
+ const lines = text?.replace(/\r\n?/g, "\n").trimEnd().split("\n").slice(-LIVE_ROWS) ?? [];
655
+ for (let i = 0; i < LIVE_ROWS; i++) screen.progress(`command:${i}`, text !== undefined && i < lines.length ? dim(` │ ${lines[i]}`) : undefined);
656
+ };
657
+ const ctx: CommandContext = {
658
+ signal: ac.signal,
659
+ ui: bridge.ui,
660
+ sessions: manager,
661
+ print: (t, o) => screen.log(ansi(t), o?.details ? { details: ansi(o.details) } : undefined),
662
+ progress: showLive,
663
+ };
575
664
  try {
576
665
  const result = await found.command.run(rest, ctx);
577
- if (typeof result === "string") screen.log(result);
578
- else if (result && typeof result === "object" && typeof result.prompt === "string") {
666
+ if (isPrompt(result)) {
579
667
  if (found.command.instant) screen.log(yellow(`[warning] /${name} is instant and cannot send a prompt`));
580
668
  else await say(result.prompt);
581
- }
669
+ } else if (result !== undefined && result !== null) screen.log(ansi(result));
582
670
  } catch (e) {
583
671
  if (!ac.signal.aborted) screen.log(red(`[error] /${name}: ${errorText(e)}`));
584
672
  } finally {
673
+ showLive(undefined);
585
674
  commandAborts.delete(ac);
586
675
  }
587
676
  return true;
@@ -589,6 +678,10 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
589
678
 
590
679
  function onSubmit(text: string) {
591
680
  if (quitting) return;
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()}`;
592
685
  const name = commandName(text);
593
686
  if (name !== undefined && instant(name)) {
594
687
  // 不碰会话的命令运行中也直接执行
@@ -625,6 +718,8 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
625
718
  showQueued();
626
719
  view.echo(text);
627
720
  if (commandName(text) !== undefined) {
721
+ // 命令可能要跑一阵(/sh 跑测试):让用户看到它在跑
722
+ screen.busy("Running");
628
723
  if (!(await command(text))) {
629
724
  exit = true;
630
725
  return;
@@ -657,12 +752,8 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
657
752
  } catch (e) {
658
753
  screen.log(red(`[error] ${errorText(e)}`));
659
754
  }
660
- if (!models?.current()) {
661
- // /model(jade/models 提供)当场就能配好,不用重启;没有这条命令时只能改文件
662
- const file = `put ANTHROPIC_API_KEY=... (or OPENAI_API_KEY=...) in ${path.join(home, ".env")}, then restart jade`;
663
- 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}.`));
664
- }
665
- 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."));
666
757
  ready = true;
667
758
  for (const text of [...(args.prompt ? [args.prompt] : []), ...early.splice(0)]) onSubmit(text);
668
759
 
@@ -670,23 +761,6 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
670
761
  }
671
762
 
672
763
  /** 当前分支;不在仓库里或没有 git 时 undefined */
673
- /** 最近一条有正文的助手消息的正文(模型写的原文,没有折行和排版) */
674
- export function lastReply(messages: readonly { role: string; content: readonly Block[] }[]): string | undefined {
675
- for (let i = messages.length - 1; i >= 0; i--) {
676
- const m = messages[i]!;
677
- if (m.role !== "assistant") continue;
678
- const text = m.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim();
679
- if (text) return text;
680
- }
681
- return undefined;
682
- }
683
-
684
- /** Markdown 里最后一个围栏代码块的内容 */
685
- export function lastCodeBlock(markdown: string): string | undefined {
686
- const blocks = [...markdown.matchAll(/^ {0,3}(`{3,}|~{3,})[^\n]*\n([\s\S]*?)^ {0,3}\1[`~]*[ \t]*$/gm)];
687
- return blocks.at(-1)?.[2]?.replace(/\n$/, "");
688
- }
689
-
690
764
  function gitBranch(cwd: string): Promise<string | undefined> {
691
765
  return new Promise((resolve) => {
692
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
  },
@@ -19,7 +19,7 @@ export type Mood =
19
19
  | "writing" // 输出正文或工具参数:低头,眼睛随打字左右移,旁边打字的点
20
20
  | "tool" // 运行工具:看向右边转着的圈,身上扫过一道光
21
21
  | "asking" // 弹出对话框等用户:睁大眼,头上一个闪烁的感叹号
22
- | "stopping" // 正在中断:眯眼,变成琥珀色,冒一滴汗
22
+ | "stopping" // 正在中断:眯眼,变成琥珀色,汗一滴滴往下滑
23
23
  | "happy"; // 刚做完:^ ^ 地原地蹦一下,落地一亮,转头看右边画出一个 ✓,再回过头冲你眨一只眼
24
24
 
25
25
  /** 做完后笑多久 */
@@ -386,12 +386,13 @@ function side(mood: Mood, now: number, t: number): [number, number, RGB][] {
386
386
  const c = mix(BANG[0]!, BANG[1]!, 0.5 + 0.5 * Math.sin(now / 160));
387
387
  return [0, 1, 2, 4].map((y) => [1, y, c]);
388
388
  }
389
- case "stopping":
390
- // 汗珠挂在头的右上角,贴着身体
391
- return [
392
- [-1, 0, SWEAT],
393
- [-1, 1, mix(SWEAT, rgb("#ffffff"), 0.4)],
394
- ];
389
+ case "stopping": {
390
+ // 汗珠从头的右上角贴着身体一滴滴往下滑:亮的一头在下面,上面拖一格淡的;滑到底停一拍再冒下一滴
391
+ const row = Math.floor((now % 1000) / 200);
392
+ if (row > 3) return [];
393
+ const head: [number, number, RGB] = [-1, row, mix(SWEAT, rgb("#ffffff"), 0.4)];
394
+ return row > 0 ? [[-1, row - 1, SWEAT], head] : [head];
395
+ }
395
396
  default:
396
397
  return [];
397
398
  }
@@ -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
  }