@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
@@ -23,18 +23,13 @@ export function shellTools(opts) {
23
23
  // 找不到 shell 时不提供这几个工具:否则模型每次调用都要用户先批准,执行时才失败,模型还会反复重试
24
24
  if (!found) {
25
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() { } };
26
+ return { tools: [], unavailable: `${shell} was not found, so the bash tool is disabled; ${hint}`, shutdown() { }, list: () => [], kill: async () => false };
27
27
  }
28
28
  const executable = found;
29
29
  const env = shellEnv(executable);
30
30
  const background = new Map();
31
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",
37
- });
32
+ const spawn = (command, cwd = opts.cwd) => launch(executable, env, command, cwd);
38
33
  async function startBackground(command) {
39
34
  const id = `bg${nextId++}`;
40
35
  const bg = { id, command, proc: await spawn(command), unread: "", dropped: 0 };
@@ -49,11 +44,21 @@ export function shellTools(opts) {
49
44
  void Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => { });
50
45
  void bg.proc.exited.then((code) => {
51
46
  bg.exitCode = code;
47
+ if (!bg.killed)
48
+ opts.onExit?.({ id, command, exitCode: code });
52
49
  });
53
50
  background.set(id, bg);
54
51
  return id;
55
52
  }
56
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
+ };
57
62
  const bash = {
58
63
  name: "bash",
59
64
  description: `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` +
@@ -80,17 +85,22 @@ export function shellTools(opts) {
80
85
  const timeout = Math.min(Math.max(timeout_ms ?? DEFAULT_TIMEOUT_MS, 1000), MAX_TIMEOUT_MS);
81
86
  const proc = await spawn(command);
82
87
  let timedOut = false;
88
+ const killed = giveUp();
83
89
  const timer = setTimeout(() => {
84
90
  timedOut = true;
85
- killTree(executable, env, proc.pid);
91
+ killTree(executable, env, proc);
92
+ killed.start();
86
93
  }, timeout);
87
- const kill = () => killTree(executable, env, proc.pid);
94
+ const kill = () => {
95
+ killTree(executable, env, proc);
96
+ killed.start();
97
+ };
88
98
  signal.addEventListener("abort", kill, { once: true });
89
99
  try {
90
100
  const [stdout, stderr, code] = await Promise.all([
91
- collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text })),
92
- collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text })),
93
- proc.exited,
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)]),
94
104
  ]);
95
105
  signal.throwIfAborted();
96
106
  const parts = [
@@ -157,10 +167,7 @@ export function shellTools(opts) {
157
167
  const bg = find(id);
158
168
  if (!bg)
159
169
  return unknown(id);
160
- if (bg.exitCode === undefined) {
161
- killTree(executable, env, bg.proc.pid);
162
- await bg.proc.exited;
163
- }
170
+ await stop(bg);
164
171
  return { content: `${id} stopped (${status(bg)})` };
165
172
  },
166
173
  };
@@ -170,9 +177,20 @@ export function shellTools(opts) {
170
177
  executable,
171
178
  run,
172
179
  shutdown() {
173
- for (const bg of background.values())
174
- if (bg.exitCode === undefined)
175
- killTree(executable, env, bg.proc.pid);
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;
176
194
  },
177
195
  };
178
196
  }
@@ -182,21 +200,33 @@ export function shellTools(opts) {
182
200
  */
183
201
  export async function capture(executable, env, command, opts) {
184
202
  opts.signal?.throwIfAborted();
185
- const proc = await spawnProc([executable, "-c", command], {
186
- cwd: opts.cwd,
187
- env,
188
- // 自成进程组,超时/中断时能连同子进程一起杀掉
189
- detached: process.platform !== "win32",
190
- });
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
+ };
191
213
  let timedOut = false;
192
- const kill = () => killTree(executable, env, proc.pid);
214
+ const killed = giveUp();
215
+ const kill = () => {
216
+ killTree(executable, env, proc);
217
+ killed.start();
218
+ };
193
219
  const timer = setTimeout(() => {
194
220
  timedOut = true;
195
221
  kill();
196
222
  }, opts.timeoutMs);
197
223
  opts.signal?.addEventListener("abort", kill, { once: true });
198
224
  try {
199
- const [stdout, stderr, code] = await Promise.all([collect(proc.stdout, () => { }), collect(proc.stderr, () => { }), proc.exited]);
225
+ 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)]),
229
+ ]);
200
230
  opts.signal?.throwIfAborted();
201
231
  return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join("\n"), timedOut };
202
232
  }
