@uncarved/jade 0.2.0 → 0.3.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 (224) hide show
  1. package/README.md +277 -0
  2. package/assets/logo.svg +1 -0
  3. package/bin/jade.js +15 -0
  4. package/dist/api.d.ts +5 -250
  5. package/dist/api.js +5 -7
  6. package/dist/api.js.map +1 -1
  7. package/dist/fetch.d.ts +8 -0
  8. package/dist/fetch.js +19 -17
  9. package/dist/fetch.js.map +1 -1
  10. package/dist/host.d.ts +12 -1
  11. package/dist/host.js +49 -1
  12. package/dist/host.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/main.js +28 -5
  17. package/dist/main.js.map +1 -1
  18. package/dist/remote.js +4 -0
  19. package/dist/remote.js.map +1 -1
  20. package/dist/session.d.ts +2 -0
  21. package/dist/session.js +133 -13
  22. package/dist/session.js.map +1 -1
  23. package/dist/source.d.ts +2 -10
  24. package/dist/source.js.map +1 -1
  25. package/dist/update.d.ts +8 -20
  26. package/dist/update.js +12 -1
  27. package/dist/update.js.map +1 -1
  28. package/package.json +6 -4
  29. package/plugins/approval/index.ts +246 -84
  30. package/plugins/approval/plugin.json +5 -1
  31. package/plugins/approval/policy.ts +27 -6
  32. package/plugins/approval/review.ts +1 -1
  33. package/plugins/ask/index.ts +2 -2
  34. package/plugins/budget/index.ts +1 -1
  35. package/plugins/checks/checks.ts +3 -2
  36. package/plugins/checks/index.ts +2 -5
  37. package/plugins/commands/index.ts +2 -44
  38. package/plugins/compact/compact.ts +15 -4
  39. package/plugins/compact/index.ts +13 -16
  40. package/plugins/continue/index.ts +1 -1
  41. package/plugins/cost/index.ts +143 -0
  42. package/plugins/cost/plugin.json +13 -0
  43. package/plugins/custom-commands/index.ts +85 -0
  44. package/plugins/custom-commands/plugin.json +8 -0
  45. package/plugins/editor/index.ts +88 -0
  46. package/plugins/editor/plugin.json +17 -0
  47. package/plugins/fs/fs.ts +110 -17
  48. package/plugins/fs/grep.ts +41 -11
  49. package/plugins/fs/index.ts +9 -7
  50. package/plugins/fs/renderers.ts +1 -1
  51. package/plugins/hooks/index.ts +152 -0
  52. package/plugins/hooks/plugin.json +14 -0
  53. package/plugins/keys/index.ts +2 -18
  54. package/plugins/mcp/index.ts +40 -12
  55. package/plugins/mcp/install.ts +139 -0
  56. package/plugins/mcp/mcp.ts +2 -1
  57. package/plugins/mcp/plugin.json +1 -1
  58. package/plugins/mcp/project.ts +37 -1
  59. package/plugins/memory/index.ts +4 -9
  60. package/plugins/memory/plugin.json +1 -1
  61. package/plugins/mentions/index.ts +33 -13
  62. package/plugins/models/configure.ts +258 -150
  63. package/plugins/models/context.ts +2 -2
  64. package/plugins/models/index.ts +50 -42
  65. package/plugins/models/plugin.json +1 -1
  66. package/plugins/models/provider.ts +22 -4
  67. package/plugins/models/saved.ts +8 -4
  68. package/plugins/modes/index.ts +2 -17
  69. package/plugins/plugins/index.ts +2 -2
  70. package/plugins/print/index.ts +60 -12
  71. package/plugins/print/plugin.json +1 -0
  72. package/plugins/prompts/index.ts +50 -14
  73. package/plugins/{memory → prompts}/notes.ts +21 -9
  74. package/plugins/prompts/plugin.json +8 -2
  75. package/plugins/prompts/prompts.ts +14 -8
  76. package/plugins/prompts/results.ts +63 -0
  77. package/plugins/prompts/sys.ts +16 -4
  78. package/plugins/renderers/index.ts +2 -43
  79. package/plugins/repeats/index.ts +1 -1
  80. package/plugins/schedule/index.ts +2 -2
  81. package/plugins/scratch/index.ts +2 -3
  82. package/plugins/screenshot/index.ts +26 -13
  83. package/plugins/screenshot/plugin.json +1 -1
  84. package/plugins/sessions/index.ts +2 -17
  85. package/plugins/shell/index.ts +56 -6
  86. package/plugins/shell/plugin.json +3 -1
  87. package/plugins/shell/renderers.ts +1 -1
  88. package/plugins/shell/service.ts +2 -13
  89. package/plugins/shell/shell.ts +31 -16
  90. package/plugins/skills/index.ts +172 -37
  91. package/plugins/skills/install.ts +212 -0
  92. package/plugins/skills/plugin.json +3 -2
  93. package/plugins/skills/project.ts +38 -1
  94. package/plugins/skills/skills.ts +28 -9
  95. package/plugins/steer/index.ts +142 -0
  96. package/plugins/steer/plugin.json +8 -0
  97. package/plugins/suggest/index.ts +16 -11
  98. package/plugins/suggest/plugin.json +1 -1
  99. package/plugins/task/index.ts +8 -16
  100. package/plugins/task/plugin.json +9 -2
  101. package/plugins/task/subagent.ts +119 -15
  102. package/plugins/todo/index.ts +4 -4
  103. package/plugins/tui/editor.ts +10 -2
  104. package/plugins/tui/frontend.ts +130 -25
  105. package/plugins/tui/index.ts +3 -8
  106. package/plugins/tui/markdown.ts +51 -6
  107. package/plugins/tui/mascot.ts +505 -0
  108. package/plugins/tui/mentions.ts +48 -8
  109. package/plugins/tui/plugin.json +2 -2
  110. package/plugins/tui/screen.ts +6 -0
  111. package/plugins/tui/transcript.ts +22 -3
  112. package/plugins/tui/tui.ts +323 -95
  113. package/plugins/tui/vendor.ts +16 -0
  114. package/plugins/undo/checkpoint.ts +26 -2
  115. package/plugins/undo/index.ts +86 -24
  116. package/plugins/undo/plugin.json +8 -2
  117. package/plugins/undo/snapshot.ts +129 -0
  118. package/plugins/update/index.ts +11 -15
  119. package/plugins/update/plugin.json +2 -1
  120. package/plugins/web/index.ts +2 -5
  121. package/plugins/web/renderers.ts +1 -1
  122. package/plugins/web/web.ts +6 -5
  123. package/plugins-dist/approval/index.js +232 -50
  124. package/plugins-dist/approval/plugin.json +5 -1
  125. package/plugins-dist/approval/policy.js +27 -5
  126. package/plugins-dist/ask/index.js +1 -1
  127. package/plugins-dist/budget/index.js +1 -1
  128. package/plugins-dist/checks/checks.js +2 -1
  129. package/plugins-dist/checks/index.js +1 -1
  130. package/plugins-dist/commands/index.js +1 -1
  131. package/plugins-dist/compact/compact.js +13 -2
  132. package/plugins-dist/compact/index.js +12 -8
  133. package/plugins-dist/continue/index.js +1 -1
  134. package/plugins-dist/cost/index.js +135 -0
  135. package/plugins-dist/cost/plugin.json +16 -0
  136. package/plugins-dist/custom-commands/index.js +86 -0
  137. package/plugins-dist/custom-commands/plugin.json +12 -0
  138. package/plugins-dist/editor/index.js +89 -0
  139. package/plugins-dist/editor/plugin.json +21 -0
  140. package/plugins-dist/fs/fs.js +106 -17
  141. package/plugins-dist/fs/grep.js +40 -12
  142. package/plugins-dist/fs/index.js +8 -5
  143. package/plugins-dist/hooks/index.js +145 -0
  144. package/plugins-dist/hooks/plugin.json +19 -0
  145. package/plugins-dist/keys/index.js +1 -1
  146. package/plugins-dist/mcp/index.js +41 -9
  147. package/plugins-dist/mcp/install.js +160 -0
  148. package/plugins-dist/mcp/mcp.js +2 -1
  149. package/plugins-dist/mcp/plugin.json +2 -1
  150. package/plugins-dist/mcp/project.js +42 -1
  151. package/plugins-dist/memory/index.js +3 -5
  152. package/plugins-dist/memory/plugin.json +1 -1
  153. package/plugins-dist/mentions/index.js +29 -11
  154. package/plugins-dist/models/configure.js +252 -151
  155. package/plugins-dist/models/context.js +2 -2
  156. package/plugins-dist/models/index.js +53 -16
  157. package/plugins-dist/models/plugin.json +1 -1
  158. package/plugins-dist/models/provider.js +4 -2
  159. package/plugins-dist/models/saved.js +9 -4
  160. package/plugins-dist/modes/index.js +1 -1
  161. package/plugins-dist/plugins/index.js +1 -1
  162. package/plugins-dist/print/index.js +62 -9
  163. package/plugins-dist/print/plugin.json +3 -0
  164. package/plugins-dist/prompts/index.js +49 -2
  165. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  166. package/plugins-dist/prompts/plugin.json +8 -2
  167. package/plugins-dist/prompts/prompts.js +13 -8
  168. package/plugins-dist/prompts/results.js +60 -0
  169. package/plugins-dist/prompts/sys.js +15 -3
  170. package/plugins-dist/renderers/index.js +1 -1
  171. package/plugins-dist/repeats/index.js +1 -1
  172. package/plugins-dist/schedule/index.js +1 -1
  173. package/plugins-dist/scratch/index.js +1 -1
  174. package/plugins-dist/screenshot/index.js +25 -11
  175. package/plugins-dist/screenshot/plugin.json +1 -1
  176. package/plugins-dist/sessions/index.js +1 -1
  177. package/plugins-dist/shell/index.js +55 -3
  178. package/plugins-dist/shell/plugin.json +3 -1
  179. package/plugins-dist/shell/shell.js +26 -8
  180. package/plugins-dist/skills/index.js +184 -35
  181. package/plugins-dist/skills/install.js +178 -0
  182. package/plugins-dist/skills/plugin.json +6 -2
  183. package/plugins-dist/skills/project.js +43 -1
  184. package/plugins-dist/skills/skills.js +27 -10
  185. package/plugins-dist/steer/index.js +135 -0
  186. package/plugins-dist/steer/plugin.json +12 -0
  187. package/plugins-dist/suggest/index.js +15 -9
  188. package/plugins-dist/suggest/plugin.json +1 -1
  189. package/plugins-dist/task/index.js +7 -4
  190. package/plugins-dist/task/plugin.json +10 -2
  191. package/plugins-dist/task/subagent.js +106 -15
  192. package/plugins-dist/todo/index.js +3 -3
  193. package/plugins-dist/tui/editor.js +7 -2
  194. package/plugins-dist/tui/frontend.js +135 -18
  195. package/plugins-dist/tui/index.js +2 -1
  196. package/plugins-dist/tui/markdown.js +48 -6
  197. package/plugins-dist/tui/mascot.js +439 -0
  198. package/plugins-dist/tui/mentions.js +44 -6
  199. package/plugins-dist/tui/plugin.json +3 -2
  200. package/plugins-dist/tui/screen.js +2 -0
  201. package/plugins-dist/tui/transcript.js +19 -2
  202. package/plugins-dist/tui/tui.js +303 -83
  203. package/plugins-dist/tui/vendor.js +13822 -0
  204. package/plugins-dist/undo/checkpoint.js +28 -1
  205. package/plugins-dist/undo/index.js +92 -22
  206. package/plugins-dist/undo/plugin.json +10 -3
  207. package/plugins-dist/undo/snapshot.js +111 -0
  208. package/plugins-dist/update/index.js +9 -10
  209. package/plugins-dist/update/plugin.json +4 -1
  210. package/plugins-dist/web/index.js +1 -1
  211. package/plugins-dist/web/web.js +6 -5
  212. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  213. package/sdk/python/jade_plugin.py +8 -0
  214. package/src/api.ts +7 -262
  215. package/src/fetch.ts +18 -16
  216. package/src/host.ts +49 -1
  217. package/src/index.ts +1 -1
  218. package/src/main.ts +25 -6
  219. package/src/remote.ts +2 -0
  220. package/src/session.ts +134 -15
  221. package/src/source.ts +2 -11
  222. package/src/update.ts +16 -10
  223. package/plugins/undo/notes.ts +0 -43
  224. package/plugins-dist/undo/notes.js +0 -36
