@uncarved/jade 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +490 -29
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +36 -14
  14. package/plugins/approval/policy.ts +15 -10
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +42 -9
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +47 -12
  50. package/plugins/models/index.ts +27 -1
  51. package/plugins/models/provider.ts +24 -0
  52. package/plugins/models/saved.ts +1 -1
  53. package/plugins/modes/index.ts +13 -2
  54. package/plugins/print/index.ts +7 -4
  55. package/plugins/prompts/index.ts +0 -0
  56. package/plugins/renderers/index.ts +10 -5
  57. package/plugins/repeats/index.ts +8 -8
  58. package/plugins/schedule/index.ts +5 -1
  59. package/plugins/screenshot/browser.ts +10 -0
  60. package/plugins/sessions/index.ts +48 -2
  61. package/plugins/shell/index.ts +27 -28
  62. package/plugins/shell/plugin.json +1 -1
  63. package/plugins/shell/renderers.ts +9 -7
  64. package/plugins/shell/shell.ts +3 -1
  65. package/plugins/skills/index.ts +28 -19
  66. package/plugins/skills/project.ts +12 -7
  67. package/plugins/steer/index.ts +5 -4
  68. package/plugins/task/index.ts +80 -50
  69. package/plugins/task/plugin.json +6 -2
  70. package/plugins/task/style.ts +13 -14
  71. package/plugins/task/subagent.ts +67 -184
  72. package/plugins/todo/index.ts +39 -9
  73. package/plugins/tools/index.ts +9 -2
  74. package/plugins/tui/frontend.ts +139 -89
  75. package/plugins/tui/index.ts +2 -3
  76. package/plugins/tui/mentions.ts +11 -80
  77. package/plugins/tui/plugin.json +1 -1
  78. package/plugins/tui/screen.ts +55 -5
  79. package/plugins/tui/transcript.ts +17 -7
  80. package/plugins/tui/tui.ts +337 -101
  81. package/plugins/tui/vendor.ts +1 -1
  82. package/plugins/undo/checkpoint.ts +8 -4
  83. package/plugins/undo/index.ts +170 -31
  84. package/plugins/undo/plugin.json +1 -0
  85. package/plugins/undo/snapshot.ts +87 -14
  86. package/plugins/undo/style.ts +13 -14
  87. package/plugins/web/index.ts +7 -18
  88. package/plugins/web/plugin.json +1 -1
  89. package/plugins-dist/approval/index.js +363 -418
  90. package/plugins-dist/approval/policy.js +391 -508
  91. package/plugins-dist/approval/review.js +132 -158
  92. package/plugins-dist/approval/schema.js +50 -55
  93. package/plugins-dist/ask/index.js +115 -129
  94. package/plugins-dist/budget/index.js +27 -31
  95. package/plugins-dist/checks/checks.js +293 -329
  96. package/plugins-dist/checks/index.js +119 -139
  97. package/plugins-dist/checks/plugin.json +2 -1
  98. package/plugins-dist/checks/project.js +57 -65
  99. package/plugins-dist/commands/index.js +47 -29
  100. package/plugins-dist/compact/compact.js +233 -249
  101. package/plugins-dist/compact/index.js +98 -95
  102. package/plugins-dist/compact/style.js +9 -14
  103. package/plugins-dist/completions/index.js +30 -0
  104. package/plugins-dist/completions/plugin.json +9 -0
  105. package/plugins-dist/continue/index.js +40 -52
  106. package/plugins-dist/copy/index.js +40 -0
  107. package/plugins-dist/copy/plugin.json +9 -0
  108. package/plugins-dist/cost/index.js +98 -115
  109. package/plugins-dist/custom-commands/index.js +55 -72
  110. package/plugins-dist/editor/index.js +64 -72
  111. package/plugins-dist/fs/diff.js +111 -124
  112. package/plugins-dist/fs/fs.js +426 -469
  113. package/plugins-dist/fs/grep.js +262 -253
  114. package/plugins-dist/fs/index.js +20 -34
  115. package/plugins-dist/fs/plugin.json +1 -2
  116. package/plugins-dist/fs/renderers.js +100 -112
  117. package/plugins-dist/fs/style.js +11 -15
  118. package/plugins-dist/fs/sys.js +31 -43
  119. package/plugins-dist/hooks/index.js +107 -127
  120. package/plugins-dist/keys/index.js +27 -31
  121. package/plugins-dist/mcp/index.js +271 -199
  122. package/plugins-dist/mcp/install.js +123 -137
  123. package/plugins-dist/mcp/mcp.js +638 -577
  124. package/plugins-dist/mcp/plugin.json +3 -1
  125. package/plugins-dist/mcp/project.js +98 -115
  126. package/plugins-dist/memory/index.js +83 -88
  127. package/plugins-dist/memory/memory.js +111 -128
  128. package/plugins-dist/memory/style.js +9 -14
  129. package/plugins-dist/mentions/attach.js +91 -99
  130. package/plugins-dist/mentions/candidates.js +49 -0
  131. package/plugins-dist/mentions/index.js +71 -81
  132. package/plugins-dist/mentions/plugin.json +2 -1
  133. package/plugins-dist/mentions/style.js +9 -14
  134. package/plugins-dist/models/config.js +29 -43
  135. package/plugins-dist/models/configure.js +421 -474
  136. package/plugins-dist/models/context.js +14 -22
  137. package/plugins-dist/models/index.js +182 -189
  138. package/plugins-dist/models/provider.js +263 -307
  139. package/plugins-dist/models/saved.js +60 -72
  140. package/plugins-dist/modes/index.js +138 -165
  141. package/plugins-dist/plugins/index.js +34 -34
  142. package/plugins-dist/print/index.js +192 -175
  143. package/plugins-dist/prompts/index.js +86 -89
  144. package/plugins-dist/prompts/notes.js +31 -37
  145. package/plugins-dist/prompts/prompts.js +155 -193
  146. package/plugins-dist/prompts/results.js +40 -53
  147. package/plugins-dist/prompts/sys.js +39 -50
  148. package/plugins-dist/renderers/index.js +32 -32
  149. package/plugins-dist/repeats/index.js +131 -174
  150. package/plugins-dist/schedule/cron.js +49 -56
  151. package/plugins-dist/schedule/index.js +230 -247
  152. package/plugins-dist/schedule/store.js +93 -109
  153. package/plugins-dist/scratch/index.js +12 -18
  154. package/plugins-dist/screenshot/browser.js +136 -154
  155. package/plugins-dist/screenshot/index.js +37 -46
  156. package/plugins-dist/screenshot/sys.js +53 -65
  157. package/plugins-dist/screenshot/tool.js +98 -126
  158. package/plugins-dist/sessions/index.js +149 -117
  159. package/plugins-dist/shell/index.js +117 -135
  160. package/plugins-dist/shell/plugin.json +1 -1
  161. package/plugins-dist/shell/renderers.js +28 -33
  162. package/plugins-dist/shell/service.js +17 -23
  163. package/plugins-dist/shell/shell.js +307 -362
  164. package/plugins-dist/shell/sys.js +64 -79
  165. package/plugins-dist/skills/index.js +193 -211
  166. package/plugins-dist/skills/install.js +122 -149
  167. package/plugins-dist/skills/project.js +65 -73
  168. package/plugins-dist/skills/skills.js +135 -171
  169. package/plugins-dist/steer/index.js +108 -125
  170. package/plugins-dist/suggest/index.js +235 -259
  171. package/plugins-dist/task/index.js +130 -117
  172. package/plugins-dist/task/plugin.json +5 -2
  173. package/plugins-dist/task/style.js +9 -14
  174. package/plugins-dist/task/subagent.js +156 -279
  175. package/plugins-dist/todo/index.js +79 -63
  176. package/plugins-dist/tools/index.js +36 -42
  177. package/plugins-dist/tui/editor.js +145 -160
  178. package/plugins-dist/tui/frontend.js +639 -678
  179. package/plugins-dist/tui/history.js +34 -37
  180. package/plugins-dist/tui/index.js +16 -18
  181. package/plugins-dist/tui/markdown.js +203 -247
  182. package/plugins-dist/tui/mascot.js +266 -355
  183. package/plugins-dist/tui/mentions.js +67 -144
  184. package/plugins-dist/tui/plugin.json +1 -2
  185. package/plugins-dist/tui/render.js +35 -45
  186. package/plugins-dist/tui/screen.js +197 -180
  187. package/plugins-dist/tui/transcript.js +436 -468
  188. package/plugins-dist/tui/tui.js +1554 -1656
  189. package/plugins-dist/tui/vendor.js +1088 -1388
  190. package/plugins-dist/undo/checkpoint.js +97 -118
  191. package/plugins-dist/undo/index.js +281 -192
  192. package/plugins-dist/undo/plugin.json +3 -0
  193. package/plugins-dist/undo/snapshot.js +134 -99
  194. package/plugins-dist/undo/style.js +9 -14
  195. package/plugins-dist/update/index.js +26 -28
  196. package/plugins-dist/web/env.js +55 -68
  197. package/plugins-dist/web/index.js +80 -110
  198. package/plugins-dist/web/plugin.json +1 -2
  199. package/plugins-dist/web/renderers.js +4 -5
  200. package/plugins-dist/web/web.js +514 -593
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +9 -2
  203. package/src/api.ts +1 -1
  204. package/src/host.ts +39 -4
  205. package/src/remote.ts +6 -1
  206. package/src/session.ts +496 -36
