@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,345 +1,342 @@
1
- // bash 工具:在工作目录里执行一条 shell 命令。输出边读边通过 ctx.progress 推给宿主。
2
- //
3
- // run_in_background 的命令立即返回一个编号,进程留在后台(开发服务器、watch 等);
4
- // 用 bash_output 读取它的新输出,kill_shell 停止它。后台进程只属于本进程,宿主退出时调用 shutdown 全部杀掉。
5
1
  import { existsSync } from "node:fs";
6
2
  import path from "node:path";
7
3
  import { runSync, spawn as spawnProc, which } from "./sys.js";
8
- const DEFAULT_TIMEOUT_MS = 120_000;
9
- const MAX_TIMEOUT_MS = 600_000;
10
- const MAX_OUTPUT_CHARS = 30_000;
11
- /** 后台进程最多缓存这么多还没读取的输出,超出的丢弃最早的部分 */
12
- const MAX_BUFFER_CHARS = 1_000_000;
13
- /** 只要 bash 工具时用(测试) */
4
+ const DEFAULT_TIMEOUT_MS = 120000;
5
+ const MAX_TIMEOUT_MS = 600000;
6
+ const MAX_OUTPUT_CHARS = 30000;
7
+ const MAX_BUFFER_CHARS = 1e6;
14
8
  export function shellTool(opts) {
15
- const { tools, unavailable } = shellTools(opts);
16
- if (!tools[0])
17
- throw new Error(unavailable);
18
- return tools[0];
9
+ const { tools, unavailable } = shellTools(opts);
10
+ if (!tools[0])
11
+ throw new Error(unavailable);
12
+ return tools[0];
19
13
  }
