@uncarved/jade 0.3.1 → 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 (199) hide show
  1. package/dist/api.d.ts +1 -1
  2. package/dist/api.js +1 -1
  3. package/dist/host.d.ts +2 -0
  4. package/dist/host.js +39 -5
  5. package/dist/host.js.map +1 -1
  6. package/dist/remote.js +5 -0
  7. package/dist/remote.js.map +1 -1
  8. package/dist/session.d.ts +7 -0
  9. package/dist/session.js +482 -27
  10. package/dist/session.js.map +1 -1
  11. package/package.json +4 -4
  12. package/plugins/approval/index.ts +36 -14
  13. package/plugins/approval/policy.ts +15 -10
  14. package/plugins/approval/review.ts +9 -5
  15. package/plugins/checks/checks.ts +10 -7
  16. package/plugins/checks/index.ts +13 -13
  17. package/plugins/checks/plugin.json +1 -1
  18. package/plugins/checks/project.ts +37 -38
  19. package/plugins/commands/index.ts +27 -3
  20. package/plugins/compact/compact.ts +13 -5
  21. package/plugins/compact/index.ts +20 -3
  22. package/plugins/compact/style.ts +13 -14
  23. package/plugins/completions/index.ts +35 -0
  24. package/plugins/completions/plugin.json +7 -0
  25. package/plugins/copy/index.ts +46 -0
  26. package/plugins/copy/plugin.json +7 -0
  27. package/plugins/editor/index.ts +10 -4
  28. package/plugins/fs/diff.ts +7 -6
  29. package/plugins/fs/fs.ts +8 -4
  30. package/plugins/fs/grep.ts +42 -9
  31. package/plugins/fs/index.ts +2 -7
  32. package/plugins/fs/plugin.json +1 -1
  33. package/plugins/fs/renderers.ts +16 -15
  34. package/plugins/fs/style.ts +16 -15
  35. package/plugins/hooks/index.ts +3 -2
  36. package/plugins/keys/index.ts +5 -1
  37. package/plugins/mcp/index.ts +197 -78
  38. package/plugins/mcp/install.ts +5 -3
  39. package/plugins/mcp/mcp.ts +163 -11
  40. package/plugins/mcp/plugin.json +2 -1
  41. package/plugins/mcp/project.ts +47 -50
  42. package/plugins/memory/index.ts +4 -4
  43. package/plugins/memory/style.ts +13 -14
  44. package/plugins/mentions/candidates.ts +67 -0
  45. package/plugins/mentions/index.ts +12 -5
  46. package/plugins/mentions/plugin.json +1 -1
  47. package/plugins/mentions/style.ts +13 -14
  48. package/plugins/models/configure.ts +10 -9
  49. package/plugins/models/index.ts +27 -1
  50. package/plugins/modes/index.ts +13 -2
  51. package/plugins/print/index.ts +7 -4
  52. package/plugins/prompts/index.ts +0 -0
  53. package/plugins/renderers/index.ts +10 -5
  54. package/plugins/repeats/index.ts +8 -8
  55. package/plugins/schedule/index.ts +2 -0
  56. package/plugins/screenshot/browser.ts +10 -0
  57. package/plugins/sessions/index.ts +48 -2
  58. package/plugins/shell/index.ts +20 -25
  59. package/plugins/shell/plugin.json +1 -2
  60. package/plugins/shell/renderers.ts +9 -7
  61. package/plugins/shell/shell.ts +3 -1
  62. package/plugins/skills/index.ts +28 -19
  63. package/plugins/skills/project.ts +12 -7
  64. package/plugins/steer/index.ts +5 -4
  65. package/plugins/task/index.ts +80 -50
  66. package/plugins/task/plugin.json +6 -2
  67. package/plugins/task/style.ts +13 -14
  68. package/plugins/task/subagent.ts +67 -184
  69. package/plugins/todo/index.ts +39 -9
  70. package/plugins/tools/index.ts +9 -2
  71. package/plugins/tui/frontend.ts +139 -89
  72. package/plugins/tui/index.ts +2 -3
  73. package/plugins/tui/mentions.ts +11 -80
  74. package/plugins/tui/plugin.json +1 -1
  75. package/plugins/tui/screen.ts +55 -5
  76. package/plugins/tui/transcript.ts +17 -7
  77. package/plugins/tui/tui.ts +337 -101
  78. package/plugins/tui/vendor.ts +1 -1
  79. package/plugins/undo/checkpoint.ts +5 -3
  80. package/plugins/undo/index.ts +43 -14
  81. package/plugins/undo/style.ts +13 -14
  82. package/plugins/web/index.ts +7 -18
  83. package/plugins/web/plugin.json +1 -1
  84. package/plugins-dist/approval/index.js +363 -418
  85. package/plugins-dist/approval/policy.js +391 -508
  86. package/plugins-dist/approval/review.js +132 -158
  87. package/plugins-dist/approval/schema.js +50 -55
  88. package/plugins-dist/ask/index.js +115 -129
  89. package/plugins-dist/budget/index.js +27 -31
  90. package/plugins-dist/checks/checks.js +293 -329
  91. package/plugins-dist/checks/index.js +119 -139
  92. package/plugins-dist/checks/plugin.json +2 -1
  93. package/plugins-dist/checks/project.js +57 -65
  94. package/plugins-dist/commands/index.js +47 -29
  95. package/plugins-dist/compact/compact.js +233 -249
  96. package/plugins-dist/compact/index.js +98 -95
  97. package/plugins-dist/compact/style.js +9 -14
  98. package/plugins-dist/completions/index.js +30 -0
  99. package/plugins-dist/completions/plugin.json +9 -0
  100. package/plugins-dist/continue/index.js +40 -52
  101. package/plugins-dist/copy/index.js +40 -0
  102. package/plugins-dist/copy/plugin.json +9 -0
  103. package/plugins-dist/cost/index.js +98 -115
  104. package/plugins-dist/custom-commands/index.js +55 -72
  105. package/plugins-dist/editor/index.js +64 -72
  106. package/plugins-dist/fs/diff.js +111 -124
  107. package/plugins-dist/fs/fs.js +426 -469
  108. package/plugins-dist/fs/grep.js +262 -253
  109. package/plugins-dist/fs/index.js +20 -34
  110. package/plugins-dist/fs/plugin.json +1 -2
  111. package/plugins-dist/fs/renderers.js +100 -112
  112. package/plugins-dist/fs/style.js +11 -15
  113. package/plugins-dist/fs/sys.js +31 -43
  114. package/plugins-dist/hooks/index.js +107 -127
  115. package/plugins-dist/keys/index.js +27 -31
  116. package/plugins-dist/mcp/index.js +271 -199
  117. package/plugins-dist/mcp/install.js +123 -137
  118. package/plugins-dist/mcp/mcp.js +638 -577
  119. package/plugins-dist/mcp/plugin.json +3 -1
  120. package/plugins-dist/mcp/project.js +98 -115
  121. package/plugins-dist/memory/index.js +83 -88
  122. package/plugins-dist/memory/memory.js +111 -128
  123. package/plugins-dist/memory/style.js +9 -14
  124. package/plugins-dist/mentions/attach.js +91 -99
  125. package/plugins-dist/mentions/candidates.js +49 -0
  126. package/plugins-dist/mentions/index.js +71 -81
  127. package/plugins-dist/mentions/plugin.json +2 -1
  128. package/plugins-dist/mentions/style.js +9 -14
  129. package/plugins-dist/models/config.js +29 -43
  130. package/plugins-dist/models/configure.js +392 -473
  131. package/plugins-dist/models/context.js +14 -22
  132. package/plugins-dist/models/index.js +182 -189
  133. package/plugins-dist/models/provider.js +243 -307
  134. package/plugins-dist/models/saved.js +59 -71
  135. package/plugins-dist/modes/index.js +138 -165
  136. package/plugins-dist/plugins/index.js +34 -34
  137. package/plugins-dist/print/index.js +192 -175
  138. package/plugins-dist/prompts/index.js +81 -89
  139. package/plugins-dist/prompts/notes.js +31 -37
  140. package/plugins-dist/prompts/prompts.js +155 -193
  141. package/plugins-dist/prompts/results.js +40 -53
  142. package/plugins-dist/prompts/sys.js +39 -50
  143. package/plugins-dist/renderers/index.js +32 -32
  144. package/plugins-dist/repeats/index.js +131 -174
  145. package/plugins-dist/schedule/cron.js +49 -56
  146. package/plugins-dist/schedule/index.js +229 -247
  147. package/plugins-dist/schedule/store.js +93 -109
  148. package/plugins-dist/scratch/index.js +12 -18
  149. package/plugins-dist/screenshot/browser.js +136 -154
  150. package/plugins-dist/screenshot/index.js +37 -46
  151. package/plugins-dist/screenshot/sys.js +53 -65
  152. package/plugins-dist/screenshot/tool.js +98 -126
  153. package/plugins-dist/sessions/index.js +149 -117
  154. package/plugins-dist/shell/index.js +115 -135
  155. package/plugins-dist/shell/plugin.json +1 -2
  156. package/plugins-dist/shell/renderers.js +28 -33
  157. package/plugins-dist/shell/service.js +17 -23
  158. package/plugins-dist/shell/shell.js +307 -362
  159. package/plugins-dist/shell/sys.js +64 -79
  160. package/plugins-dist/skills/index.js +193 -211
  161. package/plugins-dist/skills/install.js +122 -149
  162. package/plugins-dist/skills/project.js +65 -73
  163. package/plugins-dist/skills/skills.js +135 -171
  164. package/plugins-dist/steer/index.js +108 -125
  165. package/plugins-dist/suggest/index.js +235 -259
  166. package/plugins-dist/task/index.js +130 -117
  167. package/plugins-dist/task/plugin.json +5 -2
  168. package/plugins-dist/task/style.js +9 -14
  169. package/plugins-dist/task/subagent.js +156 -279
  170. package/plugins-dist/todo/index.js +79 -63
  171. package/plugins-dist/tools/index.js +36 -42
  172. package/plugins-dist/tui/editor.js +145 -160
  173. package/plugins-dist/tui/frontend.js +639 -678
  174. package/plugins-dist/tui/history.js +34 -37
  175. package/plugins-dist/tui/index.js +16 -18
  176. package/plugins-dist/tui/markdown.js +203 -247
  177. package/plugins-dist/tui/mascot.js +266 -355
  178. package/plugins-dist/tui/mentions.js +67 -144
  179. package/plugins-dist/tui/plugin.json +1 -2
  180. package/plugins-dist/tui/render.js +35 -45
  181. package/plugins-dist/tui/screen.js +197 -180
  182. package/plugins-dist/tui/transcript.js +436 -468
  183. package/plugins-dist/tui/tui.js +1554 -1656
  184. package/plugins-dist/undo/checkpoint.js +95 -118
  185. package/plugins-dist/undo/index.js +185 -192
  186. package/plugins-dist/undo/snapshot.js +83 -99
  187. package/plugins-dist/undo/style.js +9 -14
  188. package/plugins-dist/update/index.js +26 -28
  189. package/plugins-dist/web/env.js +55 -68
  190. package/plugins-dist/web/index.js +80 -110
  191. package/plugins-dist/web/plugin.json +1 -2
  192. package/plugins-dist/web/renderers.js +4 -5
  193. package/plugins-dist/web/web.js +514 -593
  194. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  195. package/sdk/python/jade_plugin.py +9 -2
  196. package/src/api.ts +1 -1
  197. package/src/host.ts +39 -4
  198. package/src/remote.ts +6 -1
  199. package/src/session.ts +489 -34