@@ -9,35 +9,48 @@ import { readFileSync } from "node:fs";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
11
  import type { Block } from "uncarved";
12
- import type { Frontend, OpenOptions, Session, SessionManager, SessionUI, UI } from "../../src/api.ts";
13
- import type { CommandContext, Commands } from "../commands/index.ts";
14
- import type { Keys } from "../keys/index.ts";
15
- import type { Compact } from "../compact/index.ts";
16
- import type { Models } from "../models/index.ts";
17
- import type { Modes } from "../modes/index.ts";
18
- import type { Renderers } from "../renderers/index.ts";
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";
19
14
  import { InputHistory } from "./history.ts";
20
15
  import { mentionCandidates } from "./mentions.ts";
21
- import type { SessionIndex } from "../sessions/index.ts";
22
16
  import { dim, red, safeScreen, yellow, type CommandInfo, type Screen } from "./screen.ts";
23
17
  import { transcript, type Transcript } from "./transcript.ts";
24
- import { tuiScreen } from "./tui.ts";
18
+
19
+ /**
20
+ * 界面(ink、React)用到时才加载:--help、参数出错、不在终端里时都不需要它,导入一次要几百毫秒。
21
+ * React 在加载时按 NODE_ENV 选开发版或生产版,开发版做大量检查,流式输出时 CPU 翻倍。
22
+ * 用户没设 NODE_ENV 时只在加载期间设成 production,加载完还原,免得传给之后 shell 工具、MCP 等子进程。
23
+ * ink 依赖的 yoga 有顶层 await,只能异步加载,做不到同步设置再还原:加载期间还没有会话,工具和 MCP 都没启动,
24
+ * 这时可能启动的子进程只有 git(不读它)和后台的 npm 自动升级(全局安装本来就不装 devDependencies)。
25
+ * 编译好的 plugins-dist 里 ink、react 已打包成生产版(vendor.ts),这里设 NODE_ENV 只对直接跑源码(bun)时有用
26
+ */
27
+ async function loadTui(): Promise<typeof import("./tui.ts")> {
28
+ if (process.env.NODE_ENV !== undefined) return import("./tui.ts");
29
+ process.env.NODE_ENV = "production";
30
+ try {
31
+ return await import("./tui.ts");
32
+ } finally {
33
+ delete process.env.NODE_ENV;
34
+ }
35
+ }
25
36
 