@@ -1,397 +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) => launch(executable, env, command, cwd);
33
- async function startBackground(command) {
34
- const id = `bg${nextId++}`;
35
- const bg = { id, command, proc: await spawn(command), unread: "", dropped: 0 };
36
- const append = (text) => {
37
- bg.unread += text;
38
- if (bg.unread.length > MAX_BUFFER_CHARS) {
39
- bg.dropped += bg.unread.length - MAX_BUFFER_CHARS;
40
- bg.unread = bg.unread.slice(-MAX_BUFFER_CHARS);
41
- }
42
- };
43
- // 输出只进 unread,不另外累积:后台进程可能一直运行
44
- void Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => { });
45
- void bg.proc.exited.then((code) => {
46
- bg.exitCode = code;
47
- if (!bg.killed)
48
- opts.onExit?.({ id, command, exitCode: code });
49
- });
50
- background.set(id, bg);
51
- return id;
52
- }
53
- const status = (bg) => (bg.exitCode === undefined ? "running" : `exited with code ${bg.exitCode}`);
54
- /** 停掉一个还在运行的后台命令,等它退出 */
55
- const stop = async (bg) => {
56
- if (bg.exitCode !== undefined)
57
- return;
58
- bg.killed = true;
59
- killTree(executable, env, bg.proc);
60
- await bg.proc.exited;
61
- };
62
- const bash = {
63
- name: "bash",
64
- description: `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` +
65
- `Each call starts a fresh shell: cd and environment variables do not persist. ` +
66
- `Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` +
67
- "Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " +
68
- "then read new output with bash_output and stop it with kill_shell. " +
69
- "Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
70
- inputSchema: {
71
- type: "object",
72
- properties: { command: { type: "string" }, timeout_ms: { type: "integer" }, run_in_background: { type: "boolean" } },
73
- required: ["command"],
74
- additionalProperties: false,
75
- },
76
- effect: "external",
77
- concurrency: "exclusive",
78
- idempotent: false,
79
- async execute(input, { signal, progress }) {
80
- const { command, timeout_ms, run_in_background } = input;
81
- if (run_in_background) {
82
- const id = await startBackground(command);
83
- return { content: `Started background shell ${id}. Read its output with bash_output, stop it with kill_shell.` };
84
- }
85
- const timeout = Math.min(Math.max(timeout_ms ?? DEFAULT_TIMEOUT_MS, 1000), MAX_TIMEOUT_MS);
86
- const proc = await spawn(command);
87
- let timedOut = false;
88
- const killed = giveUp();
89
- const timer = setTimeout(() => {
90
- timedOut = true;
91
- killTree(executable, env, proc);
92
- killed.start();
93
- }, timeout);
94
- const kill = () => {
95
- killTree(executable, env, proc);
96
- killed.start();
97
- };
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 }), true, killed.done),
102
- collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text }), true, killed.done),
103
- Promise.race([proc.exited, killed.done.then(() => null)]),
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
- },
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
+ }
122
35
  };
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,
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 });
133
41
  });
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);
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
- };
196
- }
197
- /**
198
- * 执行一条命令并把输出收下来(不经过模型、不推进度);超时或中止时连同子进程一起杀掉。
199
- * 后台命令和别的插件(`shell@1`,例如 jade/checks)都用它
200
- */
201
- export async function capture(executable, env, command, opts) {
202
- opts.signal?.throwIfAborted();
203
- const proc = await launch(executable, env, command, opts.cwd);
204
- // 输出一到就推给调用方(用户自己执行的命令要边跑边看);它出错不影响命令
205
- const onOutput = (text) => {
206
- try {
207
- opts.onOutput?.(text);
208
- }
209
- catch {
210
- // 调用方的错
211
- }
212
- };
213
- let timedOut = false;
214
- const killed = giveUp();
215
- const kill = () => {
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;
216
78
  killTree(executable, env, proc);
217
79
  killed.start();
218
- };
219
- const timer = setTimeout(() => {
220
- timedOut = true;
221
- kill();
222
- }, opts.timeoutMs);
223
- opts.signal?.addEventListener("abort", kill, { once: true });
224
- try {
80
+ }, timeout);
81
+ const kill = () => {
82
+ killTree(executable, env, proc);
83
+ killed.start();
84
+ };
85
+ signal.addEventListener("abort", kill, { once: true });
86
+ try {
225
87
  const [stdout, stderr, code] = await Promise.all([
226
- collect(proc.stdout, onOutput, true, killed.done),
227
- collect(proc.stderr, onOutput, true, killed.done),
228
- Promise.race([proc.exited, killed.done.then(() => null)]),
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)])
229
91
  ]);