@@ -1,34 +1,19 @@
1
- // jade/tui 的前端:把会话接到终端界面上。旧 jade 的 main.ts 里属于界面的部分:
2
- // 输入排队、斜杠命令、esc 中断、换会话后重新显示对话、状态栏。
3
- //
4
- // 这里不认识任何具体功能:命令来自 commands@1,快捷键来自 keys@1,工具和事件怎么显示来自 renderers@1,
5
- // 模式来自 modes@1,模型名来自 models@1。
6
1
  import { execFile } from "node:child_process";
7
2
  import { readFileSync } from "node:fs";
8
3
  import os from "node:os";
9
4
  import path from "node:path";
10
5
  import { InputHistory } from "./history.js";
11
- import { mentionCandidates } from "./mentions.js";
12
- import { dim, red, safeScreen, yellow } from "./screen.js";
6
+ import { ansi, dim, red, safeScreen, yellow } from "./screen.js";
13
7
  import { transcript } from "./transcript.js";
14
- /**
15
- * 界面(ink、React)用到时才加载:--help、参数出错、不在终端里时都不需要它,导入一次要几百毫秒。
16
- * React 在加载时按 NODE_ENV 选开发版或生产版,开发版做大量检查,流式输出时 CPU 翻倍。
17
- * 用户没设 NODE_ENV 时只在加载期间设成 production,加载完还原,免得传给之后 shell 工具、MCP 等子进程。
18
- * ink 依赖的 yoga 有顶层 await,只能异步加载,做不到同步设置再还原:加载期间还没有会话,工具和 MCP 都没启动,
19
- * 这时可能启动的子进程只有 git(不读它)和后台的 npm 自动升级(全局安装本来就不装 devDependencies)。
20
- * 编译好的 plugins-dist 里 ink、react 已打包成生产版(vendor.ts),这里设 NODE_ENV 只对直接跑源码(bun)时有用
21
- */
22
8
  async function loadTui() {
23
- if (process.env.NODE_ENV !== undefined)
24
- return import("./tui.js");
25
- process.env.NODE_ENV = "production";
26
- try {
27
- return await import("./tui.js");
28
- }
29
- finally {
30
- delete process.env.NODE_ENV;
31
- }
9
+ if (true)
10
+ return import("./tui.js");
11
+ process.env.NODE_ENV = "production";
12
+ try {
13
+ return await import("./tui.js");
14
+ } finally {
15
+ delete "development";
16
+ }
32
17
  }
33
18
  const USAGE = `usage: jade [prompt] [--resume <session id> | --continue]
34
19
 
@@ -37,692 +22,668 @@ Starts the terminal interface. With a prompt, sends it first.
37
22
  -r, --resume resume a session by id (inside jade, /resume lists them)
38
23
  Run one prompt without the interface: jade -p <prompt> (jade -p --help for more)
39
24
  jade's own commands (plugins, update, --safe): jade help`;
40
- /** 前端自己的命令:帮助和退出。其余命令都来自 commands@1 */
41
25
  const OWN = [
42
- { name: "help", about: "list the commands and keys" },
43
- { name: "copy", args: "[code]", about: "copy the last reply to the clipboard as it was written (code: only its last code block)" },
44
- { name: "exit", about: "quit (the session stays resumable)" },
26
+ { name: "help", about: "list the commands and keys" },
27
+ { name: "exit", about: "quit (the session stays resumable)" }
45
28
  ];
46
- const KEYS = "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";
47
- /** 退出时最多等正在做的事这么久 */
29
+ const KEYS = [
30
+ "Keys:",
31
+ " send enter send · ctrl+j, alt+enter or \\ then enter: new line · tab completes /commands",
32
+ " input ↑↓ history · ctrl+r search history · ↑ on the first line edits queued messages · esc twice or ctrl+c clears the input",
33
+ " 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",
34
+ " running esc interrupt (twice to also move queued messages back to the input) · ctrl+c twice to exit",
35
+ " 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"
36
+ ].join(`
37
+ `);
38
+ const paint = (v) => v === undefined || v === null ? undefined : ansi(v);
39
+ function ansiTool(r) {
40
+ const out = { tool: r.tool };
41
+ if (r.summary)
42
+ out.summary = (i) => paint(r.summary(i));
43
+ if (r.details)
44
+ out.details = (i) => paint(r.details(i));
45
+ if (r.call)
46
+ out.call = (i) => paint(r.call(i));
47
+ if (r.progress)
48
+ out.progress = (u, c) => paint(r.progress(u, c));
49
+ if (r.preview)
50
+ out.preview = async (i) => paint(await r.preview(i));
51
+ if (r.before)
52
+ out.before = (i) => r.before(i);
53
+ if (r.result)
54
+ out.result = (x) => {
55
+ const o = r.result(x);
56
+ return o ? { line: ansi(o.line), ...o.details !== undefined ? { details: ansi(o.details) } : {} } : o;
57
+ };
58
+ return out;
59
+ }
60
+ function ansiEvent(r) {
61
+ return {
62
+ event: r.event,
63
+ render: (data) => {
64
+ const o = r.render(data);
65
+ return o && { line: ansi(o.line), ...o.details !== undefined ? { details: ansi(o.details) } : {} };
66
+ }
67
+ };
68
+ }
69
+ const isPrompt = (r) => typeof r === "object" && r !== null && !Array.isArray(r) && typeof r.prompt === "string";
48
70
  const QUIT_WAIT_MS = 3000;
49
- /** 命令运行中的临时显示(CommandContext.progress)最多占几行 */
50
71
  const LIVE_ROWS = 8;
51
- /** 第二次 esc 算作"再按一次"的时间窗口 */
52
72
  const SECOND_ESC_MS = 3000;
