@uncarved/jade 0.2.1 → 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 (213) hide show
  1. package/README.md +64 -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 +233 -85
  30. package/plugins/approval/plugin.json +1 -1
  31. package/plugins/approval/policy.ts +2 -1
  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 +6 -4
  49. package/plugins/fs/index.ts +2 -3
  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 +2 -2
  62. package/plugins/models/configure.ts +258 -150
  63. package/plugins/models/context.ts +2 -2
  64. package/plugins/models/index.ts +35 -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 +36 -6
  71. package/plugins/print/plugin.json +1 -0
  72. package/plugins/prompts/index.ts +22 -14
  73. package/plugins/{memory → prompts}/notes.ts +21 -9
  74. package/plugins/prompts/plugin.json +8 -2
  75. package/plugins/prompts/prompts.ts +5 -4
  76. package/plugins/renderers/index.ts +2 -43
  77. package/plugins/repeats/index.ts +1 -1
  78. package/plugins/schedule/index.ts +2 -2
  79. package/plugins/scratch/index.ts +2 -3
  80. package/plugins/screenshot/index.ts +26 -13
  81. package/plugins/screenshot/plugin.json +1 -1
  82. package/plugins/sessions/index.ts +2 -17
  83. package/plugins/shell/index.ts +56 -6
  84. package/plugins/shell/plugin.json +3 -1
  85. package/plugins/shell/renderers.ts +1 -1
  86. package/plugins/shell/service.ts +2 -13
  87. package/plugins/shell/shell.ts +31 -16
  88. package/plugins/skills/index.ts +172 -37
  89. package/plugins/skills/install.ts +212 -0
  90. package/plugins/skills/plugin.json +3 -2
  91. package/plugins/skills/project.ts +38 -1
  92. package/plugins/skills/skills.ts +28 -9
  93. package/plugins/steer/index.ts +142 -0
  94. package/plugins/steer/plugin.json +8 -0
  95. package/plugins/suggest/index.ts +16 -11
  96. package/plugins/suggest/plugin.json +1 -1
  97. package/plugins/task/index.ts +7 -16
  98. package/plugins/task/plugin.json +9 -2
  99. package/plugins/task/subagent.ts +23 -5
  100. package/plugins/todo/index.ts +2 -2
  101. package/plugins/tui/editor.ts +10 -2
  102. package/plugins/tui/frontend.ts +103 -21
  103. package/plugins/tui/index.ts +3 -8
  104. package/plugins/tui/markdown.ts +51 -6
  105. package/plugins/tui/mascot.ts +505 -0
  106. package/plugins/tui/plugin.json +2 -2
  107. package/plugins/tui/screen.ts +6 -0
  108. package/plugins/tui/transcript.ts +17 -2
  109. package/plugins/tui/tui.ts +321 -90
  110. package/plugins/undo/checkpoint.ts +2 -2
  111. package/plugins/undo/index.ts +84 -26
  112. package/plugins/undo/plugin.json +8 -2
  113. package/plugins/undo/snapshot.ts +129 -0
  114. package/plugins/update/index.ts +11 -15
  115. package/plugins/update/plugin.json +2 -1
  116. package/plugins/web/index.ts +2 -5
  117. package/plugins/web/renderers.ts +1 -1
  118. package/plugins-dist/approval/index.js +217 -51
  119. package/plugins-dist/approval/plugin.json +1 -1
  120. package/plugins-dist/ask/index.js +1 -1
  121. package/plugins-dist/budget/index.js +1 -1
  122. package/plugins-dist/checks/checks.js +2 -1
  123. package/plugins-dist/checks/index.js +1 -1
  124. package/plugins-dist/commands/index.js +1 -1
  125. package/plugins-dist/compact/compact.js +6 -1
  126. package/plugins-dist/compact/index.js +12 -8
  127. package/plugins-dist/continue/index.js +1 -1
  128. package/plugins-dist/cost/index.js +135 -0
  129. package/plugins-dist/cost/plugin.json +16 -0
  130. package/plugins-dist/custom-commands/index.js +86 -0
  131. package/plugins-dist/custom-commands/plugin.json +12 -0
  132. package/plugins-dist/editor/index.js +89 -0
  133. package/plugins-dist/editor/plugin.json +21 -0
  134. package/plugins-dist/fs/fs.js +34 -6
  135. package/plugins-dist/fs/grep.js +5 -3
  136. package/plugins-dist/fs/index.js +1 -1
  137. package/plugins-dist/hooks/index.js +145 -0
  138. package/plugins-dist/hooks/plugin.json +19 -0
  139. package/plugins-dist/keys/index.js +1 -1
  140. package/plugins-dist/mcp/index.js +41 -9
  141. package/plugins-dist/mcp/install.js +160 -0
  142. package/plugins-dist/mcp/mcp.js +2 -1
  143. package/plugins-dist/mcp/plugin.json +2 -1
  144. package/plugins-dist/mcp/project.js +42 -1
  145. package/plugins-dist/memory/index.js +3 -5
  146. package/plugins-dist/memory/plugin.json +1 -1
  147. package/plugins-dist/mentions/index.js +1 -1
  148. package/plugins-dist/models/configure.js +252 -151
  149. package/plugins-dist/models/context.js +2 -2
  150. package/plugins-dist/models/index.js +37 -14
  151. package/plugins-dist/models/plugin.json +1 -1
  152. package/plugins-dist/models/provider.js +4 -2
  153. package/plugins-dist/models/saved.js +9 -4
  154. package/plugins-dist/modes/index.js +1 -1
  155. package/plugins-dist/plugins/index.js +1 -1
  156. package/plugins-dist/print/index.js +37 -3
  157. package/plugins-dist/print/plugin.json +3 -0
  158. package/plugins-dist/prompts/index.js +22 -3
  159. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  160. package/plugins-dist/prompts/plugin.json +8 -2
  161. package/plugins-dist/prompts/prompts.js +5 -4
  162. package/plugins-dist/renderers/index.js +1 -1
  163. package/plugins-dist/repeats/index.js +1 -1
  164. package/plugins-dist/schedule/index.js +1 -1
  165. package/plugins-dist/scratch/index.js +1 -1
  166. package/plugins-dist/screenshot/index.js +25 -11
  167. package/plugins-dist/screenshot/plugin.json +1 -1
  168. package/plugins-dist/sessions/index.js +1 -1
  169. package/plugins-dist/shell/index.js +55 -3
  170. package/plugins-dist/shell/plugin.json +3 -1
  171. package/plugins-dist/shell/shell.js +26 -8
  172. package/plugins-dist/skills/index.js +184 -35
  173. package/plugins-dist/skills/install.js +178 -0
  174. package/plugins-dist/skills/plugin.json +6 -2
  175. package/plugins-dist/skills/project.js +43 -1
  176. package/plugins-dist/skills/skills.js +27 -10
  177. package/plugins-dist/steer/index.js +135 -0
  178. package/plugins-dist/steer/plugin.json +12 -0
  179. package/plugins-dist/suggest/index.js +15 -9
  180. package/plugins-dist/suggest/plugin.json +1 -1
  181. package/plugins-dist/task/index.js +6 -4
  182. package/plugins-dist/task/plugin.json +10 -2
  183. package/plugins-dist/task/subagent.js +20 -5
  184. package/plugins-dist/todo/index.js +1 -1
  185. package/plugins-dist/tui/editor.js +7 -2
  186. package/plugins-dist/tui/frontend.js +107 -13
  187. package/plugins-dist/tui/index.js +2 -1
  188. package/plugins-dist/tui/markdown.js +48 -6
  189. package/plugins-dist/tui/mascot.js +439 -0
  190. package/plugins-dist/tui/plugin.json +3 -2
  191. package/plugins-dist/tui/screen.js +2 -0
  192. package/plugins-dist/tui/transcript.js +16 -1
  193. package/plugins-dist/tui/tui.js +302 -81
  194. package/plugins-dist/undo/checkpoint.js +1 -1
  195. package/plugins-dist/undo/index.js +91 -24
  196. package/plugins-dist/undo/plugin.json +10 -3
  197. package/plugins-dist/undo/snapshot.js +111 -0
  198. package/plugins-dist/update/index.js +9 -10
  199. package/plugins-dist/update/plugin.json +4 -1
  200. package/plugins-dist/web/index.js +1 -1
  201. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  202. package/sdk/python/jade_plugin.py +8 -0
  203. package/src/api.ts +7 -262
  204. package/src/fetch.ts +18 -16
  205. package/src/host.ts +49 -1
  206. package/src/index.ts +1 -1
  207. package/src/main.ts +23 -5
  208. package/src/remote.ts +2 -0
  209. package/src/session.ts +134 -15
  210. package/src/source.ts +2 -11
  211. package/src/update.ts +16 -10
  212. package/plugins/undo/notes.ts +0 -43
  213. package/plugins-dist/undo/notes.js +0 -36