230
- opts.signal?.throwIfAborted();
231
- return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join("\n"), timedOut };
232
- }
233
- finally {
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 {
234
107
  clearTimeout(timer);
235
- opts.signal?.removeEventListener("abort", kill);
108
+ signal.removeEventListener("abort", kill);
109
+ }
236
110
  }
237
- }
238
- /**
239
- * 找到要执行的 shell 程序,找不到返回 undefined。
240
- *
241
- * Windows 上 Git for Windows 安装时默认只把 Git\cmd 加进 PATH,PATH 里通常找不到 bash,
242
- * 所以 bash、sh 还要从 git.exe 的位置和常见安装目录找 Git 的安装目录。
243
- * Git 的 bin\bash.exe、bin\sh.exe 只是启动器,真正的 shell 是它启动的 usr\bin 下的同名程序;
244
- * killTree 按 WINPID 找 msys 进程,用启动器的 pid 找不到,所以直接用 usr\bin 下的。
245
- * Git Bash 优先于 PATH 里别的 bash(例如 System32\bash.exe 是 WSL 的启动器,看不到 Windows 路径)
246
- */
247
- export function findShell(shell) {
248
- const found = which(shell);
249
- if (process.platform !== "win32")
250
- return found;
251
- const name = /^(bash|sh)(\.exe)?$/i.exec(shell)?.[1]?.toLowerCase();
252
- if (!name)
253
- return found;
254
- const inGit = (root) => {
255
- const real = path.join(root, "usr", "bin", `${name}.exe`);
256
- return existsSync(real) ? real : undefined;
257
- };
258
- const m = /^(.*\\Git)\\(usr\\)?bin\\(bash|sh)\.exe$/i.exec(found ?? "");
259
- if (m)
260
- return inGit(m[1]) ?? found;
261
- // git.exe 在 Git\cmd、Git\bin 或 Git\mingw64\bin 下
262
- const git = which("git");
263
- const roots = git ? [path.dirname(path.dirname(git)), path.dirname(path.dirname(path.dirname(git)))] : [];
264
- for (const base of [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, "Programs")]) {
265
- if (base)
266
- roots.push(path.join(base, "Git"));
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)` };
267
148
  }
268
- for (const root of roots) {
269
- const real = inGit(root);
270
- if (real)
271
- return real;
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)})` };
272
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()) {
173
+ if (bg.exitCode !== undefined)
174
+ continue;
175
+ bg.killed = true;
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
+ };
188
+ }
189
+ export async function capture(executable, env, command, opts) {
190
+ opts.signal?.throwIfAborted();
191
+ const proc = await launch(executable, env, command, opts.cwd);
192
+ const onOutput = (text) => {
193
+ try {
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
+ }
221
+ }
222
+ export function findShell(shell) {
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)
273
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;
274
248
  }