53
73
  const VERSION = (() => {
54
- try {
55
- return JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
56
- }
57
- catch {
58
- return "";
59
- }
74
+ try {
75
+ return JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
76
+ } catch {
77
+ return "";
78
+ }
60
79
  })();
61
80
  const errorText = (e) => {
62
- // 经过膜的错误包着插件的名字;用户要看的是原因
63
- const cause = e instanceof Error && e.name === "PluginError" && e.cause instanceof Error ? e.cause : e;
64
- return cause instanceof Error ? cause.message : String(cause);
81
+ const cause = e instanceof Error && e.name === "PluginError" && e.cause instanceof Error ? e.cause : e;
82
+ return cause instanceof Error ? cause.message : String(cause);
65
83
  };
66
- /** 测试用:换掉终端(假的 stdin、stdout)。不设时用 process.stdin、process.stdout */
67
84
  export const terminal = {};
68
- /** 状态栏上插件的一段最多显示这么多字符(超出的截断,换行并成空格) */
69
85
  const MAX_SEGMENT = 80;
70
- /**
71
- * ui@1:界面出来之前的提示先攒着,出来之后显示;界面关掉之后写到 stderr。
72
- * 前端运行期间才能提问;会话里的插件经 UI.session 拿到自己的状态栏段落和输入框(4.3)
73
- */
86
+ const MAX_PANEL_LINES = 10;
87
+
74
88
  export class ScreenBridge {
75
- screen;
76
- #early = [];
77
- /** 会话打开期间的提示:打开之后要清屏,先攒着,清屏之后再显示 */
78
- #held;
79
- #closed = false;
80
- /** 状态栏上各插件的一段:会话 id → 插件 id → 文字 */
81
- #segments = new Map();
82
- /** 界面现在显示哪个会话;换会话时由前端调用 show */
83
- #session;
84
- ui = {
85
- interactive: true,
86
- notify: (message, level = "info") => {
87
- const text = level === "error" ? red(`[error] ${message}`) : level === "warning" ? yellow(`[warning] ${message}`) : dim(message);
88
- if (this.#held)
89
- this.#held.push(text);
90
- else if (this.screen)
91
- this.screen.log(text);
92
- else if (this.#closed)
93
- process.stderr.write(`jade: ${message}\n`);
94
- else
95
- this.#early.push(text);
96
- },
97
- select: async (req, signal) => {
98
- if (!this.screen)
99
- return undefined;
100
- 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 } : {}) });
101
- },
102
- input: async (req, signal) => {
103
- if (!this.screen)
104
- return undefined;
105
- return this.screen.input(req.title, { ...(req.initial ? { initial: req.initial } : {}), ...(req.placeholder ? { placeholder: req.placeholder } : {}), ...(req.mask ? { mask: true } : {}), ...(signal ? { signal } : {}) });
106
- },
107
- copy: (text) => {
108
- if (!this.screen?.copy)
109
- return false;
110
- this.screen.copy(String(text));
111
- return true;
112
- },
113
- // 界面没有占着终端(不是终端界面、还没起来)时没有什么要让的,直接执行
114
- suspend: async (fn) => (this.screen?.suspend ? this.screen.suspend(fn) : fn()),
115
- session: ({ session, plugin }) => this.#sessionUI(session, plugin),
89
+ screen;
90
+ #early = [];
91
+ #held;
92
+ #closed = false;
93
+ #segments = new Map;
94
+ #panels = new Map;
95
+ #session;
96
+ ui = {
97
+ interactive: true,
98
+ notify: (message, level = "info") => {
99
+ const text = level === "error" ? red(`[error] ${message}`) : level === "warning" ? yellow(`[warning] ${message}`) : dim(message);
100
+ if (this.#held)
101
+ this.#held.push(text);
102
+ else if (this.screen)
103
+ this.screen.log(text);
104
+ else if (this.#closed)
105
+ process.stderr.write(`jade: ${message}
106
+ `);
107
+ else
108
+ this.#early.push(text);
109
+ },
110
+ select: async (req, signal) => {
111
+ if (!this.screen)
112
+ return;
113
+ 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 } : {} });
114
+ },
115
+ input: async (req, signal) => {
116
+ if (!this.screen)
117
+ return;
118
+ return this.screen.input(req.title, { ...req.initial ? { initial: req.initial } : {}, ...req.placeholder ? { placeholder: req.placeholder } : {}, ...req.mask ? { mask: true } : {}, ...signal ? { signal } : {} });
119
+ },
120
+ copy: (text) => {
121
+ if (!this.screen?.copy)
122
+ return false;
123
+ this.screen.copy(String(text));
124
+ return true;
125
+ },
126
+ suspend: async (fn) => this.screen?.suspend ? this.screen.suspend(fn) : fn(),
127
+ session: ({ session, plugin }) => this.#sessionUI(session, plugin)
128
+ };
129
+ attach(screen) {
130
+ this.screen = screen;
131
+ for (const t of this.#early.splice(0))
132
+ screen.log(t);
133
+ }
134
+ hold() {
135
+ this.#held ??= [];
136
+ }
137
+ release() {
138
+ const held = this.#held ?? [];
139
+ this.#held = undefined;
140
+ for (const t of held) {
141
+ if (this.screen)
142
+ this.screen.log(t);
143
+ else
144
+ this.#early.push(t);
145
+ }
146
+ }
147
+ detach() {
148
+ this.screen = undefined;
149
+ this.#closed = true;
150
+ }
151
+ show(session) {
152
+ this.#session = session;
153
+ this.#apply();
154
+ }
155
+ #apply() {
156
+ if (!this.screen)
157
+ return;
158
+ const segments = this.#session === undefined ? undefined : this.#segments.get(this.#session);
159
+ const panels = this.#session === undefined ? undefined : this.#panels.get(this.#session);
160
+ this.screen.status({
161
+ plugins: [...segments ?? []].map(([plugin, text]) => ({ plugin, text })),
162
+ panels: [...panels ?? []].map(([plugin, text]) => ({ plugin, text }))
163
+ });
164
+ }
165
+ #sessionUI(session, plugin) {
166
+ const bridge = this;
167
+ let gone = false;
168
+ const apply = () => {
169
+ if (bridge.#session === session)
170
+ bridge.#apply();
116
171
  };
117
- attach(screen) {
118
- this.screen = screen;
119
- for (const t of this.#early.splice(0))
120
- screen.log(t);
121
- }
122
- /** 开始攒提示,直到 release */
123
- hold() {
124
- this.#held ??= [];
125
- }
126
- /** 显示攒下的提示,之后的照常显示 */
127
- release() {
128
- const held = this.#held ?? [];
129
- this.#held = undefined;
130
- for (const t of held) {
131
- if (this.screen)
132
- this.screen.log(t);
133
- else
134
- this.#early.push(t);
172
+ const put = (all, text) => {
173
+ if (gone)
174
+ return;
175
+ let mine = all.get(session);
176
+ if (text === undefined)
177
+ mine?.delete(plugin);
178
+ else {
179
+ if (!mine)
180
+ all.set(session, mine = new Map);
181
+ mine.set(plugin, text);
182
+ }
183
+ apply();
184
+ };
185
+ return {
186
+ status: (text) => put(bridge.#segments, text === undefined ? undefined : clipSegment(text)),
187
+ panel: (text) => put(bridge.#panels, text === undefined ? undefined : clipPanel(ansi(text))),
188
+ draft: {
189
+ text: () => bridge.screen?.draft?.text() ?? "",
190
+ insert: (text) => bridge.screen?.draft?.insert(text),
191
+ set: (text) => bridge.screen?.draft?.set(text),
192
+ hint: (text) => bridge.screen?.draft?.hint(text)
193
+ },
194
+ dispose() {
195
+ gone = true;
196
+ for (const all of [bridge.#segments, bridge.#panels]) {
197
+ const mine = all.get(session);
198
+ mine?.delete(plugin);
199
+ if (mine?.size === 0)
200
+ all.delete(session);
135
201
  }
136
- }
137
- detach() {
138
- this.screen = undefined;
139
- this.#closed = true;
140
- }
141
- /** 界面换到另一个会话:显示它的插件段落(之前那个会话的留着,换回去还在) */
142
- show(session) {
143
- this.#session = session;
144
- this.#apply();
145
- }
146
- #apply() {
147
- if (!this.screen)
148
- return;
149
- const segments = this.#session === undefined ? undefined : this.#segments.get(this.#session);
150
- this.screen.status({ plugins: [...(segments ?? [])].map(([plugin, text]) => ({ plugin, text })) });
151
- }
152
- /** 一个插件在一个会话里的界面。作用域关闭时核心调用 dispose,这里把它的段落去掉 */
153
- #sessionUI(session, plugin) {
154
- const bridge = this;
155
- let gone = false;
156
- const apply = () => {
157
- if (bridge.#session === session)
158
- bridge.#apply();
159
- };
160
- return {
161
- status(text) {
162
- if (gone)
163
- return;
164
- // 每次现取:别的插件 dispose 可能已经把空的 map 删了
165
- let segments = bridge.#segments.get(session);
166
- if (text === undefined)
167
- segments?.delete(plugin);
168
- else {
169
- if (!segments)
170
- bridge.#segments.set(session, (segments = new Map()));
171
- segments.set(plugin, clipSegment(text));
172
- }
173
- apply();
174
- },
175
- draft: {
176
- text: () => bridge.screen?.draft?.text() ?? "",
177
- insert: (text) => bridge.screen?.draft?.insert(text),
178
- set: (text) => bridge.screen?.draft?.set(text),
179
- hint: (text) => bridge.screen?.draft?.hint(text),
180
- },
181
- dispose() {
182
- gone = true;
183
- const segments = bridge.#segments.get(session);
184
- segments?.delete(plugin);
185
- if (segments?.size === 0)
186
- bridge.#segments.delete(session);
187
- apply();
188
- },
189
- };
190
- }
202
+ apply();
203
+ }
204
+ };
205
+ }
206
+ }
207
+ function clipPanel(text) {
208
+ const lines = String(text).replace(/\r\n?/g, `
209
+ `).replace(/\n+$/, "").split(`
210
+ `);
211
+ return lines.length > MAX_PANEL_LINES ? [...lines.slice(0, MAX_PANEL_LINES - 1), ` … ${lines.length - MAX_PANEL_LINES + 1} more`].join(`
212
+ `) : lines.join(`
213
+ `);
191
214
  }
192
- /** 状态栏的一段是一行:空白并成一个空格,长的截断 */
193
- function clipSegment(text) {
215
+ function clipSegment(segment) {
216
+ const clip = (text) => {
194
217
  const one = String(text).replace(/\s+/g, " ").trim();
195
218
  return one.length > MAX_SEGMENT ? `${one.slice(0, MAX_SEGMENT - 1)}…` : one;
219
+ };
220
+ if (typeof segment === "string")
221
+ return clip(segment);
222
+ return { ...segment, text: clip(segment.text), ...segment.short !== undefined ? { short: clip(segment.short) } : {} };
196
223
  }
197
224
  export function tuiFrontend(services, bridge) {
198
- return {
199
- run: (opts) => run(services, bridge, opts),
200
- };
225
+ return {
226
+ run: (opts) => run(services, bridge, opts)
227
+ };
201
228
  }
202
229
  function parse(argv) {
203
- const out = {};
204
- const words = [];
205
- for (let i = 0; i < argv.length; i++) {
206
- const a = argv[i];
207
- if (a === "-h" || a === "--help")
208
- out.help = true;
209
- else if (a === "-c" || a === "--continue")
210
- out.cont = true;
211
- else if (a === "--resume" || a === "-r") {
212
- const id = argv[++i];
213
- if (!id)
214
- return `${a} needs a session id (inside jade, /resume lists the sessions)`;
215
- out.resume = id;
216
- }
217
- else if (a.startsWith("-"))
218
- return `unknown option ${a}`;
219
- else
220
- words.push(a);
221
- }
222
- if (out.cont && out.resume)
223
- return "--continue and --resume both pick the session; use one of them";
224
- if (words.length > 0)
225
- out.prompt = words.join(" ");
226
- return out;
230
+ const out = {};
231
+ const words = [];
232
+ for (let i = 0;i < argv.length; i++) {
233
+ const a = argv[i];
234
+ if (a === "-h" || a === "--help")
235
+ out.help = true;
236
+ else if (a === "-c" || a === "--continue")
237
+ out.cont = true;
238
+ else if (a === "--resume" || a === "-r") {
239
+ const id = argv[++i];
240
+ if (!id)
241
+ return `${a} needs a session id (inside jade, /resume lists the sessions)`;
242
+ out.resume = id;
243
+ } else if (a.startsWith("-"))
244
+ return `unknown option ${a}`;
245
+ else
246
+ words.push(a);
247
+ }
248
+ if (out.cont && out.resume)
249
+ return "--continue and --resume both pick the session; use one of them";
250
+ if (words.length > 0)
251
+ out.prompt = words.join(" ");
252
+ return out;
227
253
  }
228
254
  async function run(services, bridge, opts) {
229
- const args = parse(opts.argv);
230
- if (typeof args === "string") {
231
- process.stderr.write(`${args}\n\n${USAGE}\n`);
232
- return 2;
233
- }
234
- if (args.help) {
235
- process.stdout.write(`${USAGE}\n`);
236
- return 0;
237
- }
238
- const io = terminal.io;
239
- if (!(io ?? process).stdin.isTTY || !(io ?? process).stdout.isTTY) {
240
- process.stderr.write(`jade's terminal interface needs a terminal. To run one prompt, use: jade -p <prompt>\n`);
241
- return 2;
242
- }
243
- const { cwd, home, commands, keys, renderers, modes, models, compact, index, steer } = services;
244
- const sessions = opts.sessions;
245
- // --continue:这个目录里最近用过的会话(索引由 jade/sessions 在收到第一条消息时写)
246
- if (args.cont && !index) {
247
- process.stderr.write("jade: --continue needs the jade/sessions plugin, which is not enabled\n");
248
- return 2;
249
- }
250
- const resumed = args.cont ? (await index.list(cwd))[0]?.id : args.resume;
251
- if (args.cont && !resumed) {
252
- process.stderr.write(`jade: no session to continue in ${cwd}\n`);
253
- return 2;
254
- }
255
- const history = new InputHistory(path.join(home, "history.jsonl"), cwd);
256
- const [past, branch, { tuiScreen }] = await Promise.all([history.load(), gitBranch(cwd), loadTui()]);
257
- /** 菜单里的命令:前端自己的 + 注册表里的,每次打开菜单时取 */
258
- const commandList = () => [
259
- ...OWN,
260
- ...commands
261
- .list()
262
- .filter((c) => !OWN.some((o) => o.name === c.name))
263
- .map((c) => ({ name: c.name, ...(c.args ? { args: c.args } : {}), about: `${c.description ?? ""}${c.plugin.startsWith("jade/") ? "" : ` (plugin ${c.plugin})`}`.trim() })),
264
- ];
265
- let ready = false;
266
- const early = [];
267
- let finish;
268
- const finished = new Promise((r) => (finish = r));
269
- // 插件、工具输出和模型的文字都经过 safeScreen 显示:只留颜色,去掉能搅乱终端的控制序列
270
- const screen = safeScreen(tuiScreen({
271
- status: { cwd: shortPath(cwd), ...(branch ? { branch } : {}), model: models?.current()?.model ?? "(no model)", mode: modes?.current() ?? "" },
272
- version: VERSION,
273
- commands: commandList,
274
- history: past,
275
- ...(io ? { io } : {}),
276
- handlers: {
277
- submit: (text) => {
278
- history.add(text).catch(() => { });
279
- if (ready)
280
- onSubmit(text);
281
- else
282
- early.push(text);
283
- },
284
- // 输入 @ 时列工作目录里的文件
285
- files: () => mentionCandidates(cwd),
286
- interrupt: () => ready && interrupt(),
287
- unqueue: () => takeBack(),
288
- exit: () => void quit(0),
289
- cycleMode: () => void key("shift+tab"),
290
- key: (spec) => key(spec),
291
- },
292
- }));
293
- bridge.attach(screen);
294
- const keyAbort = new AbortController();
295
- /** 插件的快捷键:找到了就在后台执行 */
296
- function key(spec) {
297
- const found = keys.get(spec);
298
- if (!found)
299
- return false;
300
- const signal = keyAbort.signal;
301
- Promise.resolve()
302
- .then(() => found.key.run({ key: spec, signal }))
303
- .catch((e) => {
304
- if (!signal.aborted)
305
- screen.log(yellow(`[warning] plugin ${found.plugin}: ${spec} failed: ${errorText(e)}`));
306
- });
307
- return true;
308
- }
309
- const offMode = modes?.subscribe((mode) => screen.status({ mode }));
310
- // /model 换了配置:状态栏跟着换
311
- const offModel = models?.subscribe?.(() => screen.status({ model: models.current()?.model ?? "(no model)" }));
312
- // ---------- 会话 ----------
313
- let current;
314
- let unsubscribe;
315
- const canRetry = () => current?.state.phase === "idle" && current.state.messages.at(-1)?.role === "user";
316
- const view = transcript({
317
- screen,
318
- cwd,
319
- contextWindow: () => models?.current()?.contextWindow ?? 0,
320
- maxTokens: () => models?.current()?.maxTokens,
321
- ...(compact ? { compactAt: () => compact.threshold() } : {}),
322
- canRetry,
323
- renderer: (tool) => renderers.forTool(tool),
324
- eventRenderer: (type) => renderers.forEvent(type),
255
+ const args = parse(opts.argv);
256
+ if (typeof args === "string") {
257
+ process.stderr.write(`${args}
258
+
259
+ ${USAGE}
260
+ `);
261
+ return 2;
262
+ }
263
+ if (args.help) {
264
+ process.stdout.write(`${USAGE}
265
+ `);
266
+ return 0;
267
+ }
268
+ const io = terminal.io;
269
+ if (!(io ?? process).stdin.isTTY || !(io ?? process).stdout.isTTY) {
270
+ process.stderr.write(`jade's terminal interface needs a terminal. To run one prompt, use: jade -p <prompt>
271
+ `);
272
+ return 2;
273
+ }
274
+ const { cwd, home, commands, keys, renderers, models, completions, index, steer } = services;
275
+ const sessions = opts.sessions;
276
+ if (args.cont && !index) {
277
+ process.stderr.write(`jade: --continue needs the jade/sessions plugin, which is not enabled
278
+ `);
279
+ return 2;
280
+ }
281
+ const resumed = args.cont ? (await index.list(cwd))[0]?.id : args.resume;
282
+ if (args.cont && !resumed) {
283
+ process.stderr.write(`jade: no session to continue in ${cwd}
284
+ `);
285
+ return 2;
286
+ }
287
+ const history = new InputHistory(path.join(home, "history.jsonl"), cwd);
288
+ const [past, branch, { tuiScreen }] = await Promise.all([history.load(), gitBranch(cwd), loadTui()]);
289
+ const commandList = () => [
290
+ ...OWN,
291
+ ...commands.list().filter((c) => !OWN.some((o) => o.name === c.name)).map((c) => ({
292
+ name: c.name,
293
+ ...c.args ? { args: c.args } : {},
294
+ ...c.prefix ? { prefix: c.prefix, ...c.prefixHint ? { prefixHint: c.prefixHint } : {} } : {},
295
+ about: `${c.description ?? ""}${c.plugin.startsWith("jade/") ? "" : ` (plugin ${c.plugin})`}`.trim()
296
+ }))
297
+ ];
298
+ const completionList = () => (completions?.list() ?? []).map(({ completion: c }) => ({ trigger: c.trigger, label: c.label, ...c.hint ? { hint: c.hint } : {} }));
299
+ let ready = false;
300
+ const early = [];
301
+ let finish;
302
+ const finished = new Promise((r) => finish = r);
303
+ const screen = safeScreen(tuiScreen({
304
+ status: { cwd: shortPath(cwd), ...branch ? { branch } : {}, model: models?.current()?.model ?? "(no model)" },
305
+ version: VERSION,
306
+ commands: commandList,
307
+ history: past,
308
+ ...io ? { io } : {},
309
+ handlers: {
310
+ submit: (text) => {
311
+ history.add(text).catch(() => {});
312
+ if (ready)
313
+ onSubmit(text);
314
+ else
315
+ early.push(text);
316
+ },
317
+ completions: completionList,
318
+ complete: async (trigger) => await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates() ?? [],
319
+ interrupt: () => ready && interrupt(),
320
+ unqueue: () => takeBack(),
321
+ exit: () => void quit(0),
322
+ key: (spec) => key(spec)
323
+ }
324
+ }));
325
+ bridge.attach(screen);
326
+ const keyAbort = new AbortController;
327
+ function key(spec) {
328
+ const found = keys.get(spec);
329
+ if (!found)
330
+ return false;
331
+ const signal = keyAbort.signal;
332
+ Promise.resolve().then(() => found.key.run({ key: spec, signal })).catch((e) => {
333
+ if (!signal.aborted)
334
+ screen.log(yellow(`[warning] plugin ${found.plugin}: ${spec} failed: ${errorText(e)}`));
325
335
  });
326
- /** 换成另一个会话:清屏,恢复的会话重新显示之前的对话,然后继续日志里没做完的工作 */
327
- async function adopt(s, resumed) {
328
- unsubscribe?.();
329
- current = s;
330
- view.reset();
331
- screen.clear();
332
- screen.status({ session: s.id, context: undefined, cache: undefined, spent: undefined, speed: undefined });
333
- // 状态栏上插件自己的段落跟着换:新会话的显示出来,旧会话的留着(换回去还在)
334
- bridge.show(s.id);
335
- if (resumed)
336
- await view.replay(await s.history(), true);
336
+ return true;
337
+ }
338
+ const offModel = models?.subscribe?.(() => screen.status({ model: models.current()?.model ?? "(no model)" }));
339
+ let current;
340
+ let unsubscribe;
341
+ const canRetry = () => current?.state.phase === "idle" && current.state.messages.at(-1)?.role === "user";
342
+ const view = transcript({
343
+ screen,
344
+ cwd,
345
+ contextWindow: () => models?.current()?.contextWindow ?? 0,
346
+ maxTokens: () => models?.current()?.maxTokens,
347
+ canRetry,
348
+ renderer: (tool) => {
349
+ const found = renderers.forTool(tool);
350
+ return found && { plugin: found.plugin, renderer: ansiTool(found.renderer) };
351
+ },
352
+ eventRenderer: (type) => {
353
+ const found = renderers.forEvent(type);
354
+ return found && { plugin: found.plugin, renderer: ansiEvent(found.renderer) };
355
+ }
356
+ });
357
+ async function adopt(s, resumed) {
358
+ unsubscribe?.();
359
+ current = s;
360
+ view.reset();
361
+ screen.clear();
362
+ screen.status({ session: s.id, context: undefined, cache: undefined, spent: undefined, speed: undefined });
363
+ bridge.show(s.id);
364
+ if (resumed)
365
+ await view.replay(await s.history(), true);
366
+ bridge.release();
367
+ unsubscribe = s.subscribe(view.onNotice);
368
+ if (!resumed)
369
+ return;
370
+ const held = s.state.held;
371
+ if (held) {
372
+ screen.log(yellow(`Plugins changed since this session was last used: ${held.plugins.map((p) => `${p.id}@${p.version}`).join(", ")}`));
373
+ if (held.resolution === "abort") {
374
+ screen.log(red("A plugin requires this session to stop. Restore the previous plugins to continue it, or /clear to start a new one."));
375
+ return;
376
+ }
377
+ const ok = await screen.select("Continue with the new plugins? Pending tool calls will be re-checked.", [
378
+ { label: "Yes, continue", value: true },
379
+ { label: "No", value: false }
380
+ ]) ?? false;
381
+ await guarded(() => s.send({ kind: "plugins", approved: ok }));
382
+ if (!ok)
383
+ return;
384
+ }
385
+ await guarded(() => s.recover());
386
+ screen.log(dim(`Resumed ${s.id} (${s.state.messages.length} messages)`));
387
+ }
388
+ const manager = {
389
+ get current() {
390
+ return sessions.current;
391
+ },
392
+ async open(o) {
393
+ bridge.hold();
394
+ try {
395
+ const s = await sessions.open(o);
396
+ await adopt(s, o?.resume !== undefined || o?.fork !== undefined);
397
+ return s;
398
+ } finally {
337
399
  bridge.release();
338
- unsubscribe = s.subscribe(view.onNotice);
339
- if (!resumed)
340
- return;
341
- const held = s.state.held;
342
- if (held) {
343
- screen.log(yellow(`Plugins changed since this session was last used: ${held.plugins.map((p) => `${p.id}@${p.version}`).join(", ")}`));
344
- if (held.resolution === "abort") {
345
- screen.log(red("A plugin requires this session to stop. Restore the previous plugins to continue it, or /clear to start a new one."));
346
- return;
347
- }
348
- const ok = (await screen.select("Continue with the new plugins? Pending tool calls will be re-checked.", [
349
- { label: "Yes, continue", value: true },
350
- { label: "No", value: false },
351
- ])) ?? false;
352
- await guarded(() => s.send({ kind: "plugins", approved: ok }));
353
- if (!ok)
354
- return;
355
- }
356
- await guarded(() => s.recover());
357
- screen.log(dim(`Resumed ${s.id} (${s.state.messages.length} messages)`));
358
- }
359
- /** 交给命令的会话管理器:换会话之后界面跟着换 */
360
- const manager = {
361
- get current() {
362
- return sessions.current;
363
- },
364
- async open(o) {
365
- // 插件在会话打开时发的提示(例如读了哪些指令文件)留到 adopt 清屏之后再显示
366
- bridge.hold();
367
- try {
368
- const s = await sessions.open(o);
369
- await adopt(s, o?.resume !== undefined);
370
- return s;
371
- }
372
- finally {
373
- bridge.release();
374
- }
375
- },
376
- async close() {
377
- unsubscribe?.();
378
- unsubscribe = undefined;
379
- current = undefined;
380
- bridge.show(undefined);
381
- await sessions.close();
382
- },
400
+ }
401
+ },
402
+ async close() {
403
+ unsubscribe?.();
404
+ unsubscribe = undefined;
405
+ current = undefined;
406
+ bridge.show(undefined);
407
+ await sessions.close();
408
+ }
409
+ };
410
+ const queue = [];
411
+ const steered = {
412
+ pending() {
413
+ try {
414
+ return current && steer ? steer.pending(current.id) : [];
415
+ } catch {
416
+ return [];
417
+ }
418
+ },
419
+ take() {
420
+ try {
421
+ return current && steer ? steer.take(current.id) : [];
422
+ } catch {
423
+ return [];
424
+ }
425
+ },
426
+ push(text) {
427
+ try {
428
+ return current !== undefined && steer !== undefined && steer.push(current.id, text);
429
+ } catch {
430
+ return false;
431
+ }
432
+ }
433
+ };
434
+ const showQueued = () => screen.queued([...steered.pending(), ...queue]);
435
+ let offSteer;
436
+ try {
437
+ offSteer = steer?.subscribe(showQueued);
438
+ } catch {}
439
+ let running = false;
440
+ let work;
441
+ let interruptedAt = 0;
442
+ let interruptPending = false;
443
+ const commandAborts = new Set;
444
+ let quitting = false;
445
+ async function occupy(fn) {
446
+ running = true;
447
+ work = fn();
448
+ try {
449
+ await work;
450
+ } finally {
451
+ running = false;
452
+ work = undefined;
453
+ interruptPending = false;
454
+ screen.busy(undefined);
455
+ }
456
+ }
457
+ async function guarded(fn) {
458
+ view.turnFailed = false;
459
+ view.lastError = undefined;
460
+ try {
461
+ await fn();
462
+ } catch (e) {
463
+ if (!view.turnFailed)
464
+ screen.log(red(`[error] ${errorText(e)}`));
465
+ } finally {
466
+ screen.endStream();
467
+ }
468
+ }
469
+ function interrupt() {
470
+ if (!running)
471
+ return;
472
+ const again = interruptPending || Date.now() - interruptedAt < SECOND_ESC_MS;
473
+ interruptedAt = Date.now();
474
+ interruptPending = true;
475
+ for (const ac of commandAborts)
476
+ ac.abort(new Error("interrupted by user"));
477
+ current?.abort(new Error("interrupted by user"));
478
+ screen.busy("Interrupting");
479
+ const n = queue.length + steered.pending().length;
480
+ if (n === 0)
481
+ return;
482
+ if (again) {
483
+ if (takeBack())
484
+ screen.log(dim(`[moved ${n} queued message${n > 1 ? "s" : ""} back to the input]`));
485
+ else {
486
+ steered.take();
487
+ queue.length = 0;
488
+ showQueued();
489
+ screen.log(dim(`[cleared ${n} queued message${n > 1 ? "s" : ""}]`));
490
+ }
491
+ } else {
492
+ screen.log(dim(`[${n} queued message${n > 1 ? "s" : ""} will still be sent; press esc again to edit ${n > 1 ? "them" : "it"}]`));
493
+ }
494
+ }
495
+ function takeBack() {
496
+ if (!screen.draft || queue.length + steered.pending().length === 0)
497
+ return false;
498
+ const typed = screen.draft.text();
499
+ screen.draft.set([...steered.take(), ...queue.splice(0), ...typed.trim() ? [typed] : []].join(`
500
+ `));
501
+ showQueued();
502
+ return true;
503
+ }
504
+ async function quit(code) {
505
+ if (quitting)
506
+ return;
507
+ quitting = true;
508
+ if (running)
509
+ current?.abort(new Error("exiting"));
510
+ for (const ac of commandAborts)
511
+ ac.abort(new Error("exiting"));
512
+ await Promise.race([work?.catch(() => {}), new Promise((r) => setTimeout(r, QUIT_WAIT_MS))]);
513
+ keyAbort.abort(new Error("exiting"));
514
+ offModel?.();
515
+ offSteer?.();
516
+ unsubscribe?.();
517
+ await screen.close();
518
+ bridge.detach();
519
+ if (current && current.state.messages.length > 0)
520
+ (io?.stdout ?? process.stdout).write(`${dim(`Resume with: jade --resume ${current.id}`)}
521
+ `);
522
+ finish(code);
523
+ }
524
+ opts.signal.addEventListener("abort", () => void quit(130), { once: true });
525
+ async function say(text) {
526
+ const s = current;
527
+ if (!s)
528
+ return screen.log(red("[error] there is no open session. Use /clear or /resume to continue."));
529
+ screen.busy(undefined);
530
+ screen.busy("Working");
531
+ const content = [{ kind: "text", text, origin: { by: "user" }, trust: "trusted" }];
532
+ await guarded(async () => {
533
+ await s.send({ kind: "message", content });
534
+ await s.idle();
535
+ });
536
+ }
537
+ const commandName = (text) => /^\/([^\s/]+)(?=\s|$)/.exec(text)?.[1].toLowerCase();
538
+ const instant = (name) => OWN.some((o) => o.name === name) || name === "quit" || commands.get(name)?.command.instant === true;
539
+ async function command(input) {
540
+ const name = input.slice(1).split(/\s+/)[0].toLowerCase();
541
+ const rest = input.slice(1).replace(/^\S+\s*/, "");
542
+ if (name === "exit" || name === "quit")
543
+ return false;
544
+ if (name === "help") {
545
+ const extras = [
546
+ ...commands.list().flatMap((c) => c.prefix ? [`${c.prefix}${c.args ?? ""} is /${c.name}`] : []),
547
+ ...completionList().map((c) => `${c.trigger} completes ${c.label}`)
548
+ ];
549
+ screen.log(dim(extras.length ? `${KEYS}
550
+ plugins ${extras.join(" · ")}` : KEYS));
551
+ const pluginKeys = keys.list();
552
+ if (pluginKeys.length > 0)
553
+ screen.log(dim(`Plugin keys: ${pluginKeys.map((k) => `${k.key}${k.description ? ` ${k.description}` : ""} (${k.plugin})`).join(" · ")}`));
554
+ const all = commandList();
555
+ const width = Math.max(...all.map((c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`.length)) + 2;
556
+ screen.log(all.map((c) => `${`/${c.name}${c.args ? ` ${c.args}` : ""}`.padEnd(width)}${dim(c.about)}`).join(`
557
+ `));
558
+ return true;
559
+ }
560
+ const found = commands.get(name);
561
+ if (!found) {
562
+ screen.log(red(`unknown command /${name}; /help lists the commands`));
563
+ return true;
564
+ }
565
+ const ac = new AbortController;
566
+ commandAborts.add(ac);
567
+ const showLive = (live) => {
568
+ const text = live === undefined ? undefined : ansi(live);
569
+ const lines = text?.replace(/\r\n?/g, `
570
+ `).trimEnd().split(`
571
+ `).slice(-LIVE_ROWS) ?? [];
572
+ for (let i = 0;i < LIVE_ROWS; i++)
573
+ screen.progress(`command:${i}`, text !== undefined && i < lines.length ? dim(` │ ${lines[i]}`) : undefined);
383
574
  };
384
- // ---------- 运行 ----------
385
- /** 等待执行的输入:运行中提交的消息和需要独占会话的命令排在这里,按顺序执行 */
386
- const queue = [];
387
- /**
388
- * 已经交给 jade/steer、还没交给模型的话:下一次请求模型时它们就到模型那里;这一轮先结束了的取回来,
389
- * 排到队列最前面当普通消息发。steer@1 出错时当作没有它
390
- */
391
- const steered = {
392
- pending() {
393
- try {
394
- return current && steer ? steer.pending(current.id) : [];
395
- }
396
- catch {
397
- return [];
398
- }
399
- },
400
- take() {
401
- try {
402
- return current && steer ? steer.take(current.id) : [];
403
- }
404
- catch {
405
- return [];
406
- }
407
- },
408
- push(text) {
409
- try {
410
- return current !== undefined && steer !== undefined && steer.push(current.id, text);
411
- }
412
- catch {
413
- return false;
414
- }
415
- },
575
+ const ctx = {
576
+ signal: ac.signal,
577
+ ui: bridge.ui,
578
+ sessions: manager,
579
+ print: (t, o) => screen.log(ansi(t), o?.details ? { details: ansi(o.details) } : undefined),
580
+ progress: showLive
416
581
  };
417
- /** 输入框上方显示的等待中的消息:中途说的话在前(它们先到模型那里) */
418
- const showQueued = () => screen.queued([...steered.pending(), ...queue]);
419
- let offSteer;
420
582
  try {
421
- offSteer = steer?.subscribe(showQueued);
422
- }
423
- catch {
424
- // 没有订阅上:交给模型之后显示的列表要等下一次变化才更新
425
- }
426
- let running = false;
427
- let work;
428
- let interruptedAt = 0;
429
- let interruptPending = false;
430
- const commandAborts = new Set();
431
- let quitting = false;
432
- async function occupy(fn) {
433
- running = true;
434
- work = fn();
435
- try {
436
- await work;
437
- }
438
- finally {
439
- running = false;
440
- work = undefined;
441
- interruptPending = false;
442
- screen.busy(undefined);
443
- }
444
- }
445
- /** guarded 里这一轮已经由 turn.ended 显示过原因的错误不再重复显示 */
446
- async function guarded(fn) {
447
- view.turnFailed = false;
448
- view.lastError = undefined;
449
- try {
450
- await fn();
451
- }
452
- catch (e) {
453
- if (!view.turnFailed)
454
- screen.log(red(`[error] ${errorText(e)}`));
455
- }
456
- finally {
457
- screen.endStream();
458
- }
459
- }
460
- function interrupt() {
461
- if (!running)
462
- return;
463
- const again = interruptPending || Date.now() - interruptedAt < SECOND_ESC_MS;
464
- interruptedAt = Date.now();
465
- interruptPending = true;
466
- for (const ac of commandAborts)
467
- ac.abort(new Error("interrupted by user"));
468
- current?.abort(new Error("interrupted by user"));
469
- screen.busy("Interrupting");
470
- const n = queue.length + steered.pending().length;
471
- if (n === 0)
472
- return;
473
- if (again) {
474
- if (takeBack())
475
- screen.log(dim(`[moved ${n} queued message${n > 1 ? "s" : ""} back to the input]`));
476
- else {
477
- steered.take();
478
- queue.length = 0;
479
- showQueued();
480
- screen.log(dim(`[cleared ${n} queued message${n > 1 ? "s" : ""}]`));
481
- }
482
- }
483
- else {
484
- screen.log(dim(`[${n} queued message${n > 1 ? "s" : ""} will still be sent; press esc again to edit ${n > 1 ? "them" : "it"}]`));
485
- }
486
- }
487
- /** 排队的消息不再自动发送,放回输入框(在已经输入的内容前面,一条一行);没有可放回的返回 false */
488
- function takeBack() {
489
- if (!screen.draft || queue.length + steered.pending().length === 0)
490
- return false;
491
- const typed = screen.draft.text();
492
- screen.draft.set([...steered.take(), ...queue.splice(0), ...(typed.trim() ? [typed] : [])].join("\n"));
583
+ const result = await found.command.run(rest, ctx);
584
+ if (isPrompt(result)) {
585
+ if (found.command.instant)
586
+ screen.log(yellow(`[warning] /${name} is instant and cannot send a prompt`));
587
+ else
588
+ await say(result.prompt);
589
+ } else if (result !== undefined && result !== null)
590
+ screen.log(ansi(result));
591
+ } catch (e) {
592
+ if (!ac.signal.aborted)
593
+ screen.log(red(`[error] /${name}: ${errorText(e)}`));
594
+ } finally {
595
+ showLive(undefined);
596
+ commandAborts.delete(ac);
597
+ }
598
+ return true;
599
+ }
600
+ function onSubmit(text) {
601
+ if (quitting)
602
+ return;
603
+ const short = [...text][0];
604
+ const byPrefix = short === undefined ? undefined : commands.byPrefix(short);
605
+ if (byPrefix && text.slice(short.length).trim())
606
+ text = `/${byPrefix.command.name} ${text.slice(short.length).trim()}`;
607
+ const name = commandName(text);
608
+ if (name !== undefined && instant(name)) {
609
+ view.echo(text);
610
+ command(text).then((go) => {
611
+ if (!go)
612
+ quit(0);
613
+ });
614
+ return;
615
+ }
616
+ if (running && name === undefined && queue.length === 0 && steered.push(text)) {
617
+ showQueued();
618
+ work?.catch(() => {}).then(() => pump());
619
+ return;
620
+ }
621
+ queue.push(text);
622
+ if (running)
623
+ showQueued();
624
+ pump();
625
+ }
626
+ async function pump() {
627
+ if (running)
628
+ return;
629
+ let exit = false;
630
+ await occupy(async () => {
631
+ for (;; ) {
632
+ queue.unshift(...steered.take());
633
+ if (queue.length === 0 || quitting)
634
+ break;
635
+ if (interruptPending)
636
+ interruptedAt = Date.now();
637
+ interruptPending = false;
638
+ const text = queue.shift();
493
639
  showQueued();
494
- return true;
495
- }
496
- async function quit(code) {
497
- if (quitting)
498
- return;
499
- quitting = true;
500
- if (running)
501
- current?.abort(new Error("exiting"));
502
- // 正在做的事停不下来时(例如命令杀不掉)不一直等:退出不能被它卡住
503
- for (const ac of commandAborts)
504
- ac.abort(new Error("exiting"));
505
- await Promise.race([work?.catch(() => { }), new Promise((r) => setTimeout(r, QUIT_WAIT_MS))]);
506
- keyAbort.abort(new Error("exiting"));
507
- offMode?.();
508
- offModel?.();
509
- offSteer?.();
510
- unsubscribe?.();
511
- await screen.close();
512
- bridge.detach();
513
- // 退出备用屏幕之后,里面的内容就看不到了:告诉用户怎么回来
514
- if (current && current.state.messages.length > 0)
515
- (io?.stdout ?? process.stdout).write(`${dim(`Resume with: jade --resume ${current.id}`)}\n`);
516
- finish(code);
517
- }
518
- opts.signal.addEventListener("abort", () => void quit(130), { once: true });
519
- /** 发一条用户消息,跑到会话空闲(包括插件排在这一轮之后的工作) */
520
- async function say(text) {
521
- const s = current;
522
- if (!s)
523
- return screen.log(red("[error] there is no open session. Use /clear or /resume to continue."));
524
- screen.busy(undefined);
525
- screen.busy("Working");
526
- const content = [{ kind: "text", text, origin: { by: "user" }, trust: "trusted" }];
527
- await guarded(async () => {
528
- await s.send({ kind: "message", content });
529
- await s.idle();
530
- });
531
- }
532
- /** 输入是命令时返回命令名。第一个词里还有 / 的是路径(/c/Users/…、/usr/bin/x),当普通消息发给模型 */
533
- const commandName = (text) => /^\/([^\s/]+)(?=\s|$)/.exec(text)?.[1].toLowerCase();
534
- const instant = (name) => OWN.some((o) => o.name === name) || name === "quit" || commands.get(name)?.command.instant === true;
535
- /** 执行一条命令;返回 false 表示退出 */
536
- async function command(input) {
537
- const name = input.slice(1).split(/\s+/)[0].toLowerCase();
538
- const rest = input.slice(1).replace(/^\S+\s*/, "");
539
- if (name === "exit" || name === "quit")
540
- return false;
541
- if (name === "help") {
542
- const all = commandList();
543
- const width = Math.max(...all.map((c) => `/${c.name}${c.args ? ` ${c.args}` : ""}`.length)) + 2;
544
- screen.log(all.map((c) => `${`/${c.name}${c.args ? ` ${c.args}` : ""}`.padEnd(width)}${dim(c.about)}`).join("\n"));
545
- screen.log(dim(KEYS));
546
- const pluginKeys = keys.list();
547
- if (pluginKeys.length > 0)
548
- screen.log(dim(`Plugin keys: ${pluginKeys.map((k) => `${k.key}${k.description ? ` ${k.description}` : ""} (${k.plugin})`).join(" · ")}`));
549
- return true;
550
- }
551
- if (name === "copy") {
552
- const reply = lastReply(current?.state.messages ?? []);
553
- const text = rest.trim() === "code" ? reply && lastCodeBlock(reply) : reply;
554
- if (!text)
555
- screen.log(dim(rest.trim() === "code" ? "The last reply has no code block." : "There is no reply to copy yet."));
556
- else if (!screen.copy)
557
- screen.log(red("[error] this terminal cannot copy"));
558
- else {
559
- screen.copy(text);
560
- screen.log(dim(`[copied ${[...text].length} characters]`));
561
- }
562
- return true;
563
- }
564
- const found = commands.get(name);
565
- if (!found) {
566
- screen.log(red(`unknown command /${name}; /help lists the commands`));
567
- return true;
568
- }
569
- const ac = new AbortController();
570
- commandAborts.add(ac);
571
- // 命令的临时显示:末尾几行,每行占进度区的一行
572
- const showLive = (text) => {
573
- const lines = text?.replace(/\r\n?/g, "\n").trimEnd().split("\n").slice(-LIVE_ROWS) ?? [];
574
- for (let i = 0; i < LIVE_ROWS; i++)
575
- screen.progress(`command:${i}`, text !== undefined && i < lines.length ? dim(` │ ${lines[i]}`) : undefined);
576
- };
577
- const ctx = {
578
- signal: ac.signal,
579
- ui: bridge.ui,
580
- sessions: manager,
581
- print: (t, o) => screen.log(t, o?.details ? { details: o.details } : undefined),
582
- progress: showLive,
583
- };
584
- try {
585
- const result = await found.command.run(rest, ctx);
586
- if (typeof result === "string")
587
- screen.log(result);
588
- else if (result && typeof result === "object" && typeof result.prompt === "string") {
589
- if (found.command.instant)
590
- screen.log(yellow(`[warning] /${name} is instant and cannot send a prompt`));
591
- else
592
- await say(result.prompt);
593
- }
594
- }
595
- catch (e) {
596
- if (!ac.signal.aborted)
597
- screen.log(red(`[error] /${name}: ${errorText(e)}`));
598
- }
599
- finally {
600
- showLive(undefined);
601
- commandAborts.delete(ac);
602
- }
603
- return true;
604
- }
605
- function onSubmit(text) {
606
- if (quitting)
607
- return;
608
- // !<命令> 是 /sh <命令> 的简写(jade/shell 提供):用户自己执行,不经过模型
609
- if (/^!\s*\S/.test(text))
610
- text = `/sh ${text.slice(1).trim()}`;
611
- const name = commandName(text);
612
- if (name !== undefined && instant(name)) {
613
- // 不碰会话的命令运行中也直接执行
614
- view.echo(text);
615
- void command(text).then((go) => {
616
- if (!go)
617
- void quit(0);
618
- });
619
- return;
620
- }
621
- // 模型正在工作、前面也没有别的在排队:这句话在下一次请求模型时就交给它(jade/steer),不等这一轮结束。
622
- // 命令、已经有东西在排队时照旧排队,先后顺序不变
623
- if (running && name === undefined && queue.length === 0 && steered.push(text)) {
624
- showQueued();
625
- // 没赶上这一轮的,等正在做的事做完再发(那时不一定是 pump 在跑,例如刚恢复会话)
626
- void work?.catch(() => { }).then(() => pump());
640
+ view.echo(text);
641
+ if (commandName(text) !== undefined) {
642
+ screen.busy("Running");
643
+ if (!await command(text)) {
644
+ exit = true;
627
645
  return;
628
- }
629
- queue.push(text);
630
- if (running)
631
- showQueued();
632
- void pump();
633
- }
634
- async function pump() {
635
- if (running)
636
- return;
637
- let exit = false;
638
- await occupy(async () => {
639
- for (;;) {
640
- // 中途说的话没赶上这一轮(模型没有再被请求就结束了):当普通消息发,排在后来排队的前面
641
- queue.unshift(...steered.take());
642
- if (queue.length === 0 || quitting)
643
- break;
644
- if (interruptPending)
645
- interruptedAt = Date.now();
646
- interruptPending = false;
647
- const text = queue.shift();
648
- showQueued();
649
- view.echo(text);
650
- if (commandName(text) !== undefined) {
651
- // 命令可能要跑一阵(/sh 跑测试):让用户看到它在跑
652
- screen.busy("Running");
653
- if (!(await command(text))) {
654
- exit = true;
655
- return;
656
- }
657
- }
658
- else
659
- await say(text);
660
- }
661
- });
662
- if (exit)
663
- await quit(0);
664
- }
665
- // ---------- 开始 ----------
666
- try {
667
- let opened = false;
668
- await occupy(async () => {
669
- try {
670
- await manager.open(resumed ? { resume: resumed } : {});
671
- opened = true;
672
- }
673
- catch (e) {
674
- screen.log(red(`[error] ${resumed ? `could not resume ${resumed}` : "could not start a session"}: ${errorText(e)}`));
675
- }
676
- });
677
- if (!opened && resumed) {
678
- // 恢复不了:新开一个,免得界面里没有会话
679
- screen.log(dim("Starting a new session instead."));
680
- await occupy(async () => {
681
- await manager.open().catch((e) => screen.log(red(`[error] could not start a session: ${errorText(e)}`)));
682
- });
683
- }
684
- }
685
- catch (e) {
686
- screen.log(red(`[error] ${errorText(e)}`));
687
- }
688
- if (!models?.current()) {
689
- // /model(jade/models 提供)当场就能配好,不用重启;没有这条命令时只能改文件
690
- const file = `put ANTHROPIC_API_KEY=... (or OPENAI_API_KEY=...) in ${path.join(home, ".env")}, then restart jade`;
691
- 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}.`));
692
- }
693
- else if (!resumed)
694
- screen.log(dim("Type / for commands, esc to interrupt."));
695
- ready = true;
696
- for (const text of [...(args.prompt ? [args.prompt] : []), ...early.splice(0)])
697
- onSubmit(text);
698
- return finished;
699
- }
700
- /** 当前分支;不在仓库里或没有 git 时 undefined */
701
- /** 最近一条有正文的助手消息的正文(模型写的原文,没有折行和排版) */
702
- export function lastReply(messages) {
703
- for (let i = messages.length - 1; i >= 0; i--) {
704
- const m = messages[i];
705
- if (m.role !== "assistant")
706
- continue;
707
- const text = m.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim();
708
- if (text)
709
- return text;
710
- }
711
- return undefined;
712
- }
713
- /** Markdown 里最后一个围栏代码块的内容 */
714
- export function lastCodeBlock(markdown) {
715
- const blocks = [...markdown.matchAll(/^ {0,3}(`{3,}|~{3,})[^\n]*\n([\s\S]*?)^ {0,3}\1[`~]*[ \t]*$/gm)];
716
- return blocks.at(-1)?.[2]?.replace(/\n$/, "");
646
+ }
647
+ } else
648
+ await say(text);
649
+ }
650
+ });
651
+ if (exit)
652
+ await quit(0);
653
+ }
654
+ try {
655
+ let opened = false;
656
+ await occupy(async () => {
657
+ try {
658
+ await manager.open(resumed ? { resume: resumed } : {});
659
+ opened = true;
660
+ } catch (e) {
661
+ screen.log(red(`[error] ${resumed ? `could not resume ${resumed}` : "could not start a session"}: ${errorText(e)}`));
662
+ }
663
+ });
664
+ if (!opened && resumed) {
665
+ screen.log(dim("Starting a new session instead."));
666
+ await occupy(async () => {
667
+ await manager.open().catch((e) => screen.log(red(`[error] could not start a session: ${errorText(e)}`)));
668
+ });
669
+ }
670
+ } catch (e) {
671
+ screen.log(red(`[error] ${errorText(e)}`));
672
+ }
673
+ if (models?.current() && !resumed)
674
+ screen.log(dim("Type / for commands, esc to interrupt."));
675
+ ready = true;
676
+ for (const text of [...args.prompt ? [args.prompt] : [], ...early.splice(0)])
677
+ onSubmit(text);
678
+ return finished;
717
679
  }
718
680
  function gitBranch(cwd) {
719
- return new Promise((resolve) => {
720
- execFile("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd, timeout: 2000, windowsHide: true }, (err, stdout) => resolve(err ? undefined : stdout.trim() || undefined));
721
- });
681
+ return new Promise((resolve) => {
682
+ execFile("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd, timeout: 2000, windowsHide: true }, (err, stdout) => resolve(err ? undefined : stdout.trim() || undefined));
683
+ });
722
684
  }
723
- /** 家目录下的路径写成 ~/… */
724
685
  function shortPath(p) {
725
- const home = os.homedir();
726
- const rel = path.relative(home, p);
727
- return rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? `~${path.sep}${rel}` : p === home ? "~" : p;
686
+ const home = os.homedir();
687
+ const rel = path.relative(home, p);
688
+ return rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? `~${path.sep}${rel}` : p === home ? "~" : p;
728
689
  }