26
37
  const USAGE = `usage: jade [prompt] [--resume <session id> | --continue]
27
38
 
28
39
  Starts the terminal interface. With a prompt, sends it first.
29
40
  -c, --continue continue the most recent session in this directory
30
41
  -r, --resume resume a session by id (inside jade, /resume lists them)
31
- Run one prompt without the interface: jade -p <prompt>`;
42
+ Run one prompt without the interface: jade -p <prompt> (jade -p --help for more)
43
+ jade's own commands (plugins, update, --safe): jade help`;
32
44
 
33
45
  /** 前端自己的命令:帮助和退出。其余命令都来自 commands@1 */
34
46
  const OWN: CommandInfo[] = [
35
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)" },
36
49
  { name: "exit", about: "quit (the session stays resumable)" },
37
50
  ];
38
51
 
39
52
  const KEYS =
40
- "Keys: enter send · \\ or alt+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";
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";
41
54
 
42
55
  /** 第二次 esc 算作"再按一次"的时间窗口 */
43
56
  const SECOND_ESC_MS = 3000;
@@ -71,6 +84,8 @@ export interface FrontendServices {
71
84
  compact?: Compact;
72
85
  /** 会话索引(jade/sessions),--continue 用 */
73
86
  index?: SessionIndex;
87
+ /** 一轮中途说的话(jade/steer):有它时,模型工作中提交的消息在下一次请求模型时就交给它,不等这一轮结束 */
88
+ steer?: Steer;
74
89
  }