20
14
  export function shellTools(opts) {
21
- const shell = opts.shell ?? process.env.JADE_SHELL ?? "bash";
22
- const found = findShell(shell);
23
- // 找不到 shell 时不提供这几个工具:否则模型每次调用都要用户先批准,执行时才失败,模型还会反复重试
24
- if (!found) {
25
- const hint = process.platform === "win32" ? "install Git for Windows, or set JADE_SHELL to the path of a bash executable" : "set JADE_SHELL to the path of a shell";
26
- return { tools: [], unavailable: `${shell} was not found, so the bash tool is disabled; ${hint}`, shutdown() { }, list: () => [], kill: async () => false };
27
- }
28
- const executable = found;
29
- const env = shellEnv(executable);
30
- const background = new Map();
31
- let nextId = 1;
32
- const spawn = (command, cwd = opts.cwd) => spawnProc([executable, "-c", command], {
33
- cwd,
34
- env,
35
- // 自成进程组,超时/中断时能连同子进程一起杀掉
36
- detached: process.platform !== "win32",
15
+ const shell = opts.shell ?? process.env.JADE_SHELL ?? "bash";
16
+ const found = findShell(shell);
17
+ if (!found) {
18
+ const hint = process.platform === "win32" ? "install Git for Windows, or set JADE_SHELL to the path of a bash executable" : "set JADE_SHELL to the path of a shell";
19
+ return { tools: [], unavailable: `${shell} was not found, so the bash tool is disabled; ${hint}`, shutdown() {}, list: () => [], kill: async () => false };
20
+ }
21
+ const executable = found;
22
+ const env = shellEnv(executable);
23
+ const background = new Map;
24
+ let nextId = 1;
25
+ const spawn = (command, cwd = opts.cwd) => launch(executable, env, command, cwd);
26
+ async function startBackground(command) {
27
+ const id = `bg${nextId++}`;
28
+ const bg = { id, command, proc: await spawn(command), unread: "", dropped: 0 };
29
+ const append = (text) => {
30
+ bg.unread += text;
31
+ if (bg.unread.length > MAX_BUFFER_CHARS) {
32
+ bg.dropped += bg.unread.length - MAX_BUFFER_CHARS;
33
+ bg.unread = bg.unread.slice(-MAX_BUFFER_CHARS);
34
+ }
35
+ };
36
+ Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => {});
37
+ bg.proc.exited.then((code) => {
38
+ bg.exitCode = code;
39
+ if (!bg.killed)
40
+ opts.onExit?.({ id, command, exitCode: code });
37
41
  });
38
- async function startBackground(command) {
39
- const id = `bg${nextId++}`;
40
- const bg = { id, command, proc: await spawn(command), unread: "", dropped: 0 };
41
- const append = (text) => {
42
- bg.unread += text;
43
- if (bg.unread.length > MAX_BUFFER_CHARS) {
44
- bg.dropped += bg.unread.length - MAX_BUFFER_CHARS;
45
- bg.unread = bg.unread.slice(-MAX_BUFFER_CHARS);
46
- }
47
- };
48
- // 输出只进 unread,不另外累积:后台进程可能一直运行
49
- void Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => { });
50
- void bg.proc.exited.then((code) => {
51
- bg.exitCode = code;
52
- if (!bg.killed)
53
- opts.onExit?.({ id, command, exitCode: code });
54
- });
55
- background.set(id, bg);
56
- return id;
42
+ background.set(id, bg);
43
+ return id;
44
+ }
45
+ const status = (bg) => bg.exitCode === undefined ? "running" : `exited with code ${bg.exitCode}`;
46
+ const stop = async (bg) => {
47
+ if (bg.exitCode !== undefined)
48
+ return;
49
+ bg.killed = true;
50
+ killTree(executable, env, bg.proc);
51
+ await bg.proc.exited;
52
+ };
53
+ const bash = {
54
+ name: "bash",
55
+ meta: { shell: "command" },
56
+ description: `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` + `Each call starts a fresh shell: cd and environment variables do not persist. ` + `Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` + "Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " + "then read new output with bash_output and stop it with kill_shell. " + "Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
57
+ inputSchema: {
58
+ type: "object",
59
+ properties: { command: { type: "string" }, timeout_ms: { type: "integer" }, run_in_background: { type: "boolean" } },
60
+ required: ["command"],
61
+ additionalProperties: false
62
+ },
63
+ effect: "external",
64
+ concurrency: "exclusive",
65
+ idempotent: false,
66
+ async execute(input, { signal, progress }) {
67
+ const { command, timeout_ms, run_in_background } = input;
68
+ if (run_in_background) {
69
+ const id = await startBackground(command);
70
+ return { content: `Started background shell ${id}. Read its output with bash_output, stop it with kill_shell.` };
71
+ }
72
+ const timeout = Math.min(Math.max(timeout_ms ?? DEFAULT_TIMEOUT_MS, 1000), MAX_TIMEOUT_MS);
73
+ const proc = await spawn(command);
74
+ let timedOut = false;
75
+ const killed = giveUp();
76
+ const timer = setTimeout(() => {
77
+ timedOut = true;
78
+ killTree(executable, env, proc);
79
+ killed.start();
80
+ }, timeout);
81
+ const kill = () => {
82
+ killTree(executable, env, proc);
83
+ killed.start();
84
+ };
85
+ signal.addEventListener("abort", kill, { once: true });
86
+ try {
87
+ const [stdout, stderr, code] = await Promise.all([
88
+ collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text }), true, killed.done),
89
+ collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text }), true, killed.done),
90
+ Promise.race([proc.exited, killed.done.then(() => null)])
91
+ ]);
92
+ signal.throwIfAborted();
93
+ const parts = [
94
+ timedOut ? `Timed out after ${timeout}ms (killed). If it needs longer, raise timeout_ms (max ${MAX_TIMEOUT_MS / 1000}s); for servers and watchers use run_in_background.` : `Exit code ${code}`
95
+ ];
96
+ if (stdout)
97
+ parts.push(`<stdout>
98
+ ${stdout}
99
+ </stdout>`);
100
+ if (stderr)
101
+ parts.push(`<stderr>
102
+ ${stderr}
103
+ </stderr>`);
104
+ return { content: parts.join(`
105
+ `), isError: timedOut || code !== 0 };
106
+ } finally {
107
+ clearTimeout(timer);
108
+ signal.removeEventListener("abort", kill);
109
+ }
110
+ }
111
+ };
112
+ const idSchema = {
113
+ type: "object",
114
+ properties: { id: { type: "string", description: "id returned by bash with run_in_background" } },
115
+ required: ["id"],
116
+ additionalProperties: false
117
+ };
118
+ const find = (id) => background.get(id);
119
+ const unknown = (id) => ({
120
+ content: `No background shell ${id}${background.size ? `; known: ${[...background.keys()].join(", ")}` : ""}`,
121
+ isError: true
122
+ });
123
+ const bashOutput = {
124
+ name: "bash_output",
125
+ description: "Return the output a background shell (started with bash run_in_background) has produced since the last bash_output call, " + "and whether it is still running. stdout and stderr are interleaved.",
126
+ inputSchema: idSchema,
127
+ effect: "read",
128
+ concurrency: "safe",
129
+ idempotent: false,
130
+ async execute(input) {
131
+ const { id } = input;
132
+ const bg = find(id);
133
+ if (!bg)
134
+ return unknown(id);
135
+ const { unread, dropped } = bg;
136
+ bg.unread = "";
137
+ bg.dropped = 0;
138
+ const title = bg.command.split(`
139
+ `)[0];
140
+ const head = `${id} (${title.length > 100 ? title.slice(0, 100) + "…" : title}): ${status(bg)}`;
141
+ const note = dropped > 0 ? `
142
+ (${dropped} earlier characters were dropped)` : "";
143
+ return { content: unread ? `${head}${note}
144
+ <output>
145
+ ${clip(unread)}
146
+ </output>` : `${head}${note}
147
+ (no new output)` };
57
148
  }
58
- const status = (bg) => (bg.exitCode === undefined ? "running" : `exited with code ${bg.exitCode}`);
59
- /** 停掉一个还在运行的后台命令,等它退出 */
60
- const stop = async (bg) => {
149
+ };
150
+ const killShell = {
151
+ name: "kill_shell",
152
+ description: "Stop a background shell started with bash run_in_background, together with the processes it started.",
153
+ inputSchema: idSchema,
154
+ effect: "read",
155
+ concurrency: "exclusive",
156
+ idempotent: true,
157
+ async execute(input) {
158
+ const { id } = input;
159
+ const bg = find(id);
160
+ if (!bg)
161
+ return unknown(id);
162
+ await stop(bg);
163
+ return { content: `${id} stopped (${status(bg)})` };
164
+ }
165
+ };
166
+ const run = (command, opts) => capture(executable, env, command, opts);
167
+ return {
168
+ tools: [bash, bashOutput, killShell],
169
+ executable,
170
+ run,
171
+ shutdown() {
172
+ for (const bg of background.values()) {
61
173
  if (bg.exitCode !== undefined)
62
- return;
174
+ continue;
63
175
  bg.killed = true;
64
- killTree(executable, env, bg.proc.pid);
65
- await bg.proc.exited;
66
- };
67
- const bash = {
68
- name: "bash",
69
- description: `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` +
70
- `Each call starts a fresh shell: cd and environment variables do not persist. ` +
71
- `Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` +
72
- "Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " +
73
- "then read new output with bash_output and stop it with kill_shell. " +
74
- "Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
75
- inputSchema: {
76
- type: "object",
77
- properties: { command: { type: "string" }, timeout_ms: { type: "integer" }, run_in_background: { type: "boolean" } },
78
- required: ["command"],
79
- additionalProperties: false,
80
- },
81
- effect: "external",
82
- concurrency: "exclusive",
83
- idempotent: false,
84
- async execute(input, { signal, progress }) {
85
- const { command, timeout_ms, run_in_background } = input;
86
- if (run_in_background) {
87
- const id = await startBackground(command);
88
- return { content: `Started background shell ${id}. Read its output with bash_output, stop it with kill_shell.` };
89
- }
90
- const timeout = Math.min(Math.max(timeout_ms ?? DEFAULT_TIMEOUT_MS, 1000), MAX_TIMEOUT_MS);
91
- const proc = await spawn(command);
92
- let timedOut = false;
93
- const timer = setTimeout(() => {
94
- timedOut = true;
95
- killTree(executable, env, proc.pid);
96
- }, timeout);
97
- const kill = () => killTree(executable, env, proc.pid);
98
- signal.addEventListener("abort", kill, { once: true });
99
- try {
100
- const [stdout, stderr, code] = await Promise.all([
101
- collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text })),
102
- collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text })),
103
- proc.exited,
104
- ]);
105
- signal.throwIfAborted();
106
- const parts = [
107
- timedOut
108
- ? `Timed out after ${timeout}ms (killed). If it needs longer, raise timeout_ms (max ${MAX_TIMEOUT_MS / 1000}s); for servers and watchers use run_in_background.`
109
- : `Exit code ${code}`,
110
- ];
111
- if (stdout)
112
- parts.push(`<stdout>\n${stdout}\n</stdout>`);
113
- if (stderr)
114
- parts.push(`<stderr>\n${stderr}\n</stderr>`);
115
- return { content: parts.join("\n"), isError: timedOut || code !== 0 };
116
- }
117
- finally {
118
- clearTimeout(timer);
119
- signal.removeEventListener("abort", kill);
120
- }
121
- },
122
- };
123
- const idSchema = {
124
- type: "object",
125
- properties: { id: { type: "string", description: "id returned by bash with run_in_background" } },
126
- required: ["id"],
127
- additionalProperties: false,
128
- };
129
- const find = (id) => background.get(id);
130
- const unknown = (id) => ({
131
- content: `No background shell ${id}${background.size ? `; known: ${[...background.keys()].join(", ")}` : ""}`,
132
- isError: true,
133
- });
134
- const bashOutput = {
135
- name: "bash_output",
136
- description: "Return the output a background shell (started with bash run_in_background) has produced since the last bash_output call, " +
137
- "and whether it is still running. stdout and stderr are interleaved.",
138
- inputSchema: idSchema,
139
- effect: "read",
140
- concurrency: "safe",
141
- // 读走的输出不会再出现
142
- idempotent: false,
143
- async execute(input) {
144
- const { id } = input;
145
- const bg = find(id);
146
- if (!bg)
147
- return unknown(id);
148
- const { unread, dropped } = bg;
149
- bg.unread = "";
150
- bg.dropped = 0;
151
- const title = bg.command.split("\n")[0];
152
- const head = `${id} (${title.length > 100 ? title.slice(0, 100) + "…" : title}): ${status(bg)}`;
153
- const note = dropped > 0 ? `\n(${dropped} earlier characters were dropped)` : "";
154
- return { content: unread ? `${head}${note}\n<output>\n${clip(unread)}\n</output>` : `${head}${note}\n(no new output)` };
155
- },
156
- };
157
- const killShell = {
158
- name: "kill_shell",
159
- description: "Stop a background shell started with bash run_in_background, together with the processes it started.",
160
- inputSchema: idSchema,
161
- // 只能停掉本会话自己启动、已经批准过的进程
162
- effect: "read",
163
- concurrency: "exclusive",
164
- idempotent: true,
165
- async execute(input) {
166
- const { id } = input;
167
- const bg = find(id);
168
- if (!bg)
169
- return unknown(id);
170
- await stop(bg);
171
- return { content: `${id} stopped (${status(bg)})` };
172
- },
173
- };
174
- const run = (command, opts) => capture(executable, env, command, opts);
175
- return {
176
- tools: [bash, bashOutput, killShell],
177
- executable,
178
- run,
179
- shutdown() {
180
- for (const bg of background.values()) {
181
- if (bg.exitCode !== undefined)
182
- continue;
183
- bg.killed = true;
184
- killTree(executable, env, bg.proc.pid);
185
- }
186
- },
187
- list: () => [...background.values()].map((bg) => ({ id: bg.id, command: bg.command, status: status(bg) })),
188
- async kill(id) {
189
- const bg = background.get(id);
190
- if (!bg)
191
- return false;
192
- await stop(bg);
193
- return true;
194
- },
195
- };
176
+ killTree(executable, env, bg.proc);
177
+ }
178
+ },
179
+ list: () => [...background.values()].map((bg) => ({ id: bg.id, command: bg.command, status: status(bg) })),
180
+ async kill(id) {
181
+ const bg = background.get(id);
182
+ if (!bg)
183
+ return false;
184
+ await stop(bg);
185
+ return true;
186
+ }
187
+ };
196
188
  }