@@ -259,33 +289,63 @@ export function shellEnv(executable, env = process.env) {
259
289
  const dirs = [path.join(root, "usr", "bin"), path.join(root, "mingw64", "bin")];
260
290
  return { ...env, [key]: [...dirs, env[key]].filter(Boolean).join(path.delimiter) };
261
291
  }
292
+ /** 标记用的环境变量:命令启动的进程都继承它,killTree 在 Windows 上靠它把它们找出来 */
293
+ const TAG = "JADE_SHELL_TAG";
294
+ let launched = 0;
295
+ /** 启动 shell 执行一条命令 */
296
+ 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 });
305
+ }
262
306
  /**
263
307
  * 只杀 shell 本身不够:它启动的子进程还占着 stdout/stderr 管道,读取会一直等到它们退出。
264
- * POSIX 上杀整个进程组。Windows 上 Git Bash(msys)模拟 fork,Windows 进程树里看不到父子关系,
265
- * 要先在 msys 里按 WINPID 找到 shell 的 msys PID(它也是进程组号)杀掉整组;taskkill /T 兜底非 msys 的 shell
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 的子进程)一起杀掉
266
312
  */
267
- function killTree(shell, env, pid) {
313
+ function killTree(shell, env, proc) {
268
314
  try {
269
315
  if (process.platform !== "win32")
270
- return process.kill(-pid, "SIGKILL");
271
- const script = `for d in /proc/[0-9]*; do [ "$(cat "$d/winpid" 2>/dev/null)" = "${pid}" ] && kill -9 -- "-\${d#/proc/}"; done`;
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)]);
272
322
  try {
323
+ // 用没有标记的环境变量跑,免得它把自己也算进去
273
324
  runSync([shell, "-c", script], { env });
274
325
  }
275
326
  catch {
276
327
  // 不是 msys/cygwin 的 shell
277
328
  }
278
- runSync(["taskkill", "/T", "/F", "/PID", String(pid)]);
279
329
  }
280
330
  catch {
281
331
  // 已经退出
282
332
  }
283
333
  }
334
+ /** 杀掉之后最多再等这么久就不等了:没杀干净的进程还占着输出管道时,读取永远等不到结束,这一轮(和整个界面)就卡在那里 */
335
+ const KILL_GRACE_MS = 2000;
336
+ /** start 之后过 KILL_GRACE_MS,done 就 resolve;不 start 永远不 resolve */
337
+ function giveUp() {
338
+ let start = () => { };
339
+ const done = new Promise((resolve) => {
340
+ start = () => void setTimeout(resolve, KILL_GRACE_MS);
341
+ });
342
+ return { start, done };
343
+ }
284
344
  /**
285
345
  * 返回截好的输出:超过 MAX_OUTPUT_CHARS 时保留开头和结尾各一半,中间截掉。
286
346
  * 边读边截,输出再多也只占几倍 MAX_OUTPUT_CHARS 的内存。keep 为 false 时只推给 onChunk,不累积,返回空串
287
347
  */
288
- async function collect(stream, onChunk, keep = true) {
348
+ async function collect(stream, onChunk, keep = true, stop) {
289
349
  const half = MAX_OUTPUT_CHARS / 2;
290
350
  const decoder = new TextDecoder();
291
351
  let head = "";
@@ -306,8 +366,18 @@ async function collect(stream, onChunk, keep = true) {
306
366
  if (tail.length > 2 * half)
307
367
  tail = tail.slice(-half);
308
368
  };
309
- for await (const chunk of stream) {
310
- const text = decoder.decode(chunk, { stream: true });
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 });
311
381
  if (text)
312
382
  add(text);
313
383
  }
@@ -1,16 +1,105 @@
1
- // jade/skills:skill 工具、系统提示词里的 skill 列表、/skills,以及每个 skill 一条 /<skill 名> 命令。
1
+ // jade/skills:skill 工具、系统提示词里的 skill 列表、/skills(列出,以及 add / update / remove,见 install.ts;
2
+ // 终端里是 jade skills …),以及每个 skill 一条 /<skill 名> 命令。
2
3
  //
3
- // 每个会话打开时重新查找 skill(/clear 之后能用上新装的)。随仓库分发的 skill(项目层)不用确认:
4
+ // 每次调用模型之前重新查找 skill:会话中途装的马上能用,不用 /clear 或重启。随仓库分发的 skill(项目层)不用确认:
4
5
  // 它只是给模型看的文字,不执行代码;和旧 jade 一样,列表里有项目层的 skill 时整段标为不可信。
5
6
  import path from "node:path";