75
90
 
76
91
  /** 状态栏上插件的一段最多显示这么多字符(超出的截断,换行并成空格) */
@@ -108,6 +123,13 @@ export class ScreenBridge {
108
123
  if (!this.screen) return undefined;
109
124
  return this.screen.input(req.title, { ...(req.initial ? { initial: req.initial } : {}), ...(req.placeholder ? { placeholder: req.placeholder } : {}), ...(req.mask ? { mask: true } : {}), ...(signal ? { signal } : {}) });
110
125
  },
126
+ copy: (text) => {
127
+ if (!this.screen?.copy) return false;
128
+ this.screen.copy(String(text));
129
+ return true;
130
+ },
131
+ // 界面没有占着终端(不是终端界面、还没起来)时没有什么要让的,直接执行
132
+ suspend: async (fn) => (this.screen?.suspend ? this.screen.suspend(fn) : fn()),
111
133
  session: ({ session, plugin }) => this.#sessionUI(session, plugin),
112
134
  };
113
135
 
@@ -231,7 +253,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
231
253
  return 2;
232
254
  }
233
255
 
234
- const { cwd, home, commands, keys, renderers, modes, models, compact, index } = services;
256
+ const { cwd, home, commands, keys, renderers, modes, models, compact, index, steer } = services;
235
257
  const sessions = opts.sessions;
