@uncarved/jade 0.2.1 → 0.3.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 (227) hide show
  1. package/README.md +65 -2
  2. package/assets/logo.svg +1 -0
  3. package/bin/jade.js +4 -0
  4. package/dist/api.d.ts +5 -250
  5. package/dist/api.js +5 -7
  6. package/dist/api.js.map +1 -1
  7. package/dist/fetch.d.ts +8 -0
  8. package/dist/fetch.js +19 -17
  9. package/dist/fetch.js.map +1 -1
  10. package/dist/host.d.ts +12 -1
  11. package/dist/host.js +49 -1
  12. package/dist/host.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/main.js +26 -4
  17. package/dist/main.js.map +1 -1
  18. package/dist/remote.js +4 -0
  19. package/dist/remote.js.map +1 -1
  20. package/dist/session.d.ts +2 -0
  21. package/dist/session.js +133 -13
  22. package/dist/session.js.map +1 -1
  23. package/dist/source.d.ts +2 -10
  24. package/dist/source.js.map +1 -1
  25. package/dist/update.d.ts +8 -20
  26. package/dist/update.js +12 -1
  27. package/dist/update.js.map +1 -1
  28. package/package.json +4 -2
  29. package/plugins/approval/index.ts +236 -85
  30. package/plugins/approval/plugin.json +1 -1
  31. package/plugins/approval/policy.ts +36 -17
  32. package/plugins/approval/review.ts +1 -1
  33. package/plugins/ask/index.ts +2 -2
  34. package/plugins/budget/index.ts +1 -1
  35. package/plugins/checks/checks.ts +3 -2
  36. package/plugins/checks/index.ts +2 -5
  37. package/plugins/commands/index.ts +2 -44
  38. package/plugins/compact/compact.ts +8 -3
  39. package/plugins/compact/index.ts +13 -16
  40. package/plugins/continue/index.ts +1 -1
  41. package/plugins/cost/index.ts +143 -0
  42. package/plugins/cost/plugin.json +13 -0
  43. package/plugins/custom-commands/index.ts +85 -0
  44. package/plugins/custom-commands/plugin.json +8 -0
  45. package/plugins/editor/index.ts +88 -0
  46. package/plugins/editor/plugin.json +17 -0
  47. package/plugins/fs/fs.ts +33 -6
  48. package/plugins/fs/grep.ts +19 -7
  49. package/plugins/fs/index.ts +6 -7
  50. package/plugins/fs/plugin.json +1 -1
  51. package/plugins/fs/renderers.ts +1 -1
  52. package/plugins/hooks/index.ts +152 -0
  53. package/plugins/hooks/plugin.json +14 -0
  54. package/plugins/keys/index.ts +2 -18
  55. package/plugins/mcp/index.ts +43 -15
  56. package/plugins/mcp/install.ts +139 -0
  57. package/plugins/mcp/mcp.ts +2 -1
  58. package/plugins/mcp/plugin.json +1 -1
  59. package/plugins/mcp/project.ts +37 -1
  60. package/plugins/memory/index.ts +4 -9
  61. package/plugins/memory/plugin.json +1 -1
  62. package/plugins/mentions/index.ts +2 -2
  63. package/plugins/models/configure.ts +258 -150
  64. package/plugins/models/context.ts +2 -2
  65. package/plugins/models/index.ts +39 -45
  66. package/plugins/models/plugin.json +1 -1
  67. package/plugins/models/provider.ts +34 -5
  68. package/plugins/models/saved.ts +8 -4
  69. package/plugins/modes/index.ts +2 -17
  70. package/plugins/plugins/index.ts +2 -2
  71. package/plugins/print/index.ts +36 -6
  72. package/plugins/print/plugin.json +1 -0
  73. package/plugins/prompts/index.ts +22 -14
  74. package/plugins/{memory → prompts}/notes.ts +21 -9
  75. package/plugins/prompts/plugin.json +8 -2
  76. package/plugins/prompts/prompts.ts +5 -4
  77. package/plugins/renderers/index.ts +2 -43
  78. package/plugins/repeats/index.ts +32 -2
  79. package/plugins/schedule/index.ts +2 -2
  80. package/plugins/scratch/index.ts +2 -3
  81. package/plugins/screenshot/browser.ts +221 -0
  82. package/plugins/screenshot/index.ts +29 -15
  83. package/plugins/screenshot/plugin.json +1 -1
  84. package/plugins/screenshot/tool.ts +27 -51
  85. package/plugins/sessions/index.ts +2 -17
  86. package/plugins/shell/index.ts +115 -7
  87. package/plugins/shell/plugin.json +3 -1
  88. package/plugins/shell/renderers.ts +1 -1
  89. package/plugins/shell/service.ts +2 -13
  90. package/plugins/shell/shell.ts +119 -47
  91. package/plugins/skills/index.ts +172 -37
  92. package/plugins/skills/install.ts +212 -0
  93. package/plugins/skills/plugin.json +3 -2
  94. package/plugins/skills/project.ts +38 -1
  95. package/plugins/skills/skills.ts +28 -9
  96. package/plugins/steer/index.ts +142 -0
  97. package/plugins/steer/plugin.json +8 -0
  98. package/plugins/suggest/index.ts +16 -11
  99. package/plugins/suggest/plugin.json +1 -1
  100. package/plugins/task/index.ts +18 -57
  101. package/plugins/task/plugin.json +9 -3
  102. package/plugins/task/subagent.ts +25 -7
  103. package/plugins/todo/index.ts +2 -2
  104. package/plugins/tools/index.ts +50 -0
  105. package/plugins/tools/plugin.json +7 -0
  106. package/plugins/tui/editor.ts +10 -2
  107. package/plugins/tui/frontend.ts +129 -23
  108. package/plugins/tui/index.ts +3 -8
  109. package/plugins/tui/markdown.ts +51 -6
  110. package/plugins/tui/mascot.ts +506 -0
  111. package/plugins/tui/plugin.json +2 -2
  112. package/plugins/tui/screen.ts +6 -0
  113. package/plugins/tui/transcript.ts +17 -2
  114. package/plugins/tui/tui.ts +344 -97
  115. package/plugins/undo/checkpoint.ts +2 -2
  116. package/plugins/undo/index.ts +84 -26
  117. package/plugins/undo/plugin.json +8 -2
  118. package/plugins/undo/snapshot.ts +129 -0
  119. package/plugins/update/index.ts +11 -15
  120. package/plugins/update/plugin.json +2 -1
  121. package/plugins/web/index.ts +8 -11
  122. package/plugins/web/plugin.json +1 -1
  123. package/plugins/web/renderers.ts +1 -1
  124. package/plugins-dist/approval/index.js +221 -51
  125. package/plugins-dist/approval/plugin.json +1 -1
  126. package/plugins-dist/approval/policy.js +30 -15
  127. package/plugins-dist/ask/index.js +1 -1
  128. package/plugins-dist/budget/index.js +1 -1
  129. package/plugins-dist/checks/checks.js +2 -1
  130. package/plugins-dist/checks/index.js +1 -1
  131. package/plugins-dist/commands/index.js +1 -1
  132. package/plugins-dist/compact/compact.js +6 -1
  133. package/plugins-dist/compact/index.js +12 -8
  134. package/plugins-dist/continue/index.js +1 -1
  135. package/plugins-dist/cost/index.js +135 -0
  136. package/plugins-dist/cost/plugin.json +16 -0
  137. package/plugins-dist/custom-commands/index.js +86 -0
  138. package/plugins-dist/custom-commands/plugin.json +12 -0
  139. package/plugins-dist/editor/index.js +89 -0
  140. package/plugins-dist/editor/plugin.json +21 -0
  141. package/plugins-dist/fs/fs.js +34 -6
  142. package/plugins-dist/fs/grep.js +17 -6
  143. package/plugins-dist/fs/index.js +6 -6
  144. package/plugins-dist/fs/plugin.json +1 -1
  145. package/plugins-dist/hooks/index.js +145 -0
  146. package/plugins-dist/hooks/plugin.json +19 -0
  147. package/plugins-dist/keys/index.js +1 -1
  148. package/plugins-dist/mcp/index.js +45 -13
  149. package/plugins-dist/mcp/install.js +160 -0
  150. package/plugins-dist/mcp/mcp.js +2 -1
  151. package/plugins-dist/mcp/plugin.json +2 -1
  152. package/plugins-dist/mcp/project.js +42 -1
  153. package/plugins-dist/memory/index.js +3 -5
  154. package/plugins-dist/memory/plugin.json +1 -1
  155. package/plugins-dist/mentions/index.js +1 -1
  156. package/plugins-dist/models/configure.js +252 -151
  157. package/plugins-dist/models/context.js +2 -2
  158. package/plugins-dist/models/index.js +41 -17
  159. package/plugins-dist/models/plugin.json +1 -1
  160. package/plugins-dist/models/provider.js +17 -3
  161. package/plugins-dist/models/saved.js +9 -4
  162. package/plugins-dist/modes/index.js +1 -1
  163. package/plugins-dist/plugins/index.js +1 -1
  164. package/plugins-dist/print/index.js +37 -3
  165. package/plugins-dist/print/plugin.json +3 -0
  166. package/plugins-dist/prompts/index.js +22 -3
  167. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  168. package/plugins-dist/prompts/plugin.json +8 -2
  169. package/plugins-dist/prompts/prompts.js +5 -4
  170. package/plugins-dist/renderers/index.js +1 -1
  171. package/plugins-dist/repeats/index.js +28 -2
  172. package/plugins-dist/schedule/index.js +1 -1
  173. package/plugins-dist/scratch/index.js +1 -1
  174. package/plugins-dist/screenshot/browser.js +187 -0
  175. package/plugins-dist/screenshot/index.js +28 -13
  176. package/plugins-dist/screenshot/plugin.json +1 -1
  177. package/plugins-dist/screenshot/tool.js +27 -49
  178. package/plugins-dist/sessions/index.js +1 -1
  179. package/plugins-dist/shell/index.js +119 -4
  180. package/plugins-dist/shell/plugin.json +3 -1
  181. package/plugins-dist/shell/shell.js +106 -36
  182. package/plugins-dist/skills/index.js +184 -35
  183. package/plugins-dist/skills/install.js +178 -0
  184. package/plugins-dist/skills/plugin.json +6 -2
  185. package/plugins-dist/skills/project.js +43 -1
  186. package/plugins-dist/skills/skills.js +27 -10
  187. package/plugins-dist/steer/index.js +135 -0
  188. package/plugins-dist/steer/plugin.json +12 -0
  189. package/plugins-dist/suggest/index.js +15 -9
  190. package/plugins-dist/suggest/plugin.json +1 -1
  191. package/plugins-dist/task/index.js +17 -46
  192. package/plugins-dist/task/plugin.json +11 -5
  193. package/plugins-dist/task/subagent.js +21 -6
  194. package/plugins-dist/todo/index.js +1 -1
  195. package/plugins-dist/tools/index.js +49 -0
  196. package/plugins-dist/tools/plugin.json +9 -0
  197. package/plugins-dist/tui/editor.js +7 -2
  198. package/plugins-dist/tui/frontend.js +134 -15
  199. package/plugins-dist/tui/index.js +2 -1
  200. package/plugins-dist/tui/markdown.js +48 -6
  201. package/plugins-dist/tui/mascot.js +441 -0
  202. package/plugins-dist/tui/plugin.json +3 -2
  203. package/plugins-dist/tui/screen.js +2 -0
  204. package/plugins-dist/tui/transcript.js +16 -1
  205. package/plugins-dist/tui/tui.js +320 -88
  206. package/plugins-dist/tui/vendor.js +1388 -1088
  207. package/plugins-dist/undo/checkpoint.js +1 -1
  208. package/plugins-dist/undo/index.js +91 -24
  209. package/plugins-dist/undo/plugin.json +10 -3
  210. package/plugins-dist/undo/snapshot.js +111 -0
  211. package/plugins-dist/update/index.js +9 -10
  212. package/plugins-dist/update/plugin.json +4 -1
  213. package/plugins-dist/web/index.js +7 -7
  214. package/plugins-dist/web/plugin.json +1 -1
  215. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  216. package/sdk/python/jade_plugin.py +8 -0
  217. package/src/api.ts +7 -262
  218. package/src/fetch.ts +18 -16
  219. package/src/host.ts +49 -1
  220. package/src/index.ts +1 -1
  221. package/src/main.ts +23 -5
  222. package/src/remote.ts +2 -0
  223. package/src/session.ts +134 -15
  224. package/src/source.ts +2 -11
  225. package/src/update.ts +16 -10
  226. package/plugins/undo/notes.ts +0 -43
  227. package/plugins-dist/undo/notes.js +0 -36
