@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
@@ -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
  });
@@ -0,0 +1,212 @@
1
+ // /skills add|update|remove:从 git 仓库、npm 包或本地目录安装 skill。
2
+ //
3
+ // 不加 --project 装到 $JADE_HOME/skills/<名字>,加了装到 <工作目录>/.jade/skills/<名字>。
4
+ // 来源的写法和下载经核心的 sources@1 服务(和 jade plugins add 同一份):先下到 skills 目录里的 .staging-*
5
+ // (以 . 开头,查找 skill 时跳过),找到 SKILL.md 后再换进正式目录。
6
+ // 安装记录在 skills 目录的 .installed.json(按名字),update 按它重新下载;记录里有安装时的内容哈希,
7
+ // 装好后手动改过的默认不覆盖,要加 --force。skill 只是文字和附带的文件:安装不执行任何东西,也不装依赖。
8
+
9
+ import { randomBytes } from "node:crypto";
10
+ import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
11
+ import path from "node:path";
12
+ import type { PluginSourceSpec, Sources } from "@uncarved/jade-api";
13
+ import { NAME, parseSkill } from "./skills.ts";
14
+
15
+ export interface SkillRecord {
16
+ name: string;
17
+ /** 用户写的来源 */
18
+ source: string;
19
+ /** 解析后的来源(git 地址、npm 写法或绝对路径);更新时直接用它 */
20
+ location: string;
21
+ kind: PluginSourceSpec["kind"];
22
+ ref?: string;
23
+ subdir?: string;
24
+ commit?: string;
25
+ /** 安装时 skill 目录的内容哈希 */
26
+ hash: string;
27
+ installedAt: string;
28
+ updatedAt?: string;
29
+ }
30
+
31
+ export interface InstallOptions {
32
+ /** 核心的 sources@1:识别来源、下载、算内容哈希 */
33
+ sources: Sources;
34
+ /** $JADE_HOME/skills 或 <工作目录>/.jade/skills */
35
+ root: string;
36
+ /** 解析相对路径用 */
37
+ cwd: string;
38
+ /** 只用来源里的这个子目录 */
39
+ subdir?: string;
40
+ /** 已有同名 skill,或装好后被手动改过时,照样替换 */
41
+ force?: boolean;
42
+ log?: (text: string) => void;
43
+ }
44
+
45
+ /** 不加 --project 装到 $JADE_HOME/skills,加了装到 <工作目录>/.jade/skills */
46
+ export const skillsRoot = (home: string, cwd: string, project: boolean) => (project ? path.join(cwd, ".jade", "skills") : path.join(home, "skills"));
47
+
48
+ const RECORDS = ".installed.json";
49
+
50
+ export async function readRecords(root: string): Promise<Record<string, SkillRecord>> {
51
+ let text: string;
52
+ try {
53
+ text = await readFile(path.join(root, RECORDS), "utf8");
54
+ } catch {
55
+ return {};
56
+ }
57
+ try {
58
+ return JSON.parse(text) as Record<string, SkillRecord>;
59
+ } catch (e) {
60
+ throw new Error(`${path.join(root, RECORDS)}: ${e instanceof Error ? e.message : String(e)}`);
61
+ }
62
+ }
63
+
64
+ async function writeRecords(root: string, records: Record<string, SkillRecord>): Promise<void> {
65
+ await writeFile(path.join(root, RECORDS), JSON.stringify(records, null, 2) + "\n");
66
+ }
67
+
68
+ const exists = (p: string) => stat(p).then(() => true, () => false);
69
+
70
+ /** 把 --path 限制在来源目录里,不能跑到外面去 */
71
+ function inSubdir(root: string, subdir: string): string {
72
+ const full = path.resolve(root, subdir);
73
+ const rel = path.relative(root, full);
74
+ if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) throw new Error(`--path ${subdir} points outside the source`);
75
+ return full;
76
+ }
77
+
78
+ /** 服务里抛出的错误带着 "plugin jade (sources@1.fetch): " 的前缀;给用户看的只要原来那句 */
79
+ async function plain<T>(call: Promise<T>): Promise<T> {
80
+ try {
81
+ return await call;
82
+ } catch (e) {
83
+ throw e instanceof Error && e.name === "PluginError" && e.cause instanceof Error ? e.cause : e;
84
+ }
85
+ }
86
+
87
+ /** 安装一个 skill,返回它的名字和目录 */
88
+ export async function addSkill(spec: string, opts: InstallOptions): Promise<{ name: string; dir: string }> {
89
+ const source = await plain(opts.sources.parse(spec, opts.cwd));
90
+ const record = await install(source, opts);
91
+ return { name: record.name, dir: path.join(path.resolve(opts.root), record.name) };
92
+ }
93
+
94
+ /** 按安装记录重新下载;没给名字时更新这个目录里所有装过的 skill。返回每个 skill 一行结果 */
95
+ export async function updateSkills(names: readonly string[], opts: Omit<InstallOptions, "subdir">): Promise<string[]> {
96
+ const root = path.resolve(opts.root);
97
+ const records = await readRecords(root);
98
+ const lines: string[] = [];
99
+ for (const name of names.length ? names : Object.keys(records).sort()) {
100
+ const rec = records[name];
101
+ if (!rec) {
102
+ lines.push(`${name}: not installed with "/skills add"${(await exists(path.join(root, name))) ? "; update it by hand" : ""}`);
103
+ continue;
104
+ }
105
+ try {
106
+ const dir = path.join(root, name);
107
+ if (!opts.force && (await exists(dir)) && (await opts.sources.hash(dir)) !== rec.hash) {
108
+ lines.push(`${name}: changed since it was installed; add --force to overwrite the changes`);
109
+ continue;
110
+ }
111
+ const source: PluginSourceSpec = { kind: rec.kind, location: rec.location, spec: rec.source, ...(rec.ref ? { ref: rec.ref } : {}) };
112
+ const next = await install(source, { ...opts, force: true, ...(rec.subdir ? { subdir: rec.subdir } : {}) }, rec);
113
+ lines.push(next.hash === rec.hash ? `current ${name}` : `updated ${name}`);
114
+ } catch (e) {
115
+ lines.push(`${name}: ${e instanceof Error ? e.message : String(e)}`);
116
+ }
117
+ }
118
+ return lines;
119
+ }
120
+
121
+ /** 删掉一个 skill 目录和它的安装记录;手动放进去的也能删 */
122
+ export async function removeSkill(name: string, root: string): Promise<string> {
123
+ if (!NAME.test(name)) throw new Error(`invalid skill name ${JSON.stringify(name)}`);
124
+ root = path.resolve(root);
125
+ const dir = path.join(root, name);
126
+ if (!(await exists(path.join(dir, "SKILL.md")))) throw new Error(`there is no skill ${name} in ${root}`);
127
+ await rm(dir, { recursive: true, force: true });
128
+ const records = await readRecords(root);
129
+ if (records[name]) {
130
+ delete records[name];
131
+ await writeRecords(root, records);
132
+ }
133
+ return dir;
134
+ }
135
+
136
+ /** 下载、找到 SKILL.md、换进正式目录、写安装记录。更新时 prev 给出原来的记录(名字不变) */
137
+ async function install(source: PluginSourceSpec, opts: InstallOptions, prev?: SkillRecord): Promise<SkillRecord> {
138
+ const root = path.resolve(opts.root);
139
+ // 本地来源包含 skills 目录时,staging 会被复制进去(甚至递归复制自己)
140
+ if (source.kind === "local") {
141
+ const from = opts.subdir ? inSubdir(source.location, opts.subdir) : source.location;
142
+ const rel = path.relative(from, root);
143
+ if (rel === "" || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) {
144
+ throw new Error(`${source.location} contains the skills directory; give the skill's own directory, or use --path`);
145
+ }
146
+ }
147
+ await mkdir(root, { recursive: true });
148
+ const records = await readRecords(root);
149
+ const staging = path.join(root, `.staging-${randomBytes(4).toString("hex")}`);
150
+ try {
151
+ const { root: fetched, commit } = await plain(opts.sources.fetch(source, staging, opts.log));
152
+ const dir = opts.subdir ? inSubdir(fetched, opts.subdir) : fetched;
153
+ if (!(await exists(path.join(dir, "SKILL.md")))) throw new Error(await noSkillMessage(source.spec, dir, fetched));
154
+ const name = prev?.name ?? skillName(parseSkill(await readFile(path.join(dir, "SKILL.md"), "utf8")).meta.name, source, opts.subdir);
155
+ const target = path.join(root, name);
156
+ if (!opts.force && (await exists(target))) {
157
+ throw new Error(`skill ${name} is already installed in ${target}; run "/skills update ${name}", or add --force to replace it`);
158
+ }
159
+ const hash = await opts.sources.hash(dir);
160
+ await rm(target, { recursive: true, force: true });
161
+ await rename(dir, target);
162
+ const now = new Date().toISOString();
163
+ const record: SkillRecord = {
164
+ name,
165
+ source: source.spec,
166
+ location: source.location,
167
+ kind: source.kind,
168
+ ...(source.ref ? { ref: source.ref } : {}),
169
+ ...(opts.subdir ? { subdir: opts.subdir } : {}),
170
+ ...(commit ? { commit } : {}),
171
+ hash,
172
+ installedAt: prev?.installedAt ?? now,
173
+ ...(prev ? { updatedAt: now } : {}),
174
+ };
175
+ records[name] = record;
176
+ await writeRecords(root, records);
177
+ return record;
178
+ } finally {
179
+ await rm(staging, { recursive: true, force: true }).catch(() => {});
180
+ }
181
+ }
182
+
183
+ /** SKILL.md 里的 name;没有时用 --path 的最后一段,再没有就用仓库名、包名或目录名 */
184
+ function skillName(declared: string | undefined, source: PluginSourceSpec, subdir?: string): string {
185
+ const fromSource =
186
+ source.kind === "npm"
187
+ ? source.location.replace(/^@[^/]+\//, "").replace(/@.*$/, "").replace(/\.(tgz|tar\.gz)$/i, "")
188
+ : source.location.replace(/[\\/]+$/, "").replace(/\.git$/, "");
189
+ const candidates = [declared, subdir && path.basename(subdir.replace(/[\\/]+$/, "")), path.basename(fromSource)];
190
+ const name = candidates.find((c) => c && NAME.test(c));
191
+ if (!name) throw new Error(`could not tell the skill's name; give it a "name:" in SKILL.md`);
192
+ return name;
193
+ }
194
+
195
+ /** 来源里没有 SKILL.md 时:列出它里面的 skill,提示用 --path 选一个 */
196
+ async function noSkillMessage(spec: string, dir: string, fetched: string): Promise<string> {
197
+ let found: string[] = [];
198
+ try {
199
+ found = (await readdir(fetched, { recursive: true, withFileTypes: true }))
200
+ .filter((e) => e.isFile() && e.name === "SKILL.md")
201
+ .map((e) => path.relative(fetched, e.parentPath).split(path.sep).join("/"))
202
+ .filter((d) => d && !d.split("/").some((seg) => seg === "node_modules" || seg.startsWith(".")))
203
+ .sort();
204
+ } catch {
205
+ // 没有可列的
206
+ }
207
+ const where = path.relative(fetched, dir).split(path.sep).join("/");
208
+ const head = `${spec}${where ? ` (--path ${where})` : ""} has no SKILL.md`;
209
+ if (found.length === 0) return `${head}; it is not a skill`;
210
+ const shown = found.slice(0, 20).map((d) => ` ${d}`).join("\n") + (found.length > 20 ? `\n … ${found.length - 20} more` : "");
211
+ return `${head}. It contains these skills; pick one with --path <dir>:\n${shown}`;
212
+ }
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "id": "jade/skills",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "api": "^1",
5
5
  "entry": "./index.ts",
6
- "optional": ["ui@1", "prompts@1", "commands@1", "approval@1"]
6
+ "requires": ["sources@1"],
7
+ "optional": ["ui@1", "prompts@1", "commands@1", "approval@1", "cli@1"]
7
8
  }