275
- /**
276
- * 直接执行 Git 的 usr\bin\bash.exe 时没有经过 bin\bash.exe 启动器,启动器会把 /usr/bin、/mingw64/bin 加进 PATH;
277
- * 不补上的话 PATH 里只有 Windows 的目录,cat、grep、head、sed 都找不到,find 还会变成 Windows 的 find.exe。
278
- * 不是 Git Bash 时返回 undefined,继承当前环境
279
- */
280
249
  export function shellEnv(executable, env = process.env) {
281
- if (process.platform !== "win32")
282
- return undefined;
283
- const m = /^(.*\\Git)\\usr\\bin\\(bash|sh)\.exe$/i.exec(executable);
284
- if (!m)
285
- return undefined;
286
- const root = m[1];
287
- // Windows 的环境变量名不分大小写,展开成普通对象后要沿用原来的键名(通常是 Path),否则会同时出现 Path 和 PATH
288
- const key = Object.keys(env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
289
- const dirs = [path.join(root, "usr", "bin"), path.join(root, "mingw64", "bin")];
290
- 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) };
291
259
  }
292
- /** 标记用的环境变量:命令启动的进程都继承它,killTree 在 Windows 上靠它把它们找出来 */
293
260
  const TAG = "JADE_SHELL_TAG";