@@ -1,11 +1,29 @@
1
1
  // jade/shell:bash 工具,以及后台命令的 bash_output、kill_shell;shell@1 给其他插件执行命令。
2
+ // 后台命令自己结束时告诉用户,并给模型留一句说明(不用它一直轮询);/shells 给用户看和停掉后台命令。
2
3
 
3
- import { definePlugin, type UI } from "../../src/api.ts";
4
- import type { Prompts } from "../prompts/index.ts";
5
- import type { Renderers } from "../renderers/index.ts";
4
+ import { definePlugin, type UI } from "@uncarved/jade-api";
5
+ import type { Commands, Prompts, Renderers, Tools } from "@uncarved/jade-api/services";
6
6
  import { shellRenderers } from "./renderers.ts";
7
7
  import { shellService } from "./service.ts";
8
- import { shellTools } from "./shell.ts";
8
+ import { shellTools, type ShellTools } from "./shell.ts";
9
+
10
+ /** 打开着的会话 → 它的后台命令(/shells 用) */
11
+ const sessions = new Map<string, Pick<ShellTools, "list" | "kill">>();
12
+ const firstLine = (command: string) => {
13
+ const line = command.split("\n")[0]!;
14
+ return line.length > 80 ? `${line.slice(0, 80)}…` : line;
15
+ };
16
+
17
+ /** /sh 的时限:用户自己看着它跑(登录、安装),给到 bash 工具的上限;不想等就按 esc */
18
+ const SH_TIMEOUT_MS = 600_000;
19
+ /** 边跑边显示的输出最多留这么多个字符(前端只显示末尾几行) */
20
+ const SH_LIVE_CHARS = 4000;
21
+ /** /sh 的结果收起时那一行最多这么多个字符 */
22
+ const SH_SUMMARY = 160;
23
+ // 设了 NO_COLOR(非空)或标准输出不是终端时不输出颜色
24
+ const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
25
+ /** 失败的红色,其余的灰色 */
26
+ const shade = (failed: boolean, s: string) => (colors ? (failed ? `\x1b[31m${s}\x1b[39m` : `\x1b[2m${s}\x1b[22m`) : s);
9
27
 