197
- /**
198
- * 执行一条命令并把输出收下来(不经过模型、不推进度);超时或中止时连同子进程一起杀掉。
199
- * 后台命令和别的插件(`shell@1`,例如 jade/checks)都用它
200
- */
201
189
  export async function capture(executable, env, command, opts) {
202
- opts.signal?.throwIfAborted();
203
- const proc = await spawnProc([executable, "-c", command], {
204
- cwd: opts.cwd,
205
- env,
206
- // 自成进程组,超时/中断时能连同子进程一起杀掉
207
- detached: process.platform !== "win32",
208
- });
209
- let timedOut = false;
210
- const kill = () => killTree(executable, env, proc.pid);
211
- const timer = setTimeout(() => {
212
- timedOut = true;
213
- kill();
214
- }, opts.timeoutMs);
215
- opts.signal?.addEventListener("abort", kill, { once: true });
190
+ opts.signal?.throwIfAborted();
191
+ const proc = await launch(executable, env, command, opts.cwd);
192
+ const onOutput = (text) => {
216
193
  try {
217
- const [stdout, stderr, code] = await Promise.all([collect(proc.stdout, () => { }), collect(proc.stderr, () => { }), proc.exited]);
218
- opts.signal?.throwIfAborted();
219
- return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join("\n"), timedOut };
220
- }
221
- finally {
222
- clearTimeout(timer);
223
- opts.signal?.removeEventListener("abort", kill);
224
- }
194
+ opts.onOutput?.(text);
195
+ } catch {}
196
+ };
197
+ let timedOut = false;
198
+ const killed = giveUp();
199
+ const kill = () => {
200
+ killTree(executable, env, proc);
201
+ killed.start();
202
+ };
203
+ const timer = setTimeout(() => {
204
+ timedOut = true;
205
+ kill();
206
+ }, opts.timeoutMs);
207
+ opts.signal?.addEventListener("abort", kill, { once: true });
208
+ try {
209
+ const [stdout, stderr, code] = await Promise.all([
210
+ collect(proc.stdout, onOutput, true, killed.done),
211
+ collect(proc.stderr, onOutput, true, killed.done),
212
+ Promise.race([proc.exited, killed.done.then(() => null)])
213
+ ]);
214
+ opts.signal?.throwIfAborted();
215
+ return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join(`
216
+ `), timedOut };
217
+ } finally {
218
+ clearTimeout(timer);
219
+ opts.signal?.removeEventListener("abort", kill);
220
+ }
225
221
  }