236
258
  // --continue:这个目录里最近用过的会话(索引由 jade/sessions 在收到第一条消息时写)
237
259
  if (args.cont && !index) {
@@ -244,7 +266,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
244
266
  return 2;
245
267
  }
246
268
  const history = new InputHistory(path.join(home, "history.jsonl"), cwd);
247
- const [past, branch] = await Promise.all([history.load(), gitBranch(cwd)]);
269
+ const [past, branch, { tuiScreen }] = await Promise.all([history.load(), gitBranch(cwd), loadTui()]);
248
270
 
249
271
  /** 菜单里的命令:前端自己的 + 注册表里的,每次打开菜单时取 */
250
272
  const commandList = (): CommandInfo[] => [
@@ -314,6 +336,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
314
336
  screen,
315
337
  cwd,
316
338
  contextWindow: () => models?.current()?.contextWindow ?? 0,
339
+ maxTokens: () => models?.current()?.maxTokens,
317
340
  ...(compact ? { compactAt: () => compact.threshold() } : {}),
318
341
  canRetry,
319
342
  renderer: (tool) => renderers.forTool(tool),
@@ -381,6 +404,41 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
381
404
 
382
405
  /** 等待执行的输入:运行中提交的消息和需要独占会话的命令排在这里,按顺序执行 */
383
406
  const queue: string[] = [];
407
+ /**
408
+ * 已经交给 jade/steer、还没交给模型的话:下一次请求模型时它们就到模型那里;这一轮先结束了的取回来,
409
+ * 排到队列最前面当普通消息发。steer@1 出错时当作没有它
410
+ */
411
+ const steered = {
412
+ pending(): string[] {
413
+ try {
414
+ return current && steer ? steer.pending(current.id) : [];
415
+ } catch {
416
+ return [];
417
+ }
418
+ },
419
+ take(): string[] {
420
+ try {
421
+ return current && steer ? steer.take(current.id) : [];
422
+ } catch {
423
+ return [];
424
+ }
425
+ },
426
+ push(text: string): boolean {
427
+ try {
428
+ return current !== undefined && steer !== undefined && steer.push(current.id, text);
429
+ } catch {
430
+ return false;
431
+ }
432
+ },
433
+ };
434
+ /** 输入框上方显示的等待中的消息:中途说的话在前(它们先到模型那里) */
435
+ const showQueued = () => screen.queued([...steered.pending(), ...queue]);
436
+ let offSteer: (() => void) | undefined;
437
+ try {
438
+ offSteer = steer?.subscribe(showQueued);
439
+ } catch {
440
+ // 没有订阅上:交给模型之后显示的列表要等下一次变化才更新
441
+ }
384
442
  let running = false;
385
443
  let work: Promise<void> | undefined;
386
444
  let interruptedAt = 0;
@@ -422,13 +480,14 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
422
480
  for (const ac of commandAborts) ac.abort(new Error("interrupted by user"));
423
481
  current?.abort(new Error("interrupted by user"));
424
482
  screen.busy("Interrupting");
425
- if (queue.length === 0) return;
426
- const n = queue.length;
483
+ const n = queue.length + steered.pending().length;
484
+ if (n === 0) return;
427
485
  if (again) {
428
486
  if (takeBack()) screen.log(dim(`[moved ${n} queued message${n > 1 ? "s" : ""} back to the input]`));
429
487
  else {
488
+ steered.take();
430
489
  queue.length = 0;
431
- screen.queued(queue);
490
+ showQueued();
432
491
  screen.log(dim(`[cleared ${n} queued message${n > 1 ? "s" : ""}]`));
433
492
  }
434
493
  } else {
@@ -438,10 +497,10 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
438
497
 
439
498
  /** 排队的消息不再自动发送,放回输入框(在已经输入的内容前面,一条一行);没有可放回的返回 false */
440
499
  function takeBack(): boolean {
441
- if (queue.length === 0 || !screen.draft) return false;
500
+ if (!screen.draft || queue.length + steered.pending().length === 0) return false;
442
501
  const typed = screen.draft.text();
443
- screen.draft.set([...queue.splice(0), ...(typed.trim() ? [typed] : [])].join("\n"));
444
- screen.queued(queue);
502
+ screen.draft.set([...steered.take(), ...queue.splice(0), ...(typed.trim() ? [typed] : [])].join("\n"));
503
+ showQueued();
445
504
  return true;
446
505
  }
447
506
 
@@ -453,6 +512,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
453
512
  keyAbort.abort(new Error("exiting"));
454
513
  offMode?.();
455
514
  offModel?.();
515
+ offSteer?.();
456
516
  unsubscribe?.();
457
517
  await screen.close();
458
518
  bridge.detach();
@@ -475,6 +535,8 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
475
535
  });