@@ -1,4 +1,4 @@
1
- // 仓库目录、显示用的小工具。插件之间不共享代码(只能共享类型),jade/mcp、jade/checks 各有一份。
1
+ // 仓库目录、显示用的小工具、斜杠命令参数的切分、token 估算。插件之间不共享代码(只能共享类型),jade/mcp、jade/checks 各有一份。
2
2
 
3
3
  import { existsSync, realpathSync } from "node:fs";
4
4
  import path from "node:path";
@@ -46,4 +46,41 @@ const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
46
46
  const paint = (open: string, close: string) => (s: string) =>
47
47
  colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
48
48
  export const dim = paint("2", "22");
49
+ export const red = paint("31", "39");
49
50
  export const bold = paint("1", "22");
51
+
52
+ /** 斜杠命令的参数按空白切开;"…" 或 '…' 里的空白不切(不处理反斜杠,Windows 路径照写) */
53
+ export function splitArgs(text: string): string[] {
54
+ const out: string[] = [];
55
+ let cur = "";
56
+ let started = false;
57
+ let quote: string | undefined;
58
+ for (const ch of text) {
59
+ if (quote) {
60
+ if (ch === quote) quote = undefined;
61
+ else cur += ch;
62
+ } else if (ch === '"' || ch === "'") {
63
+ quote = ch;
64
+ started = true;
65
+ } else if (/\s/.test(ch)) {
66
+ if (started) out.push(cur);
67
+ cur = "";
68
+ started = false;
69
+ } else {
70
+ cur += ch;
71
+ started = true;
72
+ }
73
+ }
74
+ if (quote) throw new Error(`unclosed ${quote}`);
75
+ if (started) out.push(cur);
76
+ return out;
77
+ }
78
+
79
+ /** 中日韩文字和全角符号:大约一个字一个 token(和 jade/compact 的估算一致) */
80
+ const WIDE = /[ -鿿가-힯豈-﫿＀-￯]/g;
81
+
82
+ /** 粗略估算一段文字发给模型时占多少 token:英文和代码约 4 个字符 1 个,中日韩文字每字约 1 个 */
83
+ export function estimateTokens(text: string): number {
84
+ const wide = text.match(WIDE)?.length ?? 0;
85
+ return Math.ceil((text.length - wide) / 4 + wide);
86
+ }
@@ -29,7 +29,7 @@ export interface Skill {
29
29
  overrides?: string;
30
30
  }