@@ -1,11 +1,9 @@
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
4
 
5
- import { definePlugin } from "../../src/api.ts";
6
- import type { Models } from "../models/index.ts";
7
- import type { Prompts } from "../prompts/index.ts";
8
- import type { Renderers } from "../renderers/index.ts";
5
+ import { definePlugin } from "@uncarved/jade-api";
6
+ import type { Models, Prompts, Renderers } from "@uncarved/jade-api/services";
9
7
  import { findBrowser, screenshotTool } from "./tool.ts";
10
8
 
11
9
  /** 提示词里的一段:有截图工具时才加 */
@@ -26,15 +24,30 @@ export default definePlugin({
26
24
  const browser = findBrowser(process.env);
27
25
  if (!browser) return;
28
26
  const models = ctx.service<Models>("models@1");
29
- const tool = screenshotTool({
30
- cwd: ctx.cwd,
31
- browser,
32
- // 换了模型(/model)之后也按新的配置判断
33
- available: () => models?.current()?.vision !== false,
34
- });
27
+ // 换了模型(/model)之后也按新的配置判断
28
+ const available = () => models?.current()?.vision !== false;
29
+ const tool = screenshotTool({ cwd: ctx.cwd, browser, available });
35
30
  if (!tool) return;
36
31
  ctx.kernel.tool(tool);
37
- const remove = ctx.service<Prompts>("prompts@1")?.add({ text: NOTE, stable: false });
38
- if (remove) ctx.effect(() => () => remove());
32
+
33
+ // 不能看图片的模型不给这个工具,也不加那句提示:给了它多半会试一次,白费一轮。
34
+ // 排在 jade/prompts 的 context.build 之前(order -1),它组装系统提示词时读到的段落和工具已经是这一次的
35
+ const prompts = ctx.service<Prompts>("prompts@1");
36
+ let note: (() => void) | undefined;
37
+ ctx.effect(() => () => note?.());
38
+ ctx.kernel.hook({
39
+ kind: "transform",
40
+ point: "context.build",
41
+ order: -1,
42
+ fn: (req) => {
43
+ const can = available();
44
+ if (can && !note) note = prompts?.add({ text: NOTE, stable: false });
45
+ else if (!can && note) {
46
+ note();
47
+ note = undefined;
48
+ }
49
+ return can ? req : { ...req, tools: req.tools.filter((t) => t.name !== tool.name) };
50
+ },
51
+ });
39
52
  },
40
53
  });