476
536
  }
477
537
 
538
+ /** 输入是命令时返回命令名。第一个词里还有 / 的是路径(/c/Users/…、/usr/bin/x),当普通消息发给模型 */
539
+ const commandName = (text: string) => /^\/([^\s/]+)(?=\s|$)/.exec(text)?.[1]!.toLowerCase();
478
540
  const instant = (name: string) => OWN.some((o) => o.name === name) || name === "quit" || commands.get(name)?.command.instant === true;
479
541
 
480
542
  /** 执行一条命令;返回 false 表示退出 */
@@ -491,6 +553,17 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
491
553
  if (pluginKeys.length > 0) screen.log(dim(`Plugin keys: ${pluginKeys.map((k) => `${k.key}${k.description ? ` ${k.description}` : ""} (${k.plugin})`).join(" · ")}`));
492
554
  return true;
493
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
+ return true;
566
+ }
494
567
  const found = commands.get(name);
495
568
  if (!found) {
496
569
  screen.log(red(`unknown command /${name}; /help lists the commands`));
@@ -516,7 +589,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
516
589
 
517
590
  function onSubmit(text: string) {
518
591
  if (quitting) return;
519
- const name = text.startsWith("/") ? text.slice(1).split(/\s+/)[0]!.toLowerCase() : undefined;
592
+ const name = commandName(text);
520
593
  if (name !== undefined && instant(name)) {
521
594
  // 不碰会话的命令运行中也直接执行
522
595
  view.echo(text);
@@ -525,8 +598,16 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
525
598
  });
526
599
  return;
527
600
  }
601
+ // 模型正在工作、前面也没有别的在排队:这句话在下一次请求模型时就交给它(jade/steer),不等这一轮结束。
602
+ // 命令、已经有东西在排队时照旧排队,先后顺序不变
603
+ if (running && name === undefined && queue.length === 0 && steered.push(text)) {
604
+ showQueued();
605
+ // 没赶上这一轮的,等正在做的事做完再发(那时不一定是 pump 在跑,例如刚恢复会话)
606
+ void work?.catch(() => {}).then(() => pump());
607
+ return;
608
+ }
528
609
  queue.push(text);
529
- if (running) screen.queued(queue);
610
+ if (running) showQueued();
530
611
  void pump();