31
31
 
32
- const NAME = /^[a-z0-9][a-z0-9_-]*$/i;
32
+ export const NAME = /^[a-z0-9][a-z0-9_-]*$/i;
33
33
  /** 系统提示词里每个描述的上限 */
34
34
  const MAX_DESCRIPTION = 400;
35
35
  /** skill 工具列出的目录内文件数上限 */
@@ -120,6 +120,9 @@ export function parseSkill(text: string): { meta: Record<string, string>; body:
120
120
  return { meta, body: body.trim() };
121
121
  }
122
122
 
123
+ /** 系统提示词的 skill 列表里这个 skill 的一行(/skills 按它估算占用) */
124
+ export const skillLine = (s: Skill) => `- ${s.name}: ${s.description.replace(/\s+/g, " ")}`;
125
+
123
126
  /** 系统提示词里的 skill 列表;没有 skill 时为 undefined */
124
127
  export function skillsPrompt(skills: Skill[]): string | undefined {
125
128
  if (skills.length === 0) return undefined;
@@ -129,20 +132,29 @@ export function skillsPrompt(skills: Skill[]): string | undefined {
129
132
  "When a task matches a skill's description, call the skill tool with its name before starting, then follow the instructions it returns. " +
130
133
  "Files a skill refers to are relative to its directory, which the skill tool tells you.",
131
134
  "",
132
- ...skills.map((s) => `- ${s.name}: ${s.description.replace(/\s+/g, " ")}`),
135
+ ...skills.map(skillLine),
133
136
  ].join("\n");
134
137
  }