294
261
  let launched = 0;
295
- /** 启动 shell 执行一条命令 */
296
262
  async function launch(executable, env, command, cwd) {
297
- const tag = `${process.pid}-${Date.now().toString(36)}-${++launched}`;
298
- const proc = await spawnProc([executable, "-c", command], {
299
- cwd,
300
- env: process.platform === "win32" ? { ...(env ?? process.env), [TAG]: tag } : env,
301
- // 自成进程组,超时/中断时能连同子进程一起杀掉
302
- detached: process.platform !== "win32",
303
- });
304
- return Object.assign(proc, { tag });
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 });
305
270
  }
306
- /**
307
- * 只杀 shell 本身不够:它启动的子进程还占着 stdout/stderr 管道,读取会一直等到它们退出。
308
- * POSIX 上杀整个进程组。Windows 上 Git Bash(msys)模拟 fork,Windows 进程树里看不到父子关系;
309
- * 按 WINPID 找也不行:msys 的 exec(bash -c "npm login" 直接换成 npm 那个脚本)会换一个 Windows 进程,
310
- * 我们手里的 pid 只剩一个空壳。所以启动时在环境变量里放一个标记,这里在 msys 的 /proc 里把带标记的进程
311
- * 找出来,连同它们的进程组(里面有 node 这类不是 msys 的子进程)一起杀掉
312
- */
313
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)]);
314
277
  try {
315
- if (process.platform !== "win32")
316
- return process.kill(-proc.pid, "SIGKILL");
317
- const script = `for d in /proc/[0-9]*; do ` +
318
- `if grep -qa "${TAG}=${proc.tag}" "$d/environ" 2>/dev/null || [ "$(cat "$d/winpid" 2>/dev/null)" = "${proc.pid}" ]; then ` +
319
- `kill -9 -- "-$(cat "$d/pgid")" "\${d#/proc/}" 2>/dev/null; fi; done`;
320
- // 先按 Windows 的进程树杀:cmd、node 这类不是 msys 的进程启动的子进程只有这里找得到,先杀掉它们的父进程就找不到了
321
- runSync(["taskkill", "/T", "/F", "/PID", String(proc.pid)]);
322
- try {
323
- // 用没有标记的环境变量跑,免得它把自己也算进去
324
- runSync([shell, "-c", script], { env });
325
- }
326
- catch {
327
- // 不是 msys/cygwin 的 shell
328
- }
329
- }
330
- catch {
331
- // 已经退出
332
- }
278
+ runSync([shell, "-c", script], { env });
279
+ } catch {}
280
+ } catch {}
333
281
  }
