@uncarved/jade 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/README.md +277 -0
  2. package/assets/logo.svg +1 -0
  3. package/bin/jade.js +15 -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 +28 -5
  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 +6 -4
  29. package/plugins/approval/index.ts +246 -84
  30. package/plugins/approval/plugin.json +5 -1
  31. package/plugins/approval/policy.ts +27 -6
  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 +15 -4
  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 +110 -17
  48. package/plugins/fs/grep.ts +41 -11
  49. package/plugins/fs/index.ts +9 -7
  50. package/plugins/fs/renderers.ts +1 -1
  51. package/plugins/hooks/index.ts +152 -0
  52. package/plugins/hooks/plugin.json +14 -0
  53. package/plugins/keys/index.ts +2 -18
  54. package/plugins/mcp/index.ts +40 -12
  55. package/plugins/mcp/install.ts +139 -0
  56. package/plugins/mcp/mcp.ts +2 -1
  57. package/plugins/mcp/plugin.json +1 -1
  58. package/plugins/mcp/project.ts +37 -1
  59. package/plugins/memory/index.ts +4 -9
  60. package/plugins/memory/plugin.json +1 -1
  61. package/plugins/mentions/index.ts +33 -13
  62. package/plugins/models/configure.ts +258 -150
  63. package/plugins/models/context.ts +2 -2
  64. package/plugins/models/index.ts +50 -42
  65. package/plugins/models/plugin.json +1 -1
  66. package/plugins/models/provider.ts +22 -4
  67. package/plugins/models/saved.ts +8 -4
  68. package/plugins/modes/index.ts +2 -17
  69. package/plugins/plugins/index.ts +2 -2
  70. package/plugins/print/index.ts +60 -12
  71. package/plugins/print/plugin.json +1 -0
  72. package/plugins/prompts/index.ts +50 -14
  73. package/plugins/{memory → prompts}/notes.ts +21 -9
  74. package/plugins/prompts/plugin.json +8 -2
  75. package/plugins/prompts/prompts.ts +14 -8
  76. package/plugins/prompts/results.ts +63 -0
  77. package/plugins/prompts/sys.ts +16 -4
  78. package/plugins/renderers/index.ts +2 -43
  79. package/plugins/repeats/index.ts +1 -1
  80. package/plugins/schedule/index.ts +2 -2
  81. package/plugins/scratch/index.ts +2 -3
  82. package/plugins/screenshot/index.ts +26 -13
  83. package/plugins/screenshot/plugin.json +1 -1
  84. package/plugins/sessions/index.ts +2 -17
  85. package/plugins/shell/index.ts +56 -6
  86. package/plugins/shell/plugin.json +3 -1
  87. package/plugins/shell/renderers.ts +1 -1
  88. package/plugins/shell/service.ts +2 -13
  89. package/plugins/shell/shell.ts +31 -16
  90. package/plugins/skills/index.ts +172 -37
  91. package/plugins/skills/install.ts +212 -0
  92. package/plugins/skills/plugin.json +3 -2
  93. package/plugins/skills/project.ts +38 -1
  94. package/plugins/skills/skills.ts +28 -9
  95. package/plugins/steer/index.ts +142 -0
  96. package/plugins/steer/plugin.json +8 -0
  97. package/plugins/suggest/index.ts +16 -11
  98. package/plugins/suggest/plugin.json +1 -1
  99. package/plugins/task/index.ts +8 -16
  100. package/plugins/task/plugin.json +9 -2
  101. package/plugins/task/subagent.ts +119 -15
  102. package/plugins/todo/index.ts +4 -4
  103. package/plugins/tui/editor.ts +10 -2
  104. package/plugins/tui/frontend.ts +130 -25
  105. package/plugins/tui/index.ts +3 -8
  106. package/plugins/tui/markdown.ts +51 -6
  107. package/plugins/tui/mascot.ts +505 -0
  108. package/plugins/tui/mentions.ts +48 -8
  109. package/plugins/tui/plugin.json +2 -2
  110. package/plugins/tui/screen.ts +6 -0
  111. package/plugins/tui/transcript.ts +22 -3
  112. package/plugins/tui/tui.ts +323 -95
  113. package/plugins/tui/vendor.ts +16 -0
  114. package/plugins/undo/checkpoint.ts +26 -2
  115. package/plugins/undo/index.ts +86 -24
  116. package/plugins/undo/plugin.json +8 -2
  117. package/plugins/undo/snapshot.ts +129 -0
  118. package/plugins/update/index.ts +11 -15
  119. package/plugins/update/plugin.json +2 -1
  120. package/plugins/web/index.ts +2 -5
  121. package/plugins/web/renderers.ts +1 -1
  122. package/plugins/web/web.ts +6 -5
  123. package/plugins-dist/approval/index.js +232 -50
  124. package/plugins-dist/approval/plugin.json +5 -1
  125. package/plugins-dist/approval/policy.js +27 -5
  126. package/plugins-dist/ask/index.js +1 -1
  127. package/plugins-dist/budget/index.js +1 -1
  128. package/plugins-dist/checks/checks.js +2 -1
  129. package/plugins-dist/checks/index.js +1 -1
  130. package/plugins-dist/commands/index.js +1 -1
  131. package/plugins-dist/compact/compact.js +13 -2
  132. package/plugins-dist/compact/index.js +12 -8
  133. package/plugins-dist/continue/index.js +1 -1
  134. package/plugins-dist/cost/index.js +135 -0
  135. package/plugins-dist/cost/plugin.json +16 -0
  136. package/plugins-dist/custom-commands/index.js +86 -0
  137. package/plugins-dist/custom-commands/plugin.json +12 -0
  138. package/plugins-dist/editor/index.js +89 -0
  139. package/plugins-dist/editor/plugin.json +21 -0
  140. package/plugins-dist/fs/fs.js +106 -17
  141. package/plugins-dist/fs/grep.js +40 -12
  142. package/plugins-dist/fs/index.js +8 -5
  143. package/plugins-dist/hooks/index.js +145 -0
  144. package/plugins-dist/hooks/plugin.json +19 -0
  145. package/plugins-dist/keys/index.js +1 -1
  146. package/plugins-dist/mcp/index.js +41 -9
  147. package/plugins-dist/mcp/install.js +160 -0
  148. package/plugins-dist/mcp/mcp.js +2 -1
  149. package/plugins-dist/mcp/plugin.json +2 -1
  150. package/plugins-dist/mcp/project.js +42 -1
  151. package/plugins-dist/memory/index.js +3 -5
  152. package/plugins-dist/memory/plugin.json +1 -1
  153. package/plugins-dist/mentions/index.js +29 -11
  154. package/plugins-dist/models/configure.js +252 -151
  155. package/plugins-dist/models/context.js +2 -2
  156. package/plugins-dist/models/index.js +53 -16
  157. package/plugins-dist/models/plugin.json +1 -1
  158. package/plugins-dist/models/provider.js +4 -2
  159. package/plugins-dist/models/saved.js +9 -4
  160. package/plugins-dist/modes/index.js +1 -1
  161. package/plugins-dist/plugins/index.js +1 -1
  162. package/plugins-dist/print/index.js +62 -9
  163. package/plugins-dist/print/plugin.json +3 -0
  164. package/plugins-dist/prompts/index.js +49 -2
  165. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  166. package/plugins-dist/prompts/plugin.json +8 -2
  167. package/plugins-dist/prompts/prompts.js +13 -8
  168. package/plugins-dist/prompts/results.js +60 -0
  169. package/plugins-dist/prompts/sys.js +15 -3
  170. package/plugins-dist/renderers/index.js +1 -1
  171. package/plugins-dist/repeats/index.js +1 -1
  172. package/plugins-dist/schedule/index.js +1 -1
  173. package/plugins-dist/scratch/index.js +1 -1
  174. package/plugins-dist/screenshot/index.js +25 -11
  175. package/plugins-dist/screenshot/plugin.json +1 -1
  176. package/plugins-dist/sessions/index.js +1 -1
  177. package/plugins-dist/shell/index.js +55 -3
  178. package/plugins-dist/shell/plugin.json +3 -1
  179. package/plugins-dist/shell/shell.js +26 -8
  180. package/plugins-dist/skills/index.js +184 -35
  181. package/plugins-dist/skills/install.js +178 -0
  182. package/plugins-dist/skills/plugin.json +6 -2
  183. package/plugins-dist/skills/project.js +43 -1
  184. package/plugins-dist/skills/skills.js +27 -10
  185. package/plugins-dist/steer/index.js +135 -0
  186. package/plugins-dist/steer/plugin.json +12 -0
  187. package/plugins-dist/suggest/index.js +15 -9
  188. package/plugins-dist/suggest/plugin.json +1 -1
  189. package/plugins-dist/task/index.js +7 -4
  190. package/plugins-dist/task/plugin.json +10 -2
  191. package/plugins-dist/task/subagent.js +106 -15
  192. package/plugins-dist/todo/index.js +3 -3
  193. package/plugins-dist/tui/editor.js +7 -2
  194. package/plugins-dist/tui/frontend.js +135 -18
  195. package/plugins-dist/tui/index.js +2 -1
  196. package/plugins-dist/tui/markdown.js +48 -6
  197. package/plugins-dist/tui/mascot.js +439 -0
  198. package/plugins-dist/tui/mentions.js +44 -6
  199. package/plugins-dist/tui/plugin.json +3 -2
  200. package/plugins-dist/tui/screen.js +2 -0
  201. package/plugins-dist/tui/transcript.js +19 -2
  202. package/plugins-dist/tui/tui.js +303 -83
  203. package/plugins-dist/tui/vendor.js +13822 -0
  204. package/plugins-dist/undo/checkpoint.js +28 -1
  205. package/plugins-dist/undo/index.js +92 -22
  206. package/plugins-dist/undo/plugin.json +10 -3
  207. package/plugins-dist/undo/snapshot.js +111 -0
  208. package/plugins-dist/update/index.js +9 -10
  209. package/plugins-dist/update/plugin.json +4 -1
  210. package/plugins-dist/web/index.js +1 -1
  211. package/plugins-dist/web/web.js +6 -5
  212. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  213. package/sdk/python/jade_plugin.py +8 -0
  214. package/src/api.ts +7 -262
  215. package/src/fetch.ts +18 -16
  216. package/src/host.ts +49 -1
  217. package/src/index.ts +1 -1
  218. package/src/main.ts +25 -6
  219. package/src/remote.ts +2 -0
  220. package/src/session.ts +134 -15
  221. package/src/source.ts +2 -11
  222. package/src/update.ts +16 -10
  223. package/plugins/undo/notes.ts +0 -43
  224. package/plugins-dist/undo/notes.js +0 -36