6
- import { definePlugin } from "../../dist/api.js";
7
- import { bold, clip, dim, display, realPath, repoRoot } from "./project.js";
8
- import { loadSkills, skillsPrompt, skillTool } from "./skills.js";
7
+ import { definePlugin } from "@uncarved/jade-api";
8
+ import { addSkill, removeSkill, skillsRoot, updateSkills } from "./install.js";
9
+ import { bold, clip, dim, display, estimateTokens, realPath, red, repoRoot, splitArgs } from "./project.js";
10
+ import { loadSkills, skillLine, skillsPrompt, skillTool } from "./skills.js";
9
11
  const ID = "jade/skills";
10
12
  /** /<skill> 发给模型的消息:让它先加载这个 skill */
11
13
  export function skillMessage(name, args) {
12
14
  return `Use the "${name}" skill${args.trim() ? ` for this: ${args.trim()}` : "."}`;
13
15
  }
16
+ const errorText = (e) => (e instanceof Error ? e.message : String(e));
17
+ /** cmd 是 "/skills" 或 "jade skills" */
18
+ export const manageUsage = (cmd) => `usage: ${cmd} [list]
19
+ ${cmd} add <source> [--project] [--path <dir>] [--force]
20
+ ${cmd} update [name…] [--project] [--force]
21
+ ${cmd} remove <name> [--project]
22
+
23
+ <source> a git repository (https://…, git@…, github:user/repo, user/repo; #branch, #tag or #commit at the end),
24
+ an npm package, or a local directory
25
+ --project use <cwd>/.jade/skills instead of $JADE_HOME/skills
26
+ --path the skill's directory inside the source (for repositories with several skills)
27
+ --force replace a skill with the same name, or overwrite local changes on update`;
28
+ /** list / add / update / remove,参数已经切好;返回给用户看的结果,用法错误或失败时抛错。cmd 用在提示里 */
29
+ export async function manageSkills(argv, env) {
30
+ const usage = manageUsage(env.cmd);
31
+ const [sub, ...tail] = argv;
32
+ if (sub === "-h" || sub === "--help" || tail.includes("-h") || tail.includes("--help"))
33
+ return usage;
34
+ if (sub === undefined || sub === "list") {
35
+ if (tail.length)
36
+ throw new Error(usage);
37
+ const skills = env.skills ?? (await find(env.home, env.cwd)).skills;
38
+ // 每次请求都带着的:skill 工具的定义(总是注册),和提示词里的 skill 列表。skill 的正文用到时才读入,不算
39
+ const tool = skillTool(() => skills, async () => { }, { user: skillsRoot(env.home, env.cwd, false), project: skillsRoot(env.home, env.cwd, true) });
40
+ const toolTokens = estimateTokens(JSON.stringify({ name: tool.name, description: tool.description, input_schema: tool.inputSchema }));
41
+ if (skills.length === 0) {
42
+ return dim(`(no skills) install one with ${env.cmd} add <source>, or put it in ${display(env.cwd, path.join(env.home, "skills"))}/<name>/SKILL.md or .jade/skills/<name>/SKILL.md\nthe skill tool itself takes ≈${toolTokens} tokens in every request`);
43
+ }
44
+ const total = toolTokens + estimateTokens(skillsPrompt(skills));
45
+ return [
46
+ ...skills.map((sk) => `${bold(sk.name)} ${dim(`${sk.layer} · ${display(env.cwd, sk.dir)} · ≈${estimateTokens(skillLine(sk))} tokens`)}\n ${clip(sk.description.replace(/\s+/g, " "), 300)}`),
47
+ dim(`≈${total} tokens in every request (the skill list and the skill tool); a skill's instructions are read only when it is used`),
48
+ ].join("\n");
49
+ }
50
+ const positionals = [];
51
+ let project = false;
52
+ let force = false;
53
+ let subdir;
54
+ for (let i = 0; i < tail.length; i++) {
55
+ const a = tail[i];
56
+ if (a === "--project")
57
+ project = true;
58
+ else if (a === "--force" || a === "-f")
59
+ force = true;
60
+ else if (a === "--path") {
61
+ subdir = tail[++i];
62
+ if (subdir === undefined)
63
+ throw new Error(`--path needs a value\n${usage}`);
64
+ }
65
+ else if (a.startsWith("--path="))
66
+ subdir = a.slice("--path=".length);
67
+ else if (a.startsWith("-"))
68
+ throw new Error(`unknown option ${a}\n${usage}`);
69
+ else
70
+ positionals.push(a);
71
+ }
72
+ const root = skillsRoot(env.home, env.cwd, project);
73
+ const later = "a running jade can use it from its next step";
74
+ switch (sub) {
75
+ case "add":
76
+ case "install": {
77
+ if (positionals.length !== 1)
78
+ throw new Error(usage);
79
+ const { name, dir } = await addSkill(positionals[0], { sources: env.sources, root, cwd: env.cwd, force, ...(subdir ? { subdir } : {}), ...(env.log ? { log: env.log } : {}) });
80
+ return `installed skill ${name} into ${display(env.cwd, dir)}; ${later}`;
81
+ }
82
+ case "update": {
83
+ if (subdir)
84
+ throw new Error(usage);
85
+ const lines = await updateSkills(positionals, { sources: env.sources, root, cwd: env.cwd, force, ...(env.log ? { log: env.log } : {}) });
86
+ if (lines.length === 0)
87
+ return `no skills in ${display(env.cwd, root)} were installed with "${env.cmd} add"`;
88
+ if (lines.some((l) => l.startsWith("updated ")))
89
+ lines.push("a running jade uses the updated skills from its next step");
90
+ return lines.join("\n");
91
+ }
92
+ case "remove":
93
+ case "rm": {
94
+ if (positionals.length !== 1 || subdir || force)
95
+ throw new Error(usage);
96
+ const dir = await removeSkill(positionals[0], root);
97
+ return `removed skill ${positionals[0]} (${display(env.cwd, dir)})`;
98
+ }
99
+ default:
100
+ throw new Error(usage);
101
+ }
102
+ }
14
103
  async function find(home, cwd) {
15
104
  const here = realPath(cwd);
16
105
  return loadSkills({ home, root: realPath(repoRoot(here)), cwd: here });
@@ -23,50 +112,90 @@ const skillCommands = new Map();
23
112
  const warned = new Set();
24
113
  export default definePlugin({
25
114
  process(ctx) {
115
+ const sources = ctx.require("sources@1");
26
116
  latest = undefined;
27
117
  skillCommands.clear();
28
118
  ctx.service("commands@1")?.register({
29
119
  name: "skills",
30
- description: "skills the agent can use",
120
+ args: "[add <source> | update [name…] | remove <name>] [--project]",
121
+ description: "skills the agent can use; install them from git, npm or a directory",
31
122
  instant: true,
32
- async run() {
33
- const skills = latest ?? (await find(ctx.home, ctx.cwd)).skills;
34
- if (skills.length === 0) {
35
- return dim(`(no skills) put them in ${display(ctx.cwd, path.join(ctx.home, "skills"))}/<name>/SKILL.md or .jade/skills/<name>/SKILL.md`);
123
+ async run(args, cctx) {
124
+ let argv;
125
+ try {
126
+ argv = splitArgs(args);
127
+ }
128
+ catch (e) {
129
+ return red(errorText(e));
130
+ }
131
+ try {
132
+ return await manageSkills(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "/skills", sources, log: (t) => cctx.print(dim(t)), ...(latest ? { skills: latest } : {}) });
133
+ }
134
+ catch (e) {
135
+ return red(errorText(e));
36
136
  }
37
- return skills
38
- .map((sk) => `${bold(sk.name)} ${dim(`${sk.layer} · ${display(ctx.cwd, sk.dir)}`)}\n ${clip(sk.description.replace(/\s+/g, " "), 300)}`)
39
- .join("\n");
40
137
  },
41
138
  });
139
+ // 同样的事也能在终端里做:jade skills add <source> [--project](cli@1,核心提供)
140
+ ctx.service("cli@1")?.register({
141
+ name: "skills",
142
+ run: (argv, cli) => manageSkills(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "jade skills", sources, log: cli.log }),
143
+ });
42
144
  },
43
145
  async session(ctx) {
44
- const { skills, warnings } = await find(ctx.home, ctx.cwd);
45
- latest = skills;
46
146
  const ui = ctx.service("ui@1");
47
- for (const w of warnings) {
48
- if (warned.has(w))
49
- continue;
50
- warned.add(w);
51
- ui?.notify(`${ID}: ${w}`, "warning");
52
- }
53
- if (skills.length === 0)
54
- return;
55
- ctx.kernel.tool(skillTool(skills));
56
- const text = skillsPrompt(skills);
57
- // 读 skill 目录里的文件(脚本、参考资料)不用问;会话关闭时撤销
58
147
  const approval = ctx.service("approval@1");
59
- for (const sk of skills)
60
- approval?.allowRead(sk.dir);
61
- // 有随仓库分发的 skill 时整段不可信
62
- ctx.service("prompts@1")?.add({ text, untrusted: !skills.every((s) => s.layer === "user") });
63
- // skill 也可以当命令用:/<skill 名> [要做的事]。挂在会话作用域上,随会话撤销。
64
- // 新会话在旧会话关闭之前打开:旧会话注册的同名命令先撤销,换成这个会话的。
65
- // 名字已被别的插件的命令占用时让给它(会话级的注册总在进程级的命令之后)
148
+ const prompts = ctx.service("prompts@1");
66
149
  const commands = ctx.service("commands@1");
67
- if (commands) {
150
+ /** 这个会话现在的 skill,和据此加上的东西(都挂在会话作用域上,随会话撤销) */
151
+ let current = [];
152
+ let shown = "";
153
+ let removeSection;
154
+ const readable = new Map();
155
+ /** 这个会话注册过的 /<skill> 命令 */
156
+ const mine = new Set();
157
+ /** 用新找到的 skill 更新提示词里的列表、可读目录和 /<skill> 命令;没变时什么也不做(不让提示缓存失效) */
158
+ const apply = (skills, warnings) => {
159
+ for (const w of warnings) {
160
+ if (warned.has(w))
161
+ continue;
162
+ warned.add(w);
163
+ ui?.notify(`${ID}: ${w}`, "warning");
164
+ }
165
+ current = skills;
166
+ latest = skills;
167
+ const key = JSON.stringify(skills.map((s) => [s.name, s.description, s.dir, s.layer]));
168
+ if (key === shown)
169
+ return;
170
+ shown = key;
171
+ // 有随仓库分发的 skill 时整段不可信
172
+ removeSection?.();
173
+ removeSection = skills.length ? prompts?.add({ text: skillsPrompt(skills), untrusted: !skills.every((s) => s.layer === "user") }) : undefined;
174
+ // 读 skill 目录里的文件(脚本、参考资料)不用问
175
+ const dirs = new Set(skills.map((s) => s.dir));
176
+ for (const [dir, revoke] of readable)
177
+ if (!dirs.has(dir))
178
+ (revoke(), readable.delete(dir));
179
+ for (const dir of dirs)
180
+ if (!readable.has(dir) && approval)
181
+ readable.set(dir, approval.allowRead(dir));
182
+ // skill 也可以当命令用:/<skill 名> [要做的事]。
183
+ // 新会话在旧会话关闭之前打开:旧会话注册的同名命令先撤销,换成这个会话的。
184
+ // 名字已被别的插件的命令占用时让给它(会话级的注册总在进程级的命令之后)
185
+ if (!commands)
186
+ return;
187
+ const names = new Set(skills.map((s) => s.name.toLowerCase()));
188
+ for (const [key, revoke] of skillCommands) {
189
+ if (names.has(key))
190
+ continue;
191
+ revoke();
192
+ skillCommands.delete(key);
193
+ mine.delete(key);
194
+ }
68
195
  for (const sk of skills) {
69
196
  const key = sk.name.toLowerCase();
197
+ if (mine.has(key))
198
+ continue;
70
199
  const taken = commands.get(sk.name);
71
200
  if (taken && taken.plugin !== ID)
72
201
  continue;
@@ -80,11 +209,31 @@ export default definePlugin({
80
209
  run: (args) => ({ prompt: skillMessage(sk.name, args) }),
81
210
  });
82
211
  skillCommands.set(key, revoke);
212
+ mine.add(key);
83
213
  }
84
214
  catch {
85
215
  // 名字不能当命令名(commands@1 的规则更严)或刚被占用:只是少一条快捷命令
86
216
  }
87
217
  }
88
- }
218
+ };
219
+ const refresh = async () => {
220
+ const { skills, warnings } = await find(ctx.home, ctx.cwd);
221
+ apply(skills, warnings);
222
+ };
223
+ await refresh();
224
+ // 会话中途装的 skill(/skills add、jade skills add,或模型自己装的)马上能用:
225
+ // 工具列表在会话创建时就定了,所以 skill 工具总是注册;每次调用模型之前重新查找一次,
226
+ // 列表变了才更新提示词。context.project 在 context.build(jade/prompts 拼提示词)之前执行
227
+ ctx.kernel.tool(skillTool(() => current, refresh, { user: skillsRoot(ctx.home, ctx.cwd, false), project: skillsRoot(ctx.home, ctx.cwd, true) }));
228
+ ctx.kernel.hook({
229
+ kind: "transform",
230
+ point: "context.project",
231
+ // 查找出错时沿用上一次的列表,不让这一轮失败
232
+ optional: true,
233
+ fn: async (messages) => {
234
+ await refresh();
235
+ return messages;
236
+ },
237
+ });
89
238
  },
90
239
  });