226
- /**
227
- * 找到要执行的 shell 程序,找不到返回 undefined。
228
- *
229
- * Windows 上 Git for Windows 安装时默认只把 Git\cmd 加进 PATH,PATH 里通常找不到 bash,
230
- * 所以 bash、sh 还要从 git.exe 的位置和常见安装目录找 Git 的安装目录。
231
- * Git 的 bin\bash.exe、bin\sh.exe 只是启动器,真正的 shell 是它启动的 usr\bin 下的同名程序;
232
- * killTree 按 WINPID 找 msys 进程,用启动器的 pid 找不到,所以直接用 usr\bin 下的。
233
- * Git Bash 优先于 PATH 里别的 bash(例如 System32\bash.exe 是 WSL 的启动器,看不到 Windows 路径)
234
- */
235
222
  export function findShell(shell) {
236
- const found = which(shell);
237
- if (process.platform !== "win32")
238
- return found;
239
- const name = /^(bash|sh)(\.exe)?$/i.exec(shell)?.[1]?.toLowerCase();
240
- if (!name)
241
- return found;
242
- const inGit = (root) => {
243
- const real = path.join(root, "usr", "bin", `${name}.exe`);
244
- return existsSync(real) ? real : undefined;
245
- };
246
- const m = /^(.*\\Git)\\(usr\\)?bin\\(bash|sh)\.exe$/i.exec(found ?? "");
247
- if (m)
248
- return inGit(m[1]) ?? found;
249
- // git.exe 在 Git\cmd、Git\bin 或 Git\mingw64\bin 下
250
- const git = which("git");
251
- const roots = git ? [path.dirname(path.dirname(git)), path.dirname(path.dirname(path.dirname(git)))] : [];
252
- for (const base of [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, "Programs")]) {
253
- if (base)
254
- roots.push(path.join(base, "Git"));
255
- }
256
- for (const root of roots) {
257
- const real = inGit(root);
258
- if (real)
259
- return real;
260
- }
223
+ const found = which(shell);
224
+ if (process.platform !== "win32")
225
+ return found;
226
+ const name = /^(bash|sh)(\.exe)?$/i.exec(shell)?.[1]?.toLowerCase();
227
+ if (!name)
261
228
  return found;