531
612
  }
532
613
 
@@ -534,13 +615,16 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
534
615
  if (running) return;
535
616
  let exit = false;
536
617
  await occupy(async () => {
537
- while (queue.length > 0 && !quitting) {
618
+ for (;;) {
619
+ // 中途说的话没赶上这一轮(模型没有再被请求就结束了):当普通消息发,排在后来排队的前面
620
+ queue.unshift(...steered.take());
621
+ if (queue.length === 0 || quitting) break;
538
622
  if (interruptPending) interruptedAt = Date.now();
539
623
  interruptPending = false;
540
624
  const text = queue.shift()!;
541
- screen.queued(queue);
625
+ showQueued();
542
626
  view.echo(text);
543
- if (text.startsWith("/")) {
627
+ if (commandName(text) !== undefined) {
544
628
  if (!(await command(text))) {
545
629
  exit = true;
546
630
  return;
@@ -573,7 +657,11 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
573
657
  } catch (e) {
574
658
  screen.log(red(`[error] ${errorText(e)}`));
575
659
  }
576
- if (!models?.current()) screen.log(yellow(`No model is configured yet. Put ANTHROPIC_API_KEY=... (or OPENAI_API_KEY=...) in ${path.join(home, ".env")}, then restart jade.`));
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
+ }
577
665
  else if (!resumed) screen.log(dim("Type / for commands, esc to interrupt."));
578
666
  ready = true;
579
667
  for (const text of [...(args.prompt ? [args.prompt] : []), ...early.splice(0)]) onSubmit(text);
@@ -582,6 +670,23 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
582
670
  }
583
671
 
584
672
  /** 当前分支;不在仓库里或没有 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
+
585
690
  function gitBranch(cwd: string): Promise<string | undefined> {
586
691
  return new Promise((resolve) => {
587
692
  execFile("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd, timeout: 2000, windowsHide: true }, (err, stdout) => resolve(err ? undefined : stdout.trim() || undefined));
@@ -1,13 +1,7 @@
1
1
  // jade/tui:终端界面,默认的前端。提供 frontend@1 和 ui@1;命令、快捷键、显示方式都来自注册表插件。
2
2
 
3
- import { definePlugin } from "../../src/api.ts";
4
- import type { Commands } from "../commands/index.ts";
5
- import type { Compact } from "../compact/index.ts";
6
- import type { Keys } from "../keys/index.ts";
7
- import type { Models } from "../models/index.ts";
8
- import type { Modes } from "../modes/index.ts";
9
- import type { Renderers } from "../renderers/index.ts";
10
- import type { SessionIndex } from "../sessions/index.ts";
3
+ import { definePlugin } from "@uncarved/jade-api";
4
+ import type { Commands, Compact, Keys, Models, Modes, Renderers, SessionIndex, Steer } from "@uncarved/jade-api/services";
11
5
  import { ScreenBridge, tuiFrontend } from "./frontend.ts";
12
6
 
13
7
  export default definePlugin({
@@ -27,6 +21,7 @@ export default definePlugin({
27
21
  ...optional("models", ctx.service<Models>("models@1")),
28
22
  ...optional("compact", ctx.service<Compact>("compact@1")),
29
23
  ...optional("index", ctx.service<SessionIndex>("sessions@1")),
24
+ ...optional("steer", ctx.service<Steer>("steer@1")),
30
25
  },
31
26
  bridge,
32
27
  ),
@@ -95,7 +95,52 @@ export function markdownStream(): MarkdownStream {
95
95
  export function renderMarkdown(text: string, width: number): string[] {
96
96
  const md = markdownStream();
97
97
  const out = [...text.split("\n").flatMap((l) => md.push(l)), ...md.flush()];
98
- return out.flatMap((l) => (typeof l === "string" ? [l] : l.render(width)));
98
+ return out.flatMap((l) => (typeof l === "string" ? [l] : l.render(width))).map(visibleRow);
99
+ }
100
+
101
+ // ---------- 自动折行的记号 ----------
102
+ //
103
+ // 一行太长折成屏幕上的几行时,后面的几行(续行)开头带一个看不见的记号:用鼠标选中复制时,续行接回上一行,
104
+ // 而不是变成换行。记号只用几个控制字符(显示之前去掉;外面来的文字里的控制字符早被 safeScreen 去掉了,不会撞上):
105
+ // \x1f \x1e × gap \x1d × indent \x1c
106
+ // gap:折行时上一行行尾去掉了几个空格,接回去时补上;indent:续行开头排版加的几列(列表的缩进、代码块的竖线),接回去时跳过
107
+
108
+ const SOFT_HEAD = /^\x1f(\x1e*)(\x1d*)\x1c/;
109
+
110
+ /** 把一行标成续行 */
111
+ export const softRow = (row: string, gap = 0, indent = 0): string => `\x1f${"\x1e".repeat(gap)}${"\x1d".repeat(indent)}\x1c${row}`;
112
+
113
+ /** 去掉记号,得到要显示的那一行 */
114
+ export const visibleRow = (row: string): string => (row.charCodeAt(0) === 0x1f ? row.replace(SOFT_HEAD, "") : row);
115
+
116
+ /** 一行是不是续行,以及接回上一行时要补的空格数、要跳过的列数;text 是去掉记号的那一行 */
117
+ export function softInfo(row: string): { text: string; soft: boolean; gap: number; indent: number } {
118
+ const m = row.charCodeAt(0) === 0x1f ? SOFT_HEAD.exec(row) : null;
119
+ if (!m) return { text: row, soft: false, gap: 0, indent: 0 };
120
+ return { text: row.slice(m[0].length), soft: true, gap: m[1]!.length, indent: m[2]!.length };
121
+ }
122
+
123
+ const WRAP = { hard: true, trim: false } as const;
124
+
125
+ /**
126
+ * 按显示宽度折行,保留颜色;每一项是屏幕上的一行,续行带记号。制表符先换成空格:按 0 列算宽度会对不齐、超宽。
127
+ * 不去掉空格(trim: false),所以续行直接接在上一行后面就是原文
128
+ */
129
+ export function wrapRows(text: string, width: number): string[] {
130
+ const expanded = expandTabs(text);
131
+ // 整段一起折:颜色可能跨行,分开折会丢掉后面几行的颜色
132
+ const rows = wrapAnsi(expanded, width, WRAP).split("\n");
133
+ const logical = expanded.split("\n");
134
+ if (rows.length === logical.length) return rows;
135
+ // 每个原来的行占了几行:放得下的占一行,放不下的单独折一次数出来(颜色不占宽度,不影响在哪里折)
136
+ const counts = logical.map((l) => (stringWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split("\n").length));
137
+ if (counts.reduce((a, b) => a + b, 0) !== rows.length) return rows;
138
+ let at = 0;
139
+ for (const n of counts) {
140
+ for (let i = 1; i < n; i++) rows[at + i] = softRow(rows[at + i]!);
141
+ at += n;
142
+ }
143
+ return rows;
99
144
  }
100
145
 
101
146
  /** 代码块和表格以外的一行 */
@@ -167,11 +212,11 @@ export function expandTabs(text: string, stop = 4): string {
167
212
  function hanging(head: string, body: string, rest = " ".repeat(stringWidth(head))): MdLine {
168
213
  return {
169
214
  render: (width) => {
170
- const room = Math.max(1, width - stringWidth(head));
171
- return wrapAnsi(expandTabs(body), room, { hard: true, trim: false })
172
- .split("\n")
173
- // 折行处留下的行尾空格看不见,去掉免得多占一列
174
- .map((r, i) => (i === 0 ? head : rest) + r.trimEnd());
215
+ const indent = stringWidth(head);
216
+ const room = Math.max(1, width - indent);
217
+ const rows = wrapAnsi(expandTabs(body), room, WRAP).split("\n");
218
+ // 折行处留下的行尾空格看不见,去掉免得多占一列;去掉了几个记在续行的记号里,复制时补回去
219
+ return rows.map((r, i) => (i === 0 ? head + r.trimEnd() : softRow(rest + r.trimEnd(), rows[i - 1]!.length - rows[i - 1]!.trimEnd().length, indent)));
175
220
  },
176
221
  };
177
222
  }