10
28
  export default definePlugin({
11
29
  process(ctx) {
@@ -13,12 +31,99 @@ export default definePlugin({
13
31
  const renderers = ctx.service<Renderers>("renderers@1");
14
32
  if (renderers) for (const r of shellRenderers) renderers.tool(r);
15
33
  // shell@1:找 shell 和杀进程树只有一份(见 service.ts)
16
- ctx.provide("shell@1", shellService(typeof ctx.config.shell === "string" ? { shell: ctx.config.shell } : {}));
34
+ const shell = shellService(typeof ctx.config.shell === "string" ? { shell: ctx.config.shell } : {});
35
+ ctx.provide("shell@1", shell);
36
+ const commands = ctx.service<Commands>("commands@1");
37
+ // 用户自己执行一条命令(前端里 !<命令> 是它的简写):不经过模型和审批。
38
+ // 输出显示给用户;会话里已经有对话时,结果作为用户的消息发给模型,它接着做(例如它让用户先 npm login);
39
+ // 还没有对话、或用户按 esc 停掉时不开始一轮,只给模型留一句说明,下一次请求时它能看到
40
+ commands?.register({
41
+ name: "sh",
42
+ args: "<command>",
43
+ description: "run a shell command yourself (short form: !<command>); then the agent continues with its output",
44
+ // 不是 instant:和消息一样排队,前端才把它当作正在做的事(esc 能停掉它)
45
+ async run(args, { sessions: manager, signal, print, progress }) {
46
+ const command = args.trim();
47
+ if (!command) return "Usage: /sh <command>, or !<command>";
48
+ if (!shell.executable) return shell.unavailable;
49
+ // 边跑边显示输出(npm login 这类要看着它的提示);被 esc 停掉时,已经输出的也留下来
50
+ let live = "";
51
+ let r: { code: number | null; output: string; timedOut: boolean };
52
+ let stopped = false;
53
+ try {
54
+ r = await shell.run(command, {
55
+ cwd: ctx.cwd,
56
+ timeoutMs: SH_TIMEOUT_MS,
57
+ signal,
58
+ onOutput(text) {
59
+ live = (live + text).slice(-SH_LIVE_CHARS);
60
+ progress?.(live);
61
+ },
62
+ });
63
+ } catch (e) {
64
+ if (!signal.aborted) throw e;
65
+ stopped = true;
66
+ r = { code: null, output: live.trimEnd(), timedOut: false };
67
+ }
68
+ const status = stopped ? "stopped by the user" : r.timedOut ? `timed out after ${SH_TIMEOUT_MS / 1000}s` : `exit code ${r.code}`;
69
+ // 和 bash 工具的结果一个样子:一行摘要,完整输出折叠起来
70
+ const lines = r.output ? r.output.split("\n") : [];
71
+ const failed = r.code !== 0;
72
+ const first = failed ? `${status}${lines.length ? ` · ${lines[0]}` : ""}` : (lines[0] ?? "(no output)");
73
+ const more = lines.length > 1 ? ` (+${lines.length - 1} lines)` : "";
74
+ const folded = lines.length > 1 || first.length > SH_SUMMARY;
75
+ print(shade(failed, `⎿ ${first.length > SH_SUMMARY ? `${first.slice(0, SH_SUMMARY)}…` : first}${more}`), folded ? { details: r.output.replace(/^/gm, " ") } : undefined);
76
+ const session = manager.current;
77
+ if (!stopped && session && session.state.messages.length > 0) return { prompt: `I ran this shell command myself (${status}):\n$ ${command}\n${r.output}` };
78
+ if (session) ctx.service<Prompts>("prompts@1")?.note(session.id, `The user ran this shell command themselves (${status}):\n$ ${command}\n${r.output}`);
79
+ },
80
+ });
81
+ commands?.register({
82
+ name: "shells",
83
+ args: "[kill <id>]",
84
+ description: "list the background commands the agent started, or stop one",
85
+ instant: true,
86
+ async run(args, { sessions: manager }) {
87
+ const shells = manager.current && sessions.get(manager.current.id);
88
+ const [verb, id] = args.trim().split(/\s+/);
89
+ if (verb === "kill" && id) return shells && (await shells.kill(id)) ? `Stopped ${id}.` : `There is no background command ${id}.`;
90
+ const all = shells?.list() ?? [];
91
+ if (all.length === 0) return "No background commands.";
92
+ return all.map((b) => `${b.id} ${b.status} ${firstLine(b.command)}`).join("\n");
93
+ },
94
+ });
17
95
  },
18
96
 
19
97
  async session(ctx) {
20
98
  const shell = typeof ctx.config.shell === "string" ? ctx.config.shell : undefined;
21
- const { tools, executable, unavailable, shutdown } = shellTools({ cwd: ctx.cwd, ...(shell ? { shell } : {}) });
99
+ const id = ctx.session.id;
100
+ const { tools, executable, unavailable, shutdown, list, kill } = shellTools({
101
+ cwd: ctx.cwd,
102
+ ...(shell ? { shell } : {}),
103
+ onExit(bg) {
104
+ const what = `Background shell ${bg.id} (${firstLine(bg.command)}) exited with code ${bg.exitCode}`;
105
+ ctx.service<UI>("ui@1")?.notify(what, bg.exitCode === 0 ? "info" : "warning");
106
+ ctx.service<Prompts>("prompts@1")?.note(id, `${what}. Read its remaining output with bash_output.`);
107
+ },
108
+ });
109
+ sessions.set(id, { list, kill });
110
+ // 嵌套 Agent 的 bash:只收命令和时限,不能在后台跑。它不是只读工具,哪些命令能执行由使用方把关
111
+ // (jade/task 按审批规则只放行只读的命令,下面的说明文字是按这个写的)
112
+ const bash = tools.find((t) => t.name === "bash");
113
+ try {
114
+ if (bash) {
115
+ ctx.service<Tools>("tools@1")?.register({
116
+ ...bash,
117
+ description:
118
+ "Run a read-only shell command in the working directory (for example git log, git diff, git status, ls, rg) and return its exit code and output. " +
119
+ "Commands that could change anything, or that touch paths outside the working directory, are refused.",
120
+ inputSchema: { type: "object", properties: { command: { type: "string" }, timeout_ms: { type: "integer" } }, required: ["command"], additionalProperties: false },
121
+ execute: (input, c) => bash.execute({ command: (input as { command: string }).command, timeout_ms: (input as { timeout_ms?: number }).timeout_ms }, c),
122
+ });
123
+ }
124
+ } catch {
125
+ // jade/tools 被隔离时它的服务已失效:嵌套 Agent 没有 bash,主会话的照常
126
+ }
22
127
  if (unavailable) ctx.service<UI>("ui@1")?.notify(unavailable, "warning");
23
128
  for (const tool of tools) ctx.kernel.tool(tool);
24
129
  if (executable) {
@@ -28,6 +133,9 @@ export default definePlugin({
28
133
  ctx.service<Prompts>("prompts@1")?.add({ text: lines.join("\n") });
29
134
  }
30
135
  // 会话关闭(换会话、退出)时杀掉还在运行的后台命令
31
- await ctx.effect(() => shutdown);
136
+ await ctx.effect(() => () => {
137
+ sessions.delete(id);
138
+ shutdown();
139
+ });
32
140
  },
33
141
  });
@@ -7,7 +7,9 @@
7
7
  "optional": [
8
8
  "ui@1",
9
9
  "prompts@1",
10
- "renderers@1"
10
+ "renderers@1",
11
+ "commands@1",
12
+ "tools@1"
11
13
  ],
12
14
  "config": {
13
15
  "shell": {
@@ -3,7 +3,7 @@
3
3
  // 运行中的输出不登记 progress:bash 推送的是 { kind, stream, text },前端对 { text } 形式的进度默认逐行显示,
4
4
  // 正是想要的;自己写 progress 反而只能把一次推送(可能是好几行、半行)显示成一行。
5
5
 
6
- import type { ToolRenderer } from "../renderers/index.ts";
6
+ import type { ToolRenderer } from "@uncarved/jade-api/services";
7
7
 
8
8
  // 截断和颜色从旧 jade 的 ui/render.ts、ui/screen.ts 复制:插件之间不共享代码,fs 插件也有一份
9
9
  const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n) + "…" : s);
@@ -4,20 +4,9 @@
4
4
  // 和 bash 工具不同,这里的命令不经过模型和审批:调用方(插件)自己决定要不要问用户。
5
5
  // 没有 shell 时 executable 是 undefined,run 会抛错;调用方据此说明"在这台机器上做不了"。
6
6
 
7
- import { capture, findShell, shellEnv, type RunCommand, type RunResult } from "./shell.ts";
7
+ import { capture, findShell, shellEnv } from "./shell.ts";
8
8
  import { which } from "./sys.ts";
9
-
10
- /** shell@1 */
11
- export interface Shell {
12
- /** 实际执行的 shell 程序;这台机器上没有时为 undefined */
13
- readonly executable: string | undefined;
14
- /** 找不到 shell 时的说明 */
15
- readonly unavailable?: string;
16
- /** 执行一条命令并收集输出;超时或中止时连同子进程一起杀掉 */
17
- run: RunCommand;
18
- /** 在 PATH 里找可执行文件(Windows 上按 PATHEXT 补扩展名),找不到返回 undefined */
19
- which(bin: string): string | undefined;
20
- }
9
+ import type { RunCommand, RunResult, Shell } from "@uncarved/jade-api/services";
21
10
 
22
11
  /** 默认的 shell:JADE_SHELL,否则 bash(Windows 上是 Git Bash) */
23
12
  export const shellName = (configured: unknown): string => (typeof configured === "string" && configured.trim() ? configured : (process.env.JADE_SHELL ?? "bash"));
@@ -7,6 +7,7 @@ import { existsSync } from "node:fs";
7
7
  import path from "node:path";
8
8
  import type { Tool } from "uncarved";
9
9
  import { runSync, spawn as spawnProc, which, type Proc } from "./sys.ts";
10
+ import type { RunCommand, RunResult } from "@uncarved/jade-api/services";
10
11
 
11
12
  const DEFAULT_TIMEOUT_MS = 120_000;
12
13
  const MAX_TIMEOUT_MS = 600_000;
@@ -18,6 +19,8 @@ export interface ShellOptions {
18
19
  cwd: string;
19
20
  /** 默认 JADE_SHELL 环境变量,否则 bash(Windows 上是 Git Bash) */
20
21
  shell?: string;
22
+ /** 后台命令自己结束时调用(被 kill_shell、shutdown 停掉的不算) */
23
+ onExit?(bg: { id: string; command: string; exitCode: number | null }): void;
21
24
  }
22
25
 
23
26
  export interface ShellTools {
@@ -29,20 +32,14 @@ export interface ShellTools {
29
32
  unavailable?: string;
30
33
  /** 杀掉所有还在运行的后台进程 */
31
34
  shutdown(): void;
35
+ /** 本会话启动过的后台命令 */
36
+ list(): { id: string; command: string; status: string }[];
37
+ /** 停掉一个后台命令(连同它启动的进程);没有这个编号时返回 false */
38
+ kill(id: string): Promise<boolean>;
32
39
  /** 宿主和插件自己执行一条命令(不经过模型和审批),找不到 shell 时为 undefined */
33
40
  run?: RunCommand;
34
41
  }
35
42
 
36
- export interface RunResult {
37
- /** 超时被杀掉时为 null */
38
- code: number | null;
39
- /** stdout 和 stderr 合在一起,超长时保留首尾 */
40
- output: string;
41
- timedOut: boolean;
42
- }
43
-
44
- export type RunCommand = (command: string, opts: { cwd?: string; timeoutMs: number; signal?: AbortSignal }) => Promise<RunResult>;
45
-
46
43
  /** 只要 bash 工具时用(测试) */
47
44
  export function shellTool(opts: ShellOptions): Tool {
48
45
  const { tools, unavailable } = shellTools(opts);
@@ -53,12 +50,14 @@ export function shellTool(opts: ShellOptions): Tool {
53
50
  interface Background {
54
51
  id: string;
55
52
  command: string;
56
- proc: Proc;
53
+ proc: Tagged;
57
54
  /** 还没被 bash_output 读走的输出 */
58
55
  unread: string;
59
56
  /** 因超出缓存而丢弃的字符数,下次读取时告诉模型 */
60
57
  dropped: number;
61
58
  exitCode?: number | null;
59
+ /** 是被停掉的(kill_shell、shutdown),不是自己结束的 */
60
+ killed?: boolean;
62
61
  }
63
62
 
64
63
  export function shellTools(opts: ShellOptions): ShellTools {
@@ -67,20 +66,14 @@ export function shellTools(opts: ShellOptions): ShellTools {
67
66
  // 找不到 shell 时不提供这几个工具:否则模型每次调用都要用户先批准,执行时才失败,模型还会反复重试
68
67
  if (!found) {
69
68
  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";
70
- return { tools: [], unavailable: `${shell} was not found, so the bash tool is disabled; ${hint}`, shutdown() {} };
69
+ return { tools: [], unavailable: `${shell} was not found, so the bash tool is disabled; ${hint}`, shutdown() {}, list: () => [], kill: async () => false };
71
70
  }
72
71
  const executable = found;
73
72
  const env = shellEnv(executable);
74
73
  const background = new Map<string, Background>();
75
74
  let nextId = 1;
76
75
 
77
- const spawn = (command: string, cwd = opts.cwd) =>
78
- spawnProc([executable, "-c", command], {
79
- cwd,
80
- env,
81
- // 自成进程组,超时/中断时能连同子进程一起杀掉
82
- detached: process.platform !== "win32",
83
- });
76
+ const spawn = (command: string, cwd = opts.cwd) => launch(executable, env, command, cwd);
84
77
 
85
78
  async function startBackground(command: string): Promise<string> {
86
79
  const id = `bg${nextId++}`;
@@ -96,12 +89,20 @@ export function shellTools(opts: ShellOptions): ShellTools {
96
89
  void Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => {});
97
90
  void bg.proc.exited.then((code) => {
98
91
  bg.exitCode = code;
92
+ if (!bg.killed) opts.onExit?.({ id, command, exitCode: code });
99
93
  });
100
94
  background.set(id, bg);
101
95
  return id;
102
96
  }
103
97
 
104
98
  const status = (bg: Background) => (bg.exitCode === undefined ? "running" : `exited with code ${bg.exitCode}`);
99
+ /** 停掉一个还在运行的后台命令,等它退出 */
100
+ const stop = async (bg: Background) => {
101
+ if (bg.exitCode !== undefined) return;
102
+ bg.killed = true;
103
+ killTree(executable, env, bg.proc);
104
+ await bg.proc.exited;
105
+ };
105
106
 
106
107
  const bash: Tool = {
107
108
  name: "bash",
@@ -130,17 +131,22 @@ export function shellTools(opts: ShellOptions): ShellTools {
130
131
  const timeout = Math.min(Math.max(timeout_ms ?? DEFAULT_TIMEOUT_MS, 1000), MAX_TIMEOUT_MS);
131
132
  const proc = await spawn(command);
132
133
  let timedOut = false;
134
+ const killed = giveUp();
133
135
  const timer = setTimeout(() => {
134
136
  timedOut = true;
135
- killTree(executable, env, proc.pid);
137
+ killTree(executable, env, proc);
138
+ killed.start();
136
139
  }, timeout);
137
- const kill = () => killTree(executable, env, proc.pid);
140
+ const kill = () => {
141
+ killTree(executable, env, proc);
142
+ killed.start();
143
+ };
138
144
  signal.addEventListener("abort", kill, { once: true });
139
145
  try {
140
146
  const [stdout, stderr, code] = await Promise.all([
141
- collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text })),
142
- collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text })),
143
- proc.exited,
147
+ collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text }), true, killed.done),
148
+ collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text }), true, killed.done),
149
+ Promise.race([proc.exited, killed.done.then(() => null)]),
144
150
  ]);