334
- /** 杀掉之后最多再等这么久就不等了:没杀干净的进程还占着输出管道时,读取永远等不到结束,这一轮(和整个界面)就卡在那里 */
335
282
  const KILL_GRACE_MS = 2000;
336
- /** start 之后过 KILL_GRACE_MS,done 就 resolve;不 start 永远不 resolve */
337
283
  function giveUp() {
338
- let start = () => { };
339
- const done = new Promise((resolve) => {
340
- start = () => void setTimeout(resolve, KILL_GRACE_MS);
341
- });
342
- return { start, done };
284
+ let start = () => {};
285
+ const done = new Promise((resolve) => {
286
+ start = () => void setTimeout(resolve, KILL_GRACE_MS);
287
+ });
288
+ return { start, done };
343
289
  }
344
- /**
345
- * 返回截好的输出:超过 MAX_OUTPUT_CHARS 时保留开头和结尾各一半,中间截掉。
346
- * 边读边截,输出再多也只占几倍 MAX_OUTPUT_CHARS 的内存。keep 为 false 时只推给 onChunk,不累积,返回空串
347
- */
348
290
  async function collect(stream, onChunk, keep = true, stop) {
349
- const half = MAX_OUTPUT_CHARS / 2;
350
- const decoder = new TextDecoder();
351
- let head = "";
352
- let tail = "";
353
- let total = 0;
354
- const add = (text) => {
355
- onChunk(text);
356
- if (!keep)
357
- return;
358
- total += text.length;
359
- if (head.length < half) {
360
- const n = half - head.length;
361
- head += text.slice(0, n);
362
- text = text.slice(n);
363
- }
364
- tail += text;
365
- // 攒到两倍再截,不用每块都复制
366
- if (tail.length > 2 * half)
367
- tail = tail.slice(-half);
368
- };
369
- // stop:不再等(进程杀掉之后管道还被别的进程占着),返回已经读到的
370
- const it = stream[Symbol.asyncIterator]();
371
- const stopped = stop?.then(() => undefined);
372
- for (;;) {
373
- const r = await (stopped ? Promise.race([it.next(), stopped]) : it.next());
374
- if (!r) {
375
- void Promise.resolve(it.return?.()).catch(() => { });
376
- break;
377
- }
378
- if (r.done)
379
- break;
380
- const text = decoder.decode(r.value, { stream: true });
381
- if (text)
382
- add(text);
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;
383
319
  }
384
- const rest = decoder.decode();
385
- if (rest)
386
- add(rest);
387
- if (total <= MAX_OUTPUT_CHARS)
388
- return (head + tail).trimEnd();
389
- 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();
390
334
  }
391
- /** 保留开头和结尾,中间截掉 */
392
335
  function clip(s) {
393
- if (s.length <= MAX_OUTPUT_CHARS)
394
- return s.trimEnd();
395
- const half = MAX_OUTPUT_CHARS / 2;
396
- 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();
397
342
  }