229
+ const inGit = (root) => {
230
+ const real = path.join(root, "usr", "bin", `${name}.exe`);
231
+ return existsSync(real) ? real : undefined;
232
+ };
233
+ const m = /^(.*\\Git)\\(usr\\)?bin\\(bash|sh)\.exe$/i.exec(found ?? "");
234
+ if (m)
235
+ return inGit(m[1]) ?? found;
236
+ const git = which("git");
237
+ const roots = git ? [path.dirname(path.dirname(git)), path.dirname(path.dirname(path.dirname(git)))] : [];
238
+ for (const base of [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, "Programs")]) {
239
+ if (base)
240
+ roots.push(path.join(base, "Git"));
241
+ }
242
+ for (const root of roots) {
243
+ const real = inGit(root);
244
+ if (real)
245
+ return real;
246
+ }
247
+ return found;
262
248
  }
263
- /**
264
- * 直接执行 Git 的 usr\bin\bash.exe 时没有经过 bin\bash.exe 启动器,启动器会把 /usr/bin、/mingw64/bin 加进 PATH;
265
- * 不补上的话 PATH 里只有 Windows 的目录,cat、grep、head、sed 都找不到,find 还会变成 Windows 的 find.exe。
266
- * 不是 Git Bash 时返回 undefined,继承当前环境
267
- */
268
249
  export function shellEnv(executable, env = process.env) {
269
- if (process.platform !== "win32")
270
- return undefined;
271
- const m = /^(.*\\Git)\\usr\\bin\\(bash|sh)\.exe$/i.exec(executable);
272
- if (!m)
273
- return undefined;
274
- const root = m[1];
275
- // Windows 的环境变量名不分大小写,展开成普通对象后要沿用原来的键名(通常是 Path),否则会同时出现 Path 和 PATH
276
- const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
277
- const dirs = [path.join(root, "usr", "bin"), path.join(root, "mingw64", "bin")];
278
- return { ...env, [key]: [...dirs, env[key]].filter(Boolean).join(path.delimiter) };
250
+ if (process.platform !== "win32")
251
+ return;
252
+ const m = /^(.*\\Git)\\usr\\bin\\(bash|sh)\.exe$/i.exec(executable);
253
+ if (!m)
254
+ return;
255
+ const root = m[1];
256
+ const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
257
+ const dirs = [path.join(root, "usr", "bin"), path.join(root, "mingw64", "bin")];
258
+ return { ...env, [key]: [...dirs, env[key]].filter(Boolean).join(path.delimiter) };
259
+ }
260
+ const TAG = "JADE_SHELL_TAG";
261
+ let launched = 0;
262
+ async function launch(executable, env, command, cwd) {
263
+ const tag = `${process.pid}-${Date.now().toString(36)}-${++launched}`;
264
+ const proc = await spawnProc([executable, "-c", command], {
265
+ cwd,
266
+ env: process.platform === "win32" ? { ...env ?? process.env, [TAG]: tag } : env,
267
+ detached: process.platform !== "win32"
268
+ });
269
+ return Object.assign(proc, { tag });
279
270
  }