145
151
  signal.throwIfAborted();
146
152
  const parts = [
@@ -206,10 +212,7 @@ export function shellTools(opts: ShellOptions): ShellTools {
206
212
  const { id } = input as { id: string };
207
213
  const bg = find(id);
208
214
  if (!bg) return unknown(id);
209
- if (bg.exitCode === undefined) {
210
- killTree(executable, env, bg.proc.pid);
211
- await bg.proc.exited;
212
- }
215
+ await stop(bg);
213
216
  return { content: `${id} stopped (${status(bg)})` };
214
217
  },
215
218
  };
@@ -221,7 +224,18 @@ export function shellTools(opts: ShellOptions): ShellTools {
221
224
  executable,
222
225
  run,
223
226
  shutdown() {
224
- for (const bg of background.values()) if (bg.exitCode === undefined) killTree(executable, env, bg.proc.pid);
227
+ for (const bg of background.values()) {
228
+ if (bg.exitCode !== undefined) continue;
229
+ bg.killed = true;
230
+ killTree(executable, env, bg.proc);
231
+ }
232
+ },
233
+ list: () => [...background.values()].map((bg) => ({ id: bg.id, command: bg.command, status: status(bg) })),
234
+ async kill(id) {
235
+ const bg = background.get(id);
236
+ if (!bg) return false;
237
+ await stop(bg);
238
+ return true;
225
239
  },
226
240
  };