@@ -31,11 +31,23 @@ export function spawn(cmd, opts = {}) {
31
31
  });
32
32
  });
33
33
  }
34
- /** 运行一条命令,返回 stdout 文本和退出码;启动失败时 reject */
34
+ /** 运行一条命令,返回 stdout 文本和退出码;启动失败时 reject。超过 timeoutMs 时杀掉,退出码为 null */
35
35
  export async function run(cmd, opts = {}) {
36
36
  const proc = await spawn(cmd, { cwd: opts.cwd, stderr: "ignore" });
37
- const [stdout, code] = await Promise.all([text(proc.stdout), proc.exited]);
38
- return { code, stdout };
37
+ let timedOut = false;
38
+ const timer = opts.timeoutMs === undefined
39
+ ? undefined
40
+ : setTimeout(() => {
41
+ timedOut = true;
42
+ proc.kill();
43
+ }, opts.timeoutMs);
44
+ try {
45
+ const [stdout, code] = await Promise.all([text(proc.stdout), proc.exited]);
46
+ return { code: timedOut ? null : code, stdout };
47
+ }
48
+ finally {
49
+ clearTimeout(timer);
50
+ }
39
51
  }
40
52
  export async function text(stream) {
41
53
  const decoder = new TextDecoder();
@@ -1,6 +1,6 @@
1
1
  // jade/renderers:工具调用和插件事件在对话里怎么显示的注册表。前端查这里;没有登记的用前端的默认显示。
2
2
  // 显示的文字可以带 ANSI 颜色,前端负责过滤掉颜色之外的控制序列。
3
- import { definePlugin } from "../../dist/api.js";
3
+ import { definePlugin } from "@uncarved/jade-api";
4
4
  const tools = new Map();
5
5
  const events = new Map();
6
6
  function add(map, key, renderer, plugin, what, onDispose) {
@@ -13,7 +13,7 @@
13
13
  // 从旧 jade 的 plugins/repeats.ts 移植。
14
14
  import { createHash } from "node:crypto";
15
15
  import path from "node:path";
16
- import { definePlugin } from "../../dist/api.js";
16
+ import { definePlugin } from "@uncarved/jade-api";
17
17
  const ID = "jade/repeats";
18
18
  /** jade/compact 记录压缩结果用的派生数据键(旧 jade 的约定):记一次就说明历史被压缩过 */
19
19
  export const COMPACT_KEY = "jade/compact";
@@ -3,7 +3,7 @@
3
3
  // 下次打开时错过的几次只补一次。不能提问的前端(jade -p)不投递。
4
4
  // 管理入口:/schedule 命令和给模型的 schedule_create、schedule_list、schedule_edit 工具,共用同一份存储。
5
5
  import path from "node:path";
6
- import { definePlugin } from "../../dist/api.js";
6
+ import { definePlugin } from "@uncarved/jade-api";
7
7
  import { parseCron } from "./cron.js";
8
8
  import { claimDue, nextAt, sameDir, ScheduleStore } from "./store.js";
9
9
  const ID = "jade/schedule";
@@ -4,7 +4,7 @@ import { realpathSync } from "node:fs";
4
4
  import { mkdir } from "node:fs/promises";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
- import { definePlugin } from "../../dist/api.js";
7
+ import { definePlugin } from "@uncarved/jade-api";
8
8
  /** 会话 id 对应的临时目录 */
9
9
  export const scratchDir = (session) => path.join(os.tmpdir(), "jade-scratch", session);
10
10
  export default definePlugin({
@@ -1,7 +1,7 @@
1
1
  // jade/screenshot:截图工具(见 tool.ts)。本机没有能无头截图的浏览器时不注册这个工具。
2
- // 模型能不能看图片由 jade/models 的 models@1 给出(JADE_VISION):不能看时不截图。
2
+ // 模型能不能看图片由 jade/models 的 models@1 给出(JADE_VISION):不能看时请求里没有这个工具和提示,调用了也不截图。
3
3
  // 访问网络的 URL 由 jade/approval 的关卡决定要不要问用户(effect 是 read,路径之外的 URL 会问)。
4
- import { definePlugin } from "../../dist/api.js";
4
+ import { definePlugin } from "@uncarved/jade-api";
5
5
  import { findBrowser, screenshotTool } from "./tool.js";
6
6
  /** 提示词里的一段:有截图工具时才加 */
7
7
  const NOTE = "- When the work is visual (a page, a drawing, styles), take a screenshot of the result and look at it instead of guessing from the source.";
@@ -19,17 +19,31 @@ export default definePlugin({
19
19
  if (!browser)
20
20
  return;
21
21
  const models = ctx.service("models@1");
22
- const tool = screenshotTool({
23
- cwd: ctx.cwd,
24
- browser,
25
- // 换了模型(/model)之后也按新的配置判断
26
- available: () => models?.current()?.vision !== false,
27
- });
22
+ // 换了模型(/model)之后也按新的配置判断
23
+ const available = () => models?.current()?.vision !== false;
24
+ const tool = screenshotTool({ cwd: ctx.cwd, browser, available });
28
25
  if (!tool)
29
26
  return;
30
27
  ctx.kernel.tool(tool);
31
- const remove = ctx.service("prompts@1")?.add({ text: NOTE, stable: false });
32
- if (remove)
33
- ctx.effect(() => () => remove());
28
+ // 不能看图片的模型不给这个工具,也不加那句提示:给了它多半会试一次,白费一轮。
29
+ // 排在 jade/prompts 的 context.build 之前(order -1),它组装系统提示词时读到的段落和工具已经是这一次的
30
+ const prompts = ctx.service("prompts@1");
31
+ let note;
32
+ ctx.effect(() => () => note?.());
33
+ ctx.kernel.hook({
34
+ kind: "transform",
35
+ point: "context.build",
36
+ order: -1,
37
+ fn: (req) => {
38
+ const can = available();
39
+ if (can && !note)
40
+ note = prompts?.add({ text: NOTE, stable: false });
41
+ else if (!can && note) {
42
+ note();
43
+ note = undefined;
44
+ }
45
+ return can ? req : { ...req, tools: req.tools.filter((t) => t.name !== tool.name) };
46
+ },
47
+ });
34
48
  },
35
49
  });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "jade/screenshot",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.js",
6
6
  "optional": [
@@ -3,7 +3,7 @@
3
3
  // 读的时候按 id 合并:标题取最早的一行,时间取最晚的一行;目录按 cwdKey 比较。
4
4
  import { appendFile, mkdir, readFile } from "node:fs/promises";
5
5
  import path from "node:path";
6
- import { definePlugin } from "../../dist/api.js";
6
+ import { definePlugin } from "@uncarved/jade-api";
7
7
  const TITLE_CHARS = 80;
8
8
  /** 比较目录用的键:绝对路径、去掉末尾的分隔符;Windows 上不分大小写 */
9
9
  export function cwdKey(cwd) {
@@ -1,8 +1,15 @@
1
1
  // jade/shell:bash 工具,以及后台命令的 bash_output、kill_shell;shell@1 给其他插件执行命令。
2
- import { definePlugin } from "../../dist/api.js";
2
+ // 后台命令自己结束时告诉用户,并给模型留一句说明(不用它一直轮询);/shells 给用户看和停掉后台命令。
3
+ import { definePlugin } from "@uncarved/jade-api";
3
4
  import { shellRenderers } from "./renderers.js";
4
5
  import { shellService } from "./service.js";
5
6
  import { shellTools } from "./shell.js";
7
+ /** 打开着的会话 → 它的后台命令(/shells 用) */
8
+ const sessions = new Map();
9
+ const firstLine = (command) => {
10
+ const line = command.split("\n")[0];
11
+ return line.length > 80 ? `${line.slice(0, 80)}…` : line;
12
+ };
6
13
  export default definePlugin({
7
14
  process(ctx) {
8
15
  // 显示方式和会话无关,登记一次留到进程结束;没有 renderers@1(例如 print)时用前端的默认显示
@@ -12,10 +19,52 @@ export default definePlugin({
12
19
  renderers.tool(r);
13
20
  // shell@1:找 shell 和杀进程树只有一份(见 service.ts)
14
21
  ctx.provide("shell@1", shellService(typeof ctx.config.shell === "string" ? { shell: ctx.config.shell } : {}));
22
+ ctx.service("commands@1")?.register({
23
+ name: "shells",
24
+ args: "[kill <id>]",
25
+ description: "list the background commands the agent started, or stop one",
26
+ instant: true,
27
+ async run(args, { sessions: manager }) {
28
+ const shells = manager.current && sessions.get(manager.current.id);
29
+ const [verb, id] = args.trim().split(/\s+/);
30
+ if (verb === "kill" && id)
31
+ return shells && (await shells.kill(id)) ? `Stopped ${id}.` : `There is no background command ${id}.`;
32
+ const all = shells?.list() ?? [];
33
+ if (all.length === 0)
34
+ return "No background commands.";
35
+ return all.map((b) => `${b.id} ${b.status} ${firstLine(b.command)}`).join("\n");
36
+ },
37
+ });
15
38
  },
16
39
  async session(ctx) {
17
40
  const shell = typeof ctx.config.shell === "string" ? ctx.config.shell : undefined;
18
- const { tools, executable, unavailable, shutdown } = shellTools({ cwd: ctx.cwd, ...(shell ? { shell } : {}) });
41
+ const id = ctx.session.id;
42
+ const { tools, executable, unavailable, shutdown, list, kill } = shellTools({
43
+ cwd: ctx.cwd,
44
+ ...(shell ? { shell } : {}),
45
+ onExit(bg) {
46
+ const what = `Background shell ${bg.id} (${firstLine(bg.command)}) exited with code ${bg.exitCode}`;
47
+ ctx.service("ui@1")?.notify(what, bg.exitCode === 0 ? "info" : "warning");
48
+ ctx.service("prompts@1")?.note(id, `${what}. Read its remaining output with bash_output.`);
49
+ },
50
+ });
51
+ sessions.set(id, { list, kill });
52
+ // 子 Agent(jade/task)的 bash:只收命令和时限,不能在后台跑;哪些命令能执行由 jade/task 按审批规则把关(只读的才行)
53
+ const bash = tools.find((t) => t.name === "bash");
54
+ try {
55
+ if (bash) {
56
+ ctx.service("task@1")?.tool({
57
+ ...bash,
58
+ description: "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. " +
59
+ "Commands that could change anything, or that touch paths outside the working directory, are refused.",
60
+ inputSchema: { type: "object", properties: { command: { type: "string" }, timeout_ms: { type: "integer" } }, required: ["command"], additionalProperties: false },
61
+ execute: (input, c) => bash.execute({ command: input.command, timeout_ms: input.timeout_ms }, c),
62
+ });
63
+ }
64
+ }
65
+ catch {
66
+ // jade/task 被隔离时它的服务已失效:子 Agent 没有 bash,主会话的照常
67
+ }
19
68
  if (unavailable)
20
69
  ctx.service("ui@1")?.notify(unavailable, "warning");
21
70
  for (const tool of tools)
@@ -28,6 +77,9 @@ export default definePlugin({
28
77
  ctx.service("prompts@1")?.add({ text: lines.join("\n") });
29
78
  }
30
79
  // 会话关闭(换会话、退出)时杀掉还在运行的后台命令
31
- await ctx.effect(() => shutdown);
80
+ await ctx.effect(() => () => {
81
+ sessions.delete(id);
82
+ shutdown();
83
+ });
32
84
  },
33
85
  });
@@ -9,7 +9,9 @@
9
9
  "optional": [
10
10
  "ui@1",
11
11
  "prompts@1",
12
- "renderers@1"
12
+ "renderers@1",
13
+ "commands@1",
14
+ "task@1"
13
15
  ],
14
16
  "config": {
15
17
  "shell": {
@@ -23,7 +23,7 @@ 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);
@@ -49,11 +49,21 @@ export function shellTools(opts) {
49
49
  void Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => { });
50
50
  void bg.proc.exited.then((code) => {
51
51
  bg.exitCode = code;
52
+ if (!bg.killed)
53
+ opts.onExit?.({ id, command, exitCode: code });
52
54
  });
53
55
  background.set(id, bg);
54
56
  return id;
55
57
  }
56
58
  const status = (bg) => (bg.exitCode === undefined ? "running" : `exited with code ${bg.exitCode}`);
59
+ /** 停掉一个还在运行的后台命令,等它退出 */
60
+ const stop = async (bg) => {
61
+ if (bg.exitCode !== undefined)
62
+ return;
63
+ bg.killed = true;
64
+ killTree(executable, env, bg.proc.pid);
65
+ await bg.proc.exited;
66
+ };
57
67
  const bash = {
58
68
  name: "bash",
59
69
  description: `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` +
@@ -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.pid);
185
+ }
186
+ },
187
+ list: () => [...background.values()].map((bg) => ({ id: bg.id, command: bg.command, status: status(bg) })),
188
+ async kill(id) {
189
+ const bg = background.get(id);
190
+ if (!bg)
191
+ return false;
192
+ await stop(bg);
193
+ return true;
176
194
  },
177
195
  };
178
196
  }
@@ -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
  });