@@ -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.ts",
6
6
  "optional": ["renderers@1", "prompts@1", "models@1"]
@@ -5,17 +5,8 @@
5
5
  import { appendFile, mkdir, readFile } from "node:fs/promises";
6
6
  import path from "node:path";
7
7
  import type { UserInput } from "uncarved";
8
- import { definePlugin } from "../../src/api.ts";
9
- import type { Commands } from "../commands/index.ts";
10
-
11
- export interface SessionSummary {
12
- id: string;
13
- cwd: string;
14
- /** 第一条消息的开头 */
15
- title: string;
16
- /** 最近一次使用的时间(ISO) */
17
- at: string;
18
- }
8
+ import { definePlugin } from "@uncarved/jade-api";
9
+ import type { Commands, SessionIndex, SessionSummary } from "@uncarved/jade-api/services";
19
10
 
20
11
  const TITLE_CHARS = 80;
21
12
 
@@ -78,12 +69,6 @@ function titleOf(input: UserInput): string | undefined {
78
69
  return text.length > TITLE_CHARS ? `${text.slice(0, TITLE_CHARS)}…` : text;
79
70
  }
80
71
 
81
- /** sessions@1 */
82
- export interface SessionIndex {
83
- /** cwd 里的会话,最近用过的在前(jade --continue 取第一个) */
84
- list(cwd: string): Promise<SessionSummary[]>;
85
- }
86
-
87
72
  export default definePlugin({
88
73
  process(ctx) {
89
74
  const file = path.join(ctx.home, "state", "sessions.jsonl");
@@ -1,11 +1,18 @@
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, Task } 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
+ };
9
16
 
10
17
  export default definePlugin({
11
18
  process(ctx) {
@@ -14,11 +21,51 @@ export default definePlugin({
14
21
  if (renderers) for (const r of shellRenderers) renderers.tool(r);
15
22
  // shell@1:找 shell 和杀进程树只有一份(见 service.ts)
16
23
  ctx.provide("shell@1", shellService(typeof ctx.config.shell === "string" ? { shell: ctx.config.shell } : {}));
24
+ ctx.service<Commands>("commands@1")?.register({
25
+ name: "shells",
26
+ args: "[kill <id>]",
27
+ description: "list the background commands the agent started, or stop one",
28
+ instant: true,
29
+ async run(args, { sessions: manager }) {
30
+ const shells = manager.current && sessions.get(manager.current.id);
31
+ const [verb, id] = args.trim().split(/\s+/);
32
+ if (verb === "kill" && id) return shells && (await shells.kill(id)) ? `Stopped ${id}.` : `There is no background command ${id}.`;
33
+ const all = shells?.list() ?? [];
34
+ if (all.length === 0) return "No background commands.";
35
+ return all.map((b) => `${b.id} ${b.status} ${firstLine(b.command)}`).join("\n");
36
+ },
37
+ });
17
38
  },
18
39
 
19
40
  async session(ctx) {
20
41
  const shell = typeof ctx.config.shell === "string" ? ctx.config.shell : undefined;
21
- const { tools, executable, unavailable, shutdown } = shellTools({ cwd: ctx.cwd, ...(shell ? { shell } : {}) });
42
+ const id = ctx.session.id;
43
+ const { tools, executable, unavailable, shutdown, list, kill } = shellTools({
44
+ cwd: ctx.cwd,
45
+ ...(shell ? { shell } : {}),
46
+ onExit(bg) {
47
+ const what = `Background shell ${bg.id} (${firstLine(bg.command)}) exited with code ${bg.exitCode}`;
48
+ ctx.service<UI>("ui@1")?.notify(what, bg.exitCode === 0 ? "info" : "warning");
49
+ ctx.service<Prompts>("prompts@1")?.note(id, `${what}. Read its remaining output with bash_output.`);
50
+ },
51
+ });
52
+ sessions.set(id, { list, kill });
53
+ // 子 Agent(jade/task)的 bash:只收命令和时限,不能在后台跑;哪些命令能执行由 jade/task 按审批规则把关(只读的才行)
54
+ const bash = tools.find((t) => t.name === "bash");
55
+ try {
56
+ if (bash) {
57
+ ctx.service<Task>("task@1")?.tool({
58
+ ...bash,
59
+ description:
60
+ "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. " +
61
+ "Commands that could change anything, or that touch paths outside the working directory, are refused.",
62
+ inputSchema: { type: "object", properties: { command: { type: "string" }, timeout_ms: { type: "integer" } }, required: ["command"], additionalProperties: false },
63
+ execute: (input, c) => bash.execute({ command: (input as { command: string }).command, timeout_ms: (input as { timeout_ms?: number }).timeout_ms }, c),
64
+ });
65
+ }
66
+ } catch {
67
+ // jade/task 被隔离时它的服务已失效:子 Agent 没有 bash,主会话的照常
68
+ }
22
69
  if (unavailable) ctx.service<UI>("ui@1")?.notify(unavailable, "warning");
23
70
  for (const tool of tools) ctx.kernel.tool(tool);
24
71
  if (executable) {
@@ -28,6 +75,9 @@ export default definePlugin({
28
75
  ctx.service<Prompts>("prompts@1")?.add({ text: lines.join("\n") });
29
76
  }
30
77
  // 会话关闭(换会话、退出)时杀掉还在运行的后台命令
31
- await ctx.effect(() => shutdown);
78
+ await ctx.effect(() => () => {
79
+ sessions.delete(id);
80
+ shutdown();
81
+ });
32
82
  },
33
83
  });
@@ -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
+ "task@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);
@@ -59,6 +56,8 @@ interface Background {
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,7 +66,7 @@ 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);
@@ -96,12 +95,20 @@ export function shellTools(opts: ShellOptions): ShellTools {
96
95
  void Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => {});
97
96
  void bg.proc.exited.then((code) => {
98
97
  bg.exitCode = code;
98
+ if (!bg.killed) opts.onExit?.({ id, command, exitCode: code });
99
99
  });
100
100
  background.set(id, bg);
101
101
  return id;
102
102
  }
103
103
 
104
104
  const status = (bg: Background) => (bg.exitCode === undefined ? "running" : `exited with code ${bg.exitCode}`);
105
+ /** 停掉一个还在运行的后台命令,等它退出 */
106
+ const stop = async (bg: Background) => {
107
+ if (bg.exitCode !== undefined) return;
108
+ bg.killed = true;
109
+ killTree(executable, env, bg.proc.pid);
110
+ await bg.proc.exited;
111
+ };
105
112
 
106
113
  const bash: Tool = {
107
114
  name: "bash",
@@ -206,10 +213,7 @@ export function shellTools(opts: ShellOptions): ShellTools {
206
213
  const { id } = input as { id: string };
207
214
  const bg = find(id);
208
215
  if (!bg) return unknown(id);
209
- if (bg.exitCode === undefined) {
210
- killTree(executable, env, bg.proc.pid);
211
- await bg.proc.exited;
212
- }
216
+ await stop(bg);
213
217
  return { content: `${id} stopped (${status(bg)})` };
214
218
  },
215
219
  };
@@ -221,7 +225,18 @@ export function shellTools(opts: ShellOptions): ShellTools {
221
225
  executable,
222
226
  run,
223
227
  shutdown() {
224
- for (const bg of background.values()) if (bg.exitCode === undefined) killTree(executable, env, bg.proc.pid);
228
+ for (const bg of background.values()) {
229
+ if (bg.exitCode !== undefined) continue;
230
+ bg.killed = true;
231
+ killTree(executable, env, bg.proc.pid);
232
+ }
233
+ },
234
+ list: () => [...background.values()].map((bg) => ({ id: bg.id, command: bg.command, status: status(bg) })),
235
+ async kill(id) {
236
+ const bg = background.get(id);
237
+ if (!bg) return false;
238
+ await stop(bg);
239
+ return true;
225
240
  },
226
241
  };
227
242
  }
@@ -1,15 +1,15 @@
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
 
6
7
  import path from "node:path";
7
- import { definePlugin, type UI } from "../../src/api.ts";
8
- import type { Approval } from "../approval/index.ts";
9
- import type { Commands } from "../commands/index.ts";
10
- import type { Prompts } from "../prompts/index.ts";
11
- import { bold, clip, dim, display, realPath, repoRoot } from "./project.ts";
12
- import { loadSkills, skillsPrompt, skillTool, type Skill } from "./skills.ts";
8
+ import { definePlugin, type Cli, type Sources, type UI } from "@uncarved/jade-api";
9
+ import type { Approval, Commands, Prompts } from "@uncarved/jade-api/services";
10
+ import { addSkill, removeSkill, skillsRoot, updateSkills } from "./install.ts";
11
+ import { bold, clip, dim, display, estimateTokens, realPath, red, repoRoot, splitArgs } from "./project.ts";
12
+ import { loadSkills, skillLine, skillsPrompt, skillTool, type Skill } from "./skills.ts";
13
13
 
14
14
  const ID = "jade/skills";
15
15
 
@@ -18,6 +18,85 @@ export function skillMessage(name: string, args: string): string {
18
18
  return `Use the "${name}" skill${args.trim() ? ` for this: ${args.trim()}` : "."}`;
19
19
  }
20
20
 
21
+ const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
22
+
23
+ /** cmd 是 "/skills" 或 "jade skills" */
24
+ export const manageUsage = (cmd: string) => `usage: ${cmd} [list]
25
+ ${cmd} add <source> [--project] [--path <dir>] [--force]
26
+ ${cmd} update [name…] [--project] [--force]
27
+ ${cmd} remove <name> [--project]
28
+
29
+ <source> a git repository (https://…, git@…, github:user/repo, user/repo; #branch, #tag or #commit at the end),
30
+ an npm package, or a local directory
31
+ --project use <cwd>/.jade/skills instead of $JADE_HOME/skills
32
+ --path the skill's directory inside the source (for repositories with several skills)
33
+ --force replace a skill with the same name, or overwrite local changes on update`;
34
+
35
+ /** list / add / update / remove,参数已经切好;返回给用户看的结果,用法错误或失败时抛错。cmd 用在提示里 */
36
+ export async function manageSkills(
37
+ argv: readonly string[],
38
+ env: { home: string; cwd: string; cmd: string; sources: Sources; log?: (text: string) => void; skills?: Skill[] },
39
+ ): Promise<string> {
40
+ const usage = manageUsage(env.cmd);
41
+ const [sub, ...tail] = argv;
42
+ if (sub === "-h" || sub === "--help" || tail.includes("-h") || tail.includes("--help")) return usage;
43
+ if (sub === undefined || sub === "list") {
44
+ if (tail.length) throw new Error(usage);
45
+ const skills = env.skills ?? (await find(env.home, env.cwd)).skills;
46
+ // 每次请求都带着的:skill 工具的定义(总是注册),和提示词里的 skill 列表。skill 的正文用到时才读入,不算
47
+ const tool = skillTool(() => skills, async () => {}, { user: skillsRoot(env.home, env.cwd, false), project: skillsRoot(env.home, env.cwd, true) });
48
+ const toolTokens = estimateTokens(JSON.stringify({ name: tool.name, description: tool.description, input_schema: tool.inputSchema }));
49
+ if (skills.length === 0) {
50
+ 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`);
51
+ }
52
+ const total = toolTokens + estimateTokens(skillsPrompt(skills)!);
53
+ return [
54
+ ...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)}`),
55
+ dim(`≈${total} tokens in every request (the skill list and the skill tool); a skill's instructions are read only when it is used`),
56
+ ].join("\n");
57
+ }
58
+ const positionals: string[] = [];
59
+ let project = false;
60
+ let force = false;
61
+ let subdir: string | undefined;
62
+ for (let i = 0; i < tail.length; i++) {
63
+ const a = tail[i]!;
64
+ if (a === "--project") project = true;
65
+ else if (a === "--force" || a === "-f") force = true;
66
+ else if (a === "--path") {
67
+ subdir = tail[++i];
68
+ if (subdir === undefined) throw new Error(`--path needs a value\n${usage}`);
69
+ } else if (a.startsWith("--path=")) subdir = a.slice("--path=".length);
70
+ else if (a.startsWith("-")) throw new Error(`unknown option ${a}\n${usage}`);
71
+ else positionals.push(a);
72
+ }
73
+ const root = skillsRoot(env.home, env.cwd, project);
74
+ const later = "a running jade can use it from its next step";
75
+ switch (sub) {
76
+ case "add":
77
+ case "install": {
78
+ if (positionals.length !== 1) 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) throw new Error(usage);
84
+ const lines = await updateSkills(positionals, { sources: env.sources, root, cwd: env.cwd, force, ...(env.log ? { log: env.log } : {}) });
85
+ if (lines.length === 0) return `no skills in ${display(env.cwd, root)} were installed with "${env.cmd} add"`;
86
+ if (lines.some((l) => l.startsWith("updated "))) lines.push("a running jade uses the updated skills from its next step");
87
+ return lines.join("\n");
88
+ }
89
+ case "remove":
90
+ case "rm": {
91
+ if (positionals.length !== 1 || subdir || force) throw new Error(usage);
92
+ const dir = await removeSkill(positionals[0]!, root);
93
+ return `removed skill ${positionals[0]} (${display(env.cwd, dir)})`;
94
+ }
95
+ default:
96
+ throw new Error(usage);
97
+ }
98
+ }
99
+
21
100
  async function find(home: string, cwd: string) {
22
101
  const here = realPath(cwd);
23
102
  return loadSkills({ home, root: realPath(repoRoot(here)), cwd: here });
@@ -32,50 +111,85 @@ const warned = new Set<string>();
32
111
 
33
112
  export default definePlugin({
34
113
  process(ctx) {
114
+ const sources = ctx.require<Sources>("sources@1");
35
115
  latest = undefined;
36
116
  skillCommands.clear();
37
117
  ctx.service<Commands>("commands@1")?.register({
38
118
  name: "skills",
39
- description: "skills the agent can use",
119
+ args: "[add <source> | update [name…] | remove <name>] [--project]",
120
+ description: "skills the agent can use; install them from git, npm or a directory",
40
121
  instant: true,
41
- async run() {
42
- const skills = latest ?? (await find(ctx.home, ctx.cwd)).skills;
43
- if (skills.length === 0) {
44
- return dim(`(no skills) put them in ${display(ctx.cwd, path.join(ctx.home, "skills"))}/<name>/SKILL.md or .jade/skills/<name>/SKILL.md`);
122
+ async run(args, cctx) {
123
+ let argv: string[];
124
+ try {
125
+ argv = splitArgs(args);
126
+ } catch (e) {
127
+ return red(errorText(e));
128
+ }
129
+ try {
130
+ return await manageSkills(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "/skills", sources, log: (t) => cctx.print(dim(t)), ...(latest ? { skills: latest } : {}) });
131
+ } catch (e) {
132
+ return red(errorText(e));
45
133
  }
46
- return skills
47
- .map((sk) => `${bold(sk.name)} ${dim(`${sk.layer} · ${display(ctx.cwd, sk.dir)}`)}\n ${clip(sk.description.replace(/\s+/g, " "), 300)}`)
48
- .join("\n");
49
134
  },
50
135
  });
136
+ // 同样的事也能在终端里做:jade skills add <source> [--project](cli@1,核心提供)
137
+ ctx.service<Cli>("cli@1")?.register({
138
+ name: "skills",
139
+ run: (argv, cli) => manageSkills(argv, { home: ctx.home, cwd: ctx.cwd, cmd: "jade skills", sources, log: cli.log }),
140
+ });
51
141
  },
52
142
 
53
143
  async session(ctx) {
54
- const { skills, warnings } = await find(ctx.home, ctx.cwd);
55
- latest = skills;
56
144
  const ui = ctx.service<UI>("ui@1");
57
- for (const w of warnings) {
58
- if (warned.has(w)) continue;
59
- warned.add(w);
60
- ui?.notify(`${ID}: ${w}`, "warning");
61
- }
62
- if (skills.length === 0) return;
63
-
64
- ctx.kernel.tool(skillTool(skills));
65
- const text = skillsPrompt(skills)!;
66
- // 读 skill 目录里的文件(脚本、参考资料)不用问;会话关闭时撤销
67
145
  const approval = ctx.service<Approval>("approval@1");
68
- for (const sk of skills) approval?.allowRead(sk.dir);
69
- // 有随仓库分发的 skill 时整段不可信
70
- ctx.service<Prompts>("prompts@1")?.add({ text, untrusted: !skills.every((s) => s.layer === "user") });
71
-
72
- // skill 也可以当命令用:/<skill 名> [要做的事]。挂在会话作用域上,随会话撤销。
73
- // 新会话在旧会话关闭之前打开:旧会话注册的同名命令先撤销,换成这个会话的。
74
- // 名字已被别的插件的命令占用时让给它(会话级的注册总在进程级的命令之后)
146
+ const prompts = ctx.service<Prompts>("prompts@1");
75
147
  const commands = ctx.service<Commands>("commands@1");
76
- if (commands) {
148
+
149
+ /** 这个会话现在的 skill,和据此加上的东西(都挂在会话作用域上,随会话撤销) */
150
+ let current: Skill[] = [];
151
+ let shown = "";
152
+ let removeSection: (() => void) | undefined;
153
+ const readable = new Map<string, () => void>();
154
+ /** 这个会话注册过的 /<skill> 命令 */
155
+ const mine = new Set<string>();
156
+
157
+ /** 用新找到的 skill 更新提示词里的列表、可读目录和 /<skill> 命令;没变时什么也不做(不让提示缓存失效) */
158
+ const apply = (skills: Skill[], warnings: string[]) => {
159
+ for (const w of warnings) {
160
+ if (warned.has(w)) continue;
161
+ warned.add(w);
162
+ ui?.notify(`${ID}: ${w}`, "warning");
163
+ }
164
+ current = skills;
165
+ latest = skills;
166
+ const key = JSON.stringify(skills.map((s) => [s.name, s.description, s.dir, s.layer]));
167
+ if (key === shown) return;
168
+ shown = key;
169
+
170
+ // 有随仓库分发的 skill 时整段不可信
171
+ removeSection?.();
172
+ removeSection = skills.length ? prompts?.add({ text: skillsPrompt(skills)!, untrusted: !skills.every((s) => s.layer === "user") }) : undefined;
173
+
174
+ // 读 skill 目录里的文件(脚本、参考资料)不用问
175
+ const dirs = new Set(skills.map((s) => s.dir));
176
+ for (const [dir, revoke] of readable) if (!dirs.has(dir)) (revoke(), readable.delete(dir));
177
+ for (const dir of dirs) if (!readable.has(dir) && approval) readable.set(dir, approval.allowRead(dir));
178
+
179
+ // skill 也可以当命令用:/<skill 名> [要做的事]。
180
+ // 新会话在旧会话关闭之前打开:旧会话注册的同名命令先撤销,换成这个会话的。
181
+ // 名字已被别的插件的命令占用时让给它(会话级的注册总在进程级的命令之后)
182
+ if (!commands) return;
183
+ const names = new Set(skills.map((s) => s.name.toLowerCase()));
184
+ for (const [key, revoke] of skillCommands) {
185
+ if (names.has(key)) continue;
186
+ revoke();
187
+ skillCommands.delete(key);
188
+ mine.delete(key);
189
+ }
77
190
  for (const sk of skills) {
78
191
  const key = sk.name.toLowerCase();
192
+ if (mine.has(key)) continue;
79
193
  const taken = commands.get(sk.name);
80
194
  if (taken && taken.plugin !== ID) continue;
81
195
  if (taken) skillCommands.get(key)?.();
@@ -87,10 +201,31 @@ export default definePlugin({
87
201
  run: (args) => ({ prompt: skillMessage(sk.name, args) }),
88
202
  });
89
203
  skillCommands.set(key, revoke);
204
+ mine.add(key);
90
205
  } catch {
91
206
  // 名字不能当命令名(commands@1 的规则更严)或刚被占用:只是少一条快捷命令
92
207
  }
93
208
  }
94
- }
209
+ };
210
+ const refresh = async () => {
211
+ const { skills, warnings } = await find(ctx.home, ctx.cwd);
212
+ apply(skills, warnings);
213
+ };
214
+ await refresh();
215
+
216
+ // 会话中途装的 skill(/skills add、jade skills add,或模型自己装的)马上能用:
217
+ // 工具列表在会话创建时就定了,所以 skill 工具总是注册;每次调用模型之前重新查找一次,
218
+ // 列表变了才更新提示词。context.project 在 context.build(jade/prompts 拼提示词)之前执行
219
+ ctx.kernel.tool(skillTool(() => current, refresh, { user: skillsRoot(ctx.home, ctx.cwd, false), project: skillsRoot(ctx.home, ctx.cwd, true) }));
220
+ ctx.kernel.hook({
221
+ kind: "transform",
222
+ point: "context.project",
223
+ // 查找出错时沿用上一次的列表,不让这一轮失败
224
+ optional: true,
225
+ fn: async (messages) => {
226
+ await refresh();
227
+ return messages;
228
+ },
229
+ });
95
230
  },
96
231
  });