135
138
 
136
- /** skill 工具:读入某个 skill 的正文,以及它目录里的文件 */
137
- export function skillTool(skills: Skill[]): Tool {
138
- const byName = new Map(skills.map((s) => [s.name.toLowerCase(), s]));
139
+ /**
140
+ * skill 工具:读入某个 skill 的正文,以及它目录里的文件。
141
+ * 会话里的工具列表在会话创建时就定了,所以不管有没有 skill 都注册它,名字也不写成 enum:
142
+ * 会话中途装的 skill 用 current() 取最新的列表,找不到时先 refresh() 重新查找一次。
143
+ * 说明里告诉模型怎么装 skill(装到 install 给的目录),否则它会照别的工具的习惯放进 .claude/skills
144
+ */
145
+ export function skillTool(current: () => Skill[], refresh: () => Promise<void>, install: { user: string; project: string }): Tool {
146
+ const lookup = (name: string) => current().find((s) => s.name.toLowerCase() === name.toLowerCase());
139
147
  return {
140
148
  name: "skill",
141
149
  description:
142
- "Load the instructions of a skill listed in the system prompt. Call it when a task matches the skill's description, then follow the instructions.",
150
+ 'Load the instructions of a skill listed in the system prompt under "# Skills". Call it when a task matches the skill\'s description, then follow the instructions. ' +
151
+ "To install a new skill, run `jade skills add <source>` in the shell (<source>: a git repository such as user/repo or a URL, an npm package, or a local directory; " +
152
+ "add `--path <dir>` for one skill inside a repository with several). It installs into " +
153
+ `${install.user}; add \`--project\` to install into ${install.project} for this project only. ` +
154
+ "Do not copy skills into .claude/skills. A newly installed skill can be used right away.",
143
155
  inputSchema: {
144
156
  type: "object",
145
- properties: { name: { type: "string", enum: skills.map((s) => s.name), description: "the skill's name" } },
157
+ properties: { name: { type: "string", description: "the skill's name" } },
146
158
  required: ["name"],
147
159
  additionalProperties: false,
148
160
  },
@@ -151,8 +163,15 @@ export function skillTool(skills: Skill[]): Tool {
151
163
  idempotent: true,
152
164
  async execute(input) {
153
165
  const name = String((input as { name?: unknown }).name ?? "");
154
- const skill = byName.get(name.toLowerCase());
155
- if (!skill) return { content: `There is no skill named ${JSON.stringify(name)}. Available: ${skills.map((s) => s.name).join(", ")}.`, isError: true };
166
+ let skill = lookup(name);
167
+ if (!skill) {
168
+ await refresh();
169
+ skill = lookup(name);
170
+ }
171
+ if (!skill) {
172
+ const names = current().map((s) => s.name);
173
+ return { content: `There is no skill named ${JSON.stringify(name)}. ${names.length ? `Available: ${names.join(", ")}.` : "No skills are installed."}`, isError: true };
174
+ }
156
175
  let text: string;
157
176
  try {
158
177
  text = await readFile(path.join(skill.dir, "SKILL.md"), "utf8");