227
241
  }
@@ -230,23 +244,34 @@ export function shellTools(opts: ShellOptions): ShellTools {
230
244
  * 执行一条命令并把输出收下来(不经过模型、不推进度);超时或中止时连同子进程一起杀掉。
231
245
  * 后台命令和别的插件(`shell@1`,例如 jade/checks)都用它
232
246
  */
233
- export async function capture(executable: string, env: NodeJS.ProcessEnv | undefined, command: string, opts: { cwd?: string; timeoutMs: number; signal?: AbortSignal }): Promise<RunResult> {
247
+ export async function capture(executable: string, env: NodeJS.ProcessEnv | undefined, command: string, opts: { cwd?: string; timeoutMs: number; signal?: AbortSignal; onOutput?: (text: string) => void }): Promise<RunResult> {
234
248
  opts.signal?.throwIfAborted();
235
- const proc = await spawnProc([executable, "-c", command], {
236
- cwd: opts.cwd,
237
- env,
238
- // 自成进程组,超时/中断时能连同子进程一起杀掉
239
- detached: process.platform !== "win32",
240
- });
249
+ const proc = await launch(executable, env, command, opts.cwd);
250
+ // 输出一到就推给调用方(用户自己执行的命令要边跑边看);它出错不影响命令
251
+ const onOutput = (text: string) => {
252
+ try {
253
+ opts.onOutput?.(text);
254
+ } catch {
255
+ // 调用方的错
256
+ }
257
+ };
241
258
  let timedOut = false;
242
- const kill = () => killTree(executable, env, proc.pid);
259
+ const killed = giveUp();
260
+ const kill = () => {
261
+ killTree(executable, env, proc);
262
+ killed.start();
263
+ };
243
264
  const timer = setTimeout(() => {
244
265
  timedOut = true;
245
266
  kill();
246
267
  }, opts.timeoutMs);
247
268
  opts.signal?.addEventListener("abort", kill, { once: true });
248
269
  try {
249
- const [stdout, stderr, code] = await Promise.all([collect(proc.stdout, () => {}), collect(proc.stderr, () => {}), proc.exited]);
270
+ const [stdout, stderr, code] = await Promise.all([
271
+ collect(proc.stdout, onOutput, true, killed.done),
272
+ collect(proc.stderr, onOutput, true, killed.done),
273
+ Promise.race([proc.exited, killed.done.then(() => null)]),
274
+ ]);
250
275
  opts.signal?.throwIfAborted();
251
276
  return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join("\n"), timedOut };
252
277
  } finally {
@@ -311,31 +336,69 @@ export function shellEnv(executable: string, env: NodeJS.ProcessEnv = process.en
311
336
  return { ...env, [key]: [...dirs, env[key]].filter(Boolean).join(path.delimiter) };
312
337
  }
313
338
 
339
+ /** 启动的命令和它的标记(killTree 用) */
340
+ type Tagged = Proc & { tag: string };
341
+
342
+ /** 标记用的环境变量:命令启动的进程都继承它,killTree 在 Windows 上靠它把它们找出来 */
343
+ const TAG = "JADE_SHELL_TAG";
344
+ let launched = 0;
345
+
346
+ /** 启动 shell 执行一条命令 */
347
+ async function launch(executable: string, env: NodeJS.ProcessEnv | undefined, command: string, cwd: string | undefined): Promise<Tagged> {
348
+ const tag = `${process.pid}-${Date.now().toString(36)}-${++launched}`;
349
+ const proc = await spawnProc([executable, "-c", command], {
350
+ cwd,
351
+ env: process.platform === "win32" ? { ...(env ?? process.env), [TAG]: tag } : env,
352
+ // 自成进程组,超时/中断时能连同子进程一起杀掉
353
+ detached: process.platform !== "win32",
354
+ });
355
+ return Object.assign(proc, { tag });
356
+ }
357
+
314
358
  /**
315
359
  * 只杀 shell 本身不够:它启动的子进程还占着 stdout/stderr 管道,读取会一直等到它们退出。
316
- * POSIX 上杀整个进程组。Windows 上 Git Bash(msys)模拟 fork,Windows 进程树里看不到父子关系,
317
- * 要先在 msys 里按 WINPID 找到 shell 的 msys PID(它也是进程组号)杀掉整组;taskkill /T 兜底非 msys 的 shell
360
+ * POSIX 上杀整个进程组。Windows 上 Git Bash(msys)模拟 fork,Windows 进程树里看不到父子关系;
361
+ * 按 WINPID 找也不行:msys 的 exec(bash -c "npm login" 直接换成 npm 那个脚本)会换一个 Windows 进程,
362
+ * 我们手里的 pid 只剩一个空壳。所以启动时在环境变量里放一个标记,这里在 msys 的 /proc 里把带标记的进程
363
+ * 找出来,连同它们的进程组(里面有 node 这类不是 msys 的子进程)一起杀掉
318
364
  */
319
- function killTree(shell: string, env: NodeJS.ProcessEnv | undefined, pid: number) {
365
+ function killTree(shell: string, env: NodeJS.ProcessEnv | undefined, proc: Tagged) {
320
366
  try {
321
- if (process.platform !== "win32") return process.kill(-pid, "SIGKILL");
322
- const script = `for d in /proc/[0-9]*; do [ "$(cat "$d/winpid" 2>/dev/null)" = "${pid}" ] && kill -9 -- "-\${d#/proc/}"; done`;
367
+ if (process.platform !== "win32") return process.kill(-proc.pid, "SIGKILL");
368
+ const script =
369
+ `for d in /proc/[0-9]*; do ` +
370
+ `if grep -qa "${TAG}=${proc.tag}" "$d/environ" 2>/dev/null || [ "$(cat "$d/winpid" 2>/dev/null)" = "${proc.pid}" ]; then ` +
371
+ `kill -9 -- "-$(cat "$d/pgid")" "\${d#/proc/}" 2>/dev/null; fi; done`;
372
+ // 先按 Windows 的进程树杀:cmd、node 这类不是 msys 的进程启动的子进程只有这里找得到,先杀掉它们的父进程就找不到了
373
+ runSync(["taskkill", "/T", "/F", "/PID", String(proc.pid)]);
323
374
  try {
375
+ // 用没有标记的环境变量跑,免得它把自己也算进去
324
376
  runSync([shell, "-c", script], { env });
325
377
  } catch {
326
378
  // 不是 msys/cygwin 的 shell
327
379
  }
328
- runSync(["taskkill", "/T", "/F", "/PID", String(pid)]);
329
380
  } catch {
330
381
  // 已经退出
331
382
  }
332
383
  }
333
384
 
385
+ /** 杀掉之后最多再等这么久就不等了:没杀干净的进程还占着输出管道时,读取永远等不到结束,这一轮(和整个界面)就卡在那里 */
386
+ const KILL_GRACE_MS = 2000;
387
+
388
+ /** start 之后过 KILL_GRACE_MS,done 就 resolve;不 start 永远不 resolve */
389
+ function giveUp(): { start(): void; done: Promise<void> } {
390
+ let start = () => {};
391
+ const done = new Promise<void>((resolve) => {
392
+ start = () => void setTimeout(resolve, KILL_GRACE_MS);
393
+ });
394
+ return { start, done };
395
+ }
396
+
334
397
  /**
335
398
  * 返回截好的输出:超过 MAX_OUTPUT_CHARS 时保留开头和结尾各一半,中间截掉。
336
399
  * 边读边截,输出再多也只占几倍 MAX_OUTPUT_CHARS 的内存。keep 为 false 时只推给 onChunk,不累积,返回空串
337
400
  */
338
- async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string) => void, keep = true): Promise<string> {
401
+ async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string) => void, keep = true, stop?: Promise<void>): Promise<string> {
339
402
  const half = MAX_OUTPUT_CHARS / 2;
340
403
  const decoder = new TextDecoder();
341
404
  let head = "";
@@ -354,8 +417,17 @@ async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string
354
417
  // 攒到两倍再截,不用每块都复制
355
418
  if (tail.length > 2 * half) tail = tail.slice(-half);
356
419
  };
357
- for await (const chunk of stream) {
358
- const text = decoder.decode(chunk, { stream: true });
420
+ // stop:不再等(进程杀掉之后管道还被别的进程占着),返回已经读到的
421
+ const it = stream[Symbol.asyncIterator]();
422
+ const stopped = stop?.then(() => undefined);
423
+ for (;;) {
424
+ const r = await (stopped ? Promise.race([it.next(), stopped]) : it.next());
425
+ if (!r) {
426
+ void Promise.resolve(it.return?.()).catch(() => {});
427
+ break;
428
+ }
429
+ if (r.done) break;
430
+ const text = decoder.decode(r.value, { stream: true });
359
431
  if (text) add(text);
360
432
  }
361
433
  const rest = decoder.decode();