280
- /**
281
- * 只杀 shell 本身不够:它启动的子进程还占着 stdout/stderr 管道,读取会一直等到它们退出。
282
- * POSIX 上杀整个进程组。Windows 上 Git Bash(msys)模拟 fork,Windows 进程树里看不到父子关系,
283
- * 要先在 msys 里按 WINPID 找到 shell 的 msys PID(它也是进程组号)杀掉整组;taskkill /T 兜底非 msys 的 shell
284
- */
285
- function killTree(shell, env, pid) {
271
+ function killTree(shell, env, proc) {
272
+ try {
273
+ if (process.platform !== "win32")
274
+ return process.kill(-proc.pid, "SIGKILL");
275
+ const script = `for d in /proc/[0-9]*; do ` + `if grep -qa "${TAG}=${proc.tag}" "$d/environ" 2>/dev/null || [ "$(cat "$d/winpid" 2>/dev/null)" = "${proc.pid}" ]; then ` + `kill -9 -- "-$(cat "$d/pgid")" "\${d#/proc/}" 2>/dev/null; fi; done`;
276
+ runSync(["taskkill", "/T", "/F", "/PID", String(proc.pid)]);
286
277
  try {
287
- if (process.platform !== "win32")
288
- return process.kill(-pid, "SIGKILL");
289
- const script = `for d in /proc/[0-9]*; do [ "$(cat "$d/winpid" 2>/dev/null)" = "${pid}" ] && kill -9 -- "-\${d#/proc/}"; done`;
290
- try {
291
- runSync([shell, "-c", script], { env });
292
- }
293
- catch {
294
- // 不是 msys/cygwin 的 shell
295
- }
296
- runSync(["taskkill", "/T", "/F", "/PID", String(pid)]);
297
- }
298
- catch {
299
- // 已经退出
300
- }
278
+ runSync([shell, "-c", script], { env });
279
+ } catch {}
280
+ } catch {}
301
281
  }
302
- /**
303
- * 返回截好的输出:超过 MAX_OUTPUT_CHARS 时保留开头和结尾各一半,中间截掉。
304
- * 边读边截,输出再多也只占几倍 MAX_OUTPUT_CHARS 的内存。keep 为 false 时只推给 onChunk,不累积,返回空串
305
- */
306
- async function collect(stream, onChunk, keep = true) {
307
- const half = MAX_OUTPUT_CHARS / 2;
308
- const decoder = new TextDecoder();
309
- let head = "";
310
- let tail = "";
311
- let total = 0;
312
- const add = (text) => {
313
- onChunk(text);
314
- if (!keep)
315
- return;
316
- total += text.length;
317
- if (head.length < half) {
318
- const n = half - head.length;
319
- head += text.slice(0, n);
320
- text = text.slice(n);
321
- }
322
- tail += text;
323
- // 攒到两倍再截,不用每块都复制
324
- if (tail.length > 2 * half)
325
- tail = tail.slice(-half);
326
- };
327
- for await (const chunk of stream) {
328
- const text = decoder.decode(chunk, { stream: true });
329
- if (text)
330
- add(text);
282
+ const KILL_GRACE_MS = 2000;
283
+ function giveUp() {
284
+ let start = () => {};
285
+ const done = new Promise((resolve) => {
286
+ start = () => void setTimeout(resolve, KILL_GRACE_MS);
287
+ });
288
+ return { start, done };
289
+ }
290
+ async function collect(stream, onChunk, keep = true, stop) {
291
+ const half = MAX_OUTPUT_CHARS / 2;
292
+ const decoder = new TextDecoder;
293
+ let head = "";
294
+ let tail = "";
295
+ let total = 0;
296
+ const add = (text) => {
297
+ onChunk(text);
298
+ if (!keep)
299
+ return;
300
+ total += text.length;
301
+ if (head.length < half) {
302
+ const n = half - head.length;
303
+ head += text.slice(0, n);
304
+ text = text.slice(n);
305
+ }
306
+ tail += text;
307
+ if (tail.length > 2 * half)
308
+ tail = tail.slice(-half);
309
+ };
310
+ const it = stream[Symbol.asyncIterator]();
311
+ const stopped = stop?.then(() => {
312
+ return;
313
+ });
314
+ for (;; ) {
315
+ const r = await (stopped ? Promise.race([it.next(), stopped]) : it.next());
316
+ if (!r) {
317
+ Promise.resolve(it.return?.()).catch(() => {});
318
+ break;
331
319
  }
332
- const rest = decoder.decode();
333
- if (rest)
334
- add(rest);
335
- if (total <= MAX_OUTPUT_CHARS)
336
- return (head + tail).trimEnd();
337
- return `${head}\n… (${total - MAX_OUTPUT_CHARS} characters omitted) …\n${tail.slice(-half)}`.trimEnd();
320
+ if (r.done)
321
+ break;
322
+ const text = decoder.decode(r.value, { stream: true });
323
+ if (text)
324
+ add(text);
325
+ }
326
+ const rest = decoder.decode();
327
+ if (rest)
328
+ add(rest);
329
+ if (total <= MAX_OUTPUT_CHARS)
330
+ return (head + tail).trimEnd();
331
+ return `${head}
332
+ … (${total - MAX_OUTPUT_CHARS} characters omitted) …
333
+ ${tail.slice(-half)}`.trimEnd();
338
334
  }
339
- /** 保留开头和结尾,中间截掉 */
340
335
  function clip(s) {
341
- if (s.length <= MAX_OUTPUT_CHARS)
342
- return s.trimEnd();
343
- const half = MAX_OUTPUT_CHARS / 2;
344
- return `${s.slice(0, half)}\n… (${s.length - MAX_OUTPUT_CHARS} characters omitted) …\n${s.slice(-half)}`.trimEnd();
336
+ if (s.length <= MAX_OUTPUT_CHARS)
337
+ return s.trimEnd();
338
+ const half = MAX_OUTPUT_CHARS / 2;
339
+ return `${s.slice(0, half)}
340
+ … (${s.length - MAX_OUTPUT_CHARS} characters omitted) …
341
+ ${s.slice(-half)}`.trimEnd();
345
342
  }