@uncarved/jade 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/README.md +65 -2
  2. package/assets/logo.svg +1 -0
  3. package/bin/jade.js +4 -0
  4. package/dist/api.d.ts +5 -250
  5. package/dist/api.js +5 -7
  6. package/dist/api.js.map +1 -1
  7. package/dist/fetch.d.ts +8 -0
  8. package/dist/fetch.js +19 -17
  9. package/dist/fetch.js.map +1 -1
  10. package/dist/host.d.ts +12 -1
  11. package/dist/host.js +49 -1
  12. package/dist/host.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/main.js +26 -4
  17. package/dist/main.js.map +1 -1
  18. package/dist/remote.js +4 -0
  19. package/dist/remote.js.map +1 -1
  20. package/dist/session.d.ts +2 -0
  21. package/dist/session.js +133 -13
  22. package/dist/session.js.map +1 -1
  23. package/dist/source.d.ts +2 -10
  24. package/dist/source.js.map +1 -1
  25. package/dist/update.d.ts +8 -20
  26. package/dist/update.js +12 -1
  27. package/dist/update.js.map +1 -1
  28. package/package.json +4 -2
  29. package/plugins/approval/index.ts +236 -85
  30. package/plugins/approval/plugin.json +1 -1
  31. package/plugins/approval/policy.ts +36 -17
  32. package/plugins/approval/review.ts +1 -1
  33. package/plugins/ask/index.ts +2 -2
  34. package/plugins/budget/index.ts +1 -1
  35. package/plugins/checks/checks.ts +3 -2
  36. package/plugins/checks/index.ts +2 -5
  37. package/plugins/commands/index.ts +2 -44
  38. package/plugins/compact/compact.ts +8 -3
  39. package/plugins/compact/index.ts +13 -16
  40. package/plugins/continue/index.ts +1 -1
  41. package/plugins/cost/index.ts +143 -0
  42. package/plugins/cost/plugin.json +13 -0
  43. package/plugins/custom-commands/index.ts +85 -0
  44. package/plugins/custom-commands/plugin.json +8 -0
  45. package/plugins/editor/index.ts +88 -0
  46. package/plugins/editor/plugin.json +17 -0
  47. package/plugins/fs/fs.ts +33 -6
  48. package/plugins/fs/grep.ts +19 -7
  49. package/plugins/fs/index.ts +6 -7
  50. package/plugins/fs/plugin.json +1 -1
  51. package/plugins/fs/renderers.ts +1 -1
  52. package/plugins/hooks/index.ts +152 -0
  53. package/plugins/hooks/plugin.json +14 -0
  54. package/plugins/keys/index.ts +2 -18
  55. package/plugins/mcp/index.ts +43 -15
  56. package/plugins/mcp/install.ts +139 -0
  57. package/plugins/mcp/mcp.ts +2 -1
  58. package/plugins/mcp/plugin.json +1 -1
  59. package/plugins/mcp/project.ts +37 -1
  60. package/plugins/memory/index.ts +4 -9
  61. package/plugins/memory/plugin.json +1 -1
  62. package/plugins/mentions/index.ts +2 -2
  63. package/plugins/models/configure.ts +258 -150
  64. package/plugins/models/context.ts +2 -2
  65. package/plugins/models/index.ts +39 -45
  66. package/plugins/models/plugin.json +1 -1
  67. package/plugins/models/provider.ts +34 -5
  68. package/plugins/models/saved.ts +8 -4
  69. package/plugins/modes/index.ts +2 -17
  70. package/plugins/plugins/index.ts +2 -2
  71. package/plugins/print/index.ts +36 -6
  72. package/plugins/print/plugin.json +1 -0
  73. package/plugins/prompts/index.ts +22 -14
  74. package/plugins/{memory → prompts}/notes.ts +21 -9
  75. package/plugins/prompts/plugin.json +8 -2
  76. package/plugins/prompts/prompts.ts +5 -4
  77. package/plugins/renderers/index.ts +2 -43
  78. package/plugins/repeats/index.ts +32 -2
  79. package/plugins/schedule/index.ts +2 -2
  80. package/plugins/scratch/index.ts +2 -3
  81. package/plugins/screenshot/browser.ts +221 -0
  82. package/plugins/screenshot/index.ts +29 -15
  83. package/plugins/screenshot/plugin.json +1 -1
  84. package/plugins/screenshot/tool.ts +27 -51
  85. package/plugins/sessions/index.ts +2 -17
  86. package/plugins/shell/index.ts +115 -7
  87. package/plugins/shell/plugin.json +3 -1
  88. package/plugins/shell/renderers.ts +1 -1
  89. package/plugins/shell/service.ts +2 -13
  90. package/plugins/shell/shell.ts +119 -47
  91. package/plugins/skills/index.ts +172 -37
  92. package/plugins/skills/install.ts +212 -0
  93. package/plugins/skills/plugin.json +3 -2
  94. package/plugins/skills/project.ts +38 -1
  95. package/plugins/skills/skills.ts +28 -9
  96. package/plugins/steer/index.ts +142 -0
  97. package/plugins/steer/plugin.json +8 -0
  98. package/plugins/suggest/index.ts +16 -11
  99. package/plugins/suggest/plugin.json +1 -1
  100. package/plugins/task/index.ts +18 -57
  101. package/plugins/task/plugin.json +9 -3
  102. package/plugins/task/subagent.ts +25 -7
  103. package/plugins/todo/index.ts +2 -2
  104. package/plugins/tools/index.ts +50 -0
  105. package/plugins/tools/plugin.json +7 -0
  106. package/plugins/tui/editor.ts +10 -2
  107. package/plugins/tui/frontend.ts +129 -23
  108. package/plugins/tui/index.ts +3 -8
  109. package/plugins/tui/markdown.ts +51 -6
  110. package/plugins/tui/mascot.ts +506 -0
  111. package/plugins/tui/plugin.json +2 -2
  112. package/plugins/tui/screen.ts +6 -0
  113. package/plugins/tui/transcript.ts +17 -2
  114. package/plugins/tui/tui.ts +344 -97
  115. package/plugins/undo/checkpoint.ts +2 -2
  116. package/plugins/undo/index.ts +84 -26
  117. package/plugins/undo/plugin.json +8 -2
  118. package/plugins/undo/snapshot.ts +129 -0
  119. package/plugins/update/index.ts +11 -15
  120. package/plugins/update/plugin.json +2 -1
  121. package/plugins/web/index.ts +8 -11
  122. package/plugins/web/plugin.json +1 -1
  123. package/plugins/web/renderers.ts +1 -1
  124. package/plugins-dist/approval/index.js +221 -51
  125. package/plugins-dist/approval/plugin.json +1 -1
  126. package/plugins-dist/approval/policy.js +30 -15
  127. package/plugins-dist/ask/index.js +1 -1
  128. package/plugins-dist/budget/index.js +1 -1
  129. package/plugins-dist/checks/checks.js +2 -1
  130. package/plugins-dist/checks/index.js +1 -1
  131. package/plugins-dist/commands/index.js +1 -1
  132. package/plugins-dist/compact/compact.js +6 -1
  133. package/plugins-dist/compact/index.js +12 -8
  134. package/plugins-dist/continue/index.js +1 -1
  135. package/plugins-dist/cost/index.js +135 -0
  136. package/plugins-dist/cost/plugin.json +16 -0
  137. package/plugins-dist/custom-commands/index.js +86 -0
  138. package/plugins-dist/custom-commands/plugin.json +12 -0
  139. package/plugins-dist/editor/index.js +89 -0
  140. package/plugins-dist/editor/plugin.json +21 -0
  141. package/plugins-dist/fs/fs.js +34 -6
  142. package/plugins-dist/fs/grep.js +17 -6
  143. package/plugins-dist/fs/index.js +6 -6
  144. package/plugins-dist/fs/plugin.json +1 -1
  145. package/plugins-dist/hooks/index.js +145 -0
  146. package/plugins-dist/hooks/plugin.json +19 -0
  147. package/plugins-dist/keys/index.js +1 -1
  148. package/plugins-dist/mcp/index.js +45 -13
  149. package/plugins-dist/mcp/install.js +160 -0
  150. package/plugins-dist/mcp/mcp.js +2 -1
  151. package/plugins-dist/mcp/plugin.json +2 -1
  152. package/plugins-dist/mcp/project.js +42 -1
  153. package/plugins-dist/memory/index.js +3 -5
  154. package/plugins-dist/memory/plugin.json +1 -1
  155. package/plugins-dist/mentions/index.js +1 -1
  156. package/plugins-dist/models/configure.js +252 -151
  157. package/plugins-dist/models/context.js +2 -2
  158. package/plugins-dist/models/index.js +41 -17
  159. package/plugins-dist/models/plugin.json +1 -1
  160. package/plugins-dist/models/provider.js +17 -3
  161. package/plugins-dist/models/saved.js +9 -4
  162. package/plugins-dist/modes/index.js +1 -1
  163. package/plugins-dist/plugins/index.js +1 -1
  164. package/plugins-dist/print/index.js +37 -3
  165. package/plugins-dist/print/plugin.json +3 -0
  166. package/plugins-dist/prompts/index.js +22 -3
  167. package/plugins-dist/{memory → prompts}/notes.js +10 -7
  168. package/plugins-dist/prompts/plugin.json +8 -2
  169. package/plugins-dist/prompts/prompts.js +5 -4
  170. package/plugins-dist/renderers/index.js +1 -1
  171. package/plugins-dist/repeats/index.js +28 -2
  172. package/plugins-dist/schedule/index.js +1 -1
  173. package/plugins-dist/scratch/index.js +1 -1
  174. package/plugins-dist/screenshot/browser.js +187 -0
  175. package/plugins-dist/screenshot/index.js +28 -13
  176. package/plugins-dist/screenshot/plugin.json +1 -1
  177. package/plugins-dist/screenshot/tool.js +27 -49
  178. package/plugins-dist/sessions/index.js +1 -1
  179. package/plugins-dist/shell/index.js +119 -4
  180. package/plugins-dist/shell/plugin.json +3 -1
  181. package/plugins-dist/shell/shell.js +106 -36
  182. package/plugins-dist/skills/index.js +184 -35
  183. package/plugins-dist/skills/install.js +178 -0
  184. package/plugins-dist/skills/plugin.json +6 -2
  185. package/plugins-dist/skills/project.js +43 -1
  186. package/plugins-dist/skills/skills.js +27 -10
  187. package/plugins-dist/steer/index.js +135 -0
  188. package/plugins-dist/steer/plugin.json +12 -0
  189. package/plugins-dist/suggest/index.js +15 -9
  190. package/plugins-dist/suggest/plugin.json +1 -1
  191. package/plugins-dist/task/index.js +17 -46
  192. package/plugins-dist/task/plugin.json +11 -5
  193. package/plugins-dist/task/subagent.js +21 -6
  194. package/plugins-dist/todo/index.js +1 -1
  195. package/plugins-dist/tools/index.js +49 -0
  196. package/plugins-dist/tools/plugin.json +9 -0
  197. package/plugins-dist/tui/editor.js +7 -2
  198. package/plugins-dist/tui/frontend.js +134 -15
  199. package/plugins-dist/tui/index.js +2 -1
  200. package/plugins-dist/tui/markdown.js +48 -6
  201. package/plugins-dist/tui/mascot.js +441 -0
  202. package/plugins-dist/tui/plugin.json +3 -2
  203. package/plugins-dist/tui/screen.js +2 -0
  204. package/plugins-dist/tui/transcript.js +16 -1
  205. package/plugins-dist/tui/tui.js +320 -88
  206. package/plugins-dist/tui/vendor.js +1388 -1088
  207. package/plugins-dist/undo/checkpoint.js +1 -1
  208. package/plugins-dist/undo/index.js +91 -24
  209. package/plugins-dist/undo/plugin.json +10 -3
  210. package/plugins-dist/undo/snapshot.js +111 -0
  211. package/plugins-dist/update/index.js +9 -10
  212. package/plugins-dist/update/plugin.json +4 -1
  213. package/plugins-dist/web/index.js +7 -7
  214. package/plugins-dist/web/plugin.json +1 -1
  215. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  216. package/sdk/python/jade_plugin.py +8 -0
  217. package/src/api.ts +7 -262
  218. package/src/fetch.ts +18 -16
  219. package/src/host.ts +49 -1
  220. package/src/index.ts +1 -1
  221. package/src/main.ts +23 -5
  222. package/src/remote.ts +2 -0
  223. package/src/session.ts +134 -15
  224. package/src/source.ts +2 -11
  225. package/src/update.ts +16 -10
  226. package/plugins/undo/notes.ts +0 -43
  227. package/plugins-dist/undo/notes.js +0 -36
@@ -0,0 +1,178 @@
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
+ import { randomBytes } from "node:crypto";
9
+ import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { NAME, parseSkill } from "./skills.js";
12
+ /** 不加 --project 装到 $JADE_HOME/skills,加了装到 <工作目录>/.jade/skills */
13
+ export const skillsRoot = (home, cwd, project) => (project ? path.join(cwd, ".jade", "skills") : path.join(home, "skills"));
14
+ const RECORDS = ".installed.json";
15
+ export async function readRecords(root) {
16
+ let text;
17
+ try {
18
+ text = await readFile(path.join(root, RECORDS), "utf8");
19
+ }
20
+ catch {
21
+ return {};
22
+ }
23
+ try {
24
+ return JSON.parse(text);
25
+ }
26
+ catch (e) {
27
+ throw new Error(`${path.join(root, RECORDS)}: ${e instanceof Error ? e.message : String(e)}`);
28
+ }
29
+ }
30
+ async function writeRecords(root, records) {
31
+ await writeFile(path.join(root, RECORDS), JSON.stringify(records, null, 2) + "\n");
32
+ }
33
+ const exists = (p) => stat(p).then(() => true, () => false);
34
+ /** 把 --path 限制在来源目录里,不能跑到外面去 */
35
+ function inSubdir(root, subdir) {
36
+ const full = path.resolve(root, subdir);
37
+ const rel = path.relative(root, full);
38
+ if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel))
39
+ throw new Error(`--path ${subdir} points outside the source`);
40
+ return full;
41
+ }
42
+ /** 服务里抛出的错误带着 "plugin jade (sources@1.fetch): " 的前缀;给用户看的只要原来那句 */
43
+ async function plain(call) {
44
+ try {
45
+ return await call;
46
+ }
47
+ catch (e) {
48
+ throw e instanceof Error && e.name === "PluginError" && e.cause instanceof Error ? e.cause : e;
49
+ }
50
+ }
51
+ /** 安装一个 skill,返回它的名字和目录 */
52
+ export async function addSkill(spec, opts) {
53
+ const source = await plain(opts.sources.parse(spec, opts.cwd));
54
+ const record = await install(source, opts);
55
+ return { name: record.name, dir: path.join(path.resolve(opts.root), record.name) };
56
+ }
57
+ /** 按安装记录重新下载;没给名字时更新这个目录里所有装过的 skill。返回每个 skill 一行结果 */
58
+ export async function updateSkills(names, opts) {
59
+ const root = path.resolve(opts.root);
60
+ const records = await readRecords(root);
61
+ const lines = [];
62
+ for (const name of names.length ? names : Object.keys(records).sort()) {
63
+ const rec = records[name];
64
+ if (!rec) {
65
+ lines.push(`${name}: not installed with "/skills add"${(await exists(path.join(root, name))) ? "; update it by hand" : ""}`);
66
+ continue;
67
+ }
68
+ try {
69
+ const dir = path.join(root, name);
70
+ if (!opts.force && (await exists(dir)) && (await opts.sources.hash(dir)) !== rec.hash) {
71
+ lines.push(`${name}: changed since it was installed; add --force to overwrite the changes`);
72
+ continue;
73
+ }
74
+ const source = { kind: rec.kind, location: rec.location, spec: rec.source, ...(rec.ref ? { ref: rec.ref } : {}) };
75
+ const next = await install(source, { ...opts, force: true, ...(rec.subdir ? { subdir: rec.subdir } : {}) }, rec);
76
+ lines.push(next.hash === rec.hash ? `current ${name}` : `updated ${name}`);
77
+ }
78
+ catch (e) {
79
+ lines.push(`${name}: ${e instanceof Error ? e.message : String(e)}`);
80
+ }
81
+ }
82
+ return lines;
83
+ }
84
+ /** 删掉一个 skill 目录和它的安装记录;手动放进去的也能删 */
85
+ export async function removeSkill(name, root) {
86
+ if (!NAME.test(name))
87
+ throw new Error(`invalid skill name ${JSON.stringify(name)}`);
88
+ root = path.resolve(root);
89
+ const dir = path.join(root, name);
90
+ if (!(await exists(path.join(dir, "SKILL.md"))))
91
+ throw new Error(`there is no skill ${name} in ${root}`);
92
+ await rm(dir, { recursive: true, force: true });
93
+ const records = await readRecords(root);
94
+ if (records[name]) {
95
+ delete records[name];
96
+ await writeRecords(root, records);
97
+ }
98
+ return dir;
99
+ }
100
+ /** 下载、找到 SKILL.md、换进正式目录、写安装记录。更新时 prev 给出原来的记录(名字不变) */
101
+ async function install(source, opts, prev) {
102
+ const root = path.resolve(opts.root);
103
+ // 本地来源包含 skills 目录时,staging 会被复制进去(甚至递归复制自己)
104
+ if (source.kind === "local") {
105
+ const from = opts.subdir ? inSubdir(source.location, opts.subdir) : source.location;
106
+ const rel = path.relative(from, root);
107
+ if (rel === "" || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) {
108
+ throw new Error(`${source.location} contains the skills directory; give the skill's own directory, or use --path`);
109
+ }
110
+ }
111
+ await mkdir(root, { recursive: true });
112
+ const records = await readRecords(root);
113
+ const staging = path.join(root, `.staging-${randomBytes(4).toString("hex")}`);
114
+ try {
115
+ const { root: fetched, commit } = await plain(opts.sources.fetch(source, staging, opts.log));
116
+ const dir = opts.subdir ? inSubdir(fetched, opts.subdir) : fetched;
117
+ if (!(await exists(path.join(dir, "SKILL.md"))))
118
+ throw new Error(await noSkillMessage(source.spec, dir, fetched));
119
+ const name = prev?.name ?? skillName(parseSkill(await readFile(path.join(dir, "SKILL.md"), "utf8")).meta.name, source, opts.subdir);
120
+ const target = path.join(root, name);
121
+ if (!opts.force && (await exists(target))) {
122
+ throw new Error(`skill ${name} is already installed in ${target}; run "/skills update ${name}", or add --force to replace it`);
123
+ }
124
+ const hash = await opts.sources.hash(dir);
125
+ await rm(target, { recursive: true, force: true });
126
+ await rename(dir, target);
127
+ const now = new Date().toISOString();
128
+ const record = {
129
+ name,
130
+ source: source.spec,
131
+ location: source.location,
132
+ kind: source.kind,
133
+ ...(source.ref ? { ref: source.ref } : {}),
134
+ ...(opts.subdir ? { subdir: opts.subdir } : {}),
135
+ ...(commit ? { commit } : {}),
136
+ hash,
137
+ installedAt: prev?.installedAt ?? now,
138
+ ...(prev ? { updatedAt: now } : {}),
139
+ };
140
+ records[name] = record;
141
+ await writeRecords(root, records);
142
+ return record;
143
+ }
144
+ finally {
145
+ await rm(staging, { recursive: true, force: true }).catch(() => { });
146
+ }
147
+ }
148
+ /** SKILL.md 里的 name;没有时用 --path 的最后一段,再没有就用仓库名、包名或目录名 */
149
+ function skillName(declared, source, subdir) {
150
+ const fromSource = source.kind === "npm"
151
+ ? source.location.replace(/^@[^/]+\//, "").replace(/@.*$/, "").replace(/\.(tgz|tar\.gz)$/i, "")
152
+ : source.location.replace(/[\\/]+$/, "").replace(/\.git$/, "");
153
+ const candidates = [declared, subdir && path.basename(subdir.replace(/[\\/]+$/, "")), path.basename(fromSource)];
154
+ const name = candidates.find((c) => c && NAME.test(c));
155
+ if (!name)
156
+ throw new Error(`could not tell the skill's name; give it a "name:" in SKILL.md`);
157
+ return name;
158
+ }
159
+ /** 来源里没有 SKILL.md 时:列出它里面的 skill,提示用 --path 选一个 */
160
+ async function noSkillMessage(spec, dir, fetched) {
161
+ let found = [];
162
+ try {
163
+ found = (await readdir(fetched, { recursive: true, withFileTypes: true }))
164
+ .filter((e) => e.isFile() && e.name === "SKILL.md")
165
+ .map((e) => path.relative(fetched, e.parentPath).split(path.sep).join("/"))
166
+ .filter((d) => d && !d.split("/").some((seg) => seg === "node_modules" || seg.startsWith(".")))
167
+ .sort();
168
+ }
169
+ catch {
170
+ // 没有可列的
171
+ }
172
+ const where = path.relative(fetched, dir).split(path.sep).join("/");
173
+ const head = `${spec}${where ? ` (--path ${where})` : ""} has no SKILL.md`;
174
+ if (found.length === 0)
175
+ return `${head}; it is not a skill`;
176
+ const shown = found.slice(0, 20).map((d) => ` ${d}`).join("\n") + (found.length > 20 ? `\n … ${found.length - 20} more` : "");
177
+ return `${head}. It contains these skills; pick one with --path <dir>:\n${shown}`;
178
+ }
@@ -1,12 +1,16 @@
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.js",
6
+ "requires": [
7
+ "sources@1"
8
+ ],
6
9
  "optional": [
7
10
  "ui@1",
8
11
  "prompts@1",
9
12
  "commands@1",
10
- "approval@1"
13
+ "approval@1",
14
+ "cli@1"
11
15
  ]
12
16
  }
@@ -1,4 +1,4 @@
1
- // 仓库目录、显示用的小工具。插件之间不共享代码(只能共享类型),jade/mcp、jade/checks 各有一份。
1
+ // 仓库目录、显示用的小工具、斜杠命令参数的切分、token 估算。插件之间不共享代码(只能共享类型),jade/mcp、jade/checks 各有一份。
2
2
  import { existsSync, realpathSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  export function realPath(p) {
@@ -44,4 +44,46 @@ export const clip = (s, n) => (s.length > n ? s.slice(0, n) + "…" : s);
44
44
  const colors = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
45
45
  const paint = (open, close) => (s) => colors ? `\x1b[${open}m${s.replaceAll(`\x1b[${close}m`, `\x1b[${close}m\x1b[${open}m`)}\x1b[${close}m` : s;
46
46
  export const dim = paint("2", "22");
47
+ export const red = paint("31", "39");
47
48
  export const bold = paint("1", "22");
49
+ /** 斜杠命令的参数按空白切开;"…" 或 '…' 里的空白不切(不处理反斜杠,Windows 路径照写) */
50
+ export function splitArgs(text) {
51
+ const out = [];
52
+ let cur = "";
53
+ let started = false;
54
+ let quote;
55
+ for (const ch of text) {
56
+ if (quote) {
57
+ if (ch === quote)
58
+ quote = undefined;
59
+ else
60
+ cur += ch;
61
+ }
62
+ else if (ch === '"' || ch === "'") {
63
+ quote = ch;
64
+ started = true;
65
+ }
66
+ else if (/\s/.test(ch)) {
67
+ if (started)
68
+ out.push(cur);
69
+ cur = "";
70
+ started = false;
71
+ }
72
+ else {
73
+ cur += ch;
74
+ started = true;
75
+ }
76
+ }
77
+ if (quote)
78
+ throw new Error(`unclosed ${quote}`);
79
+ if (started)
80
+ out.push(cur);
81
+ return out;
82
+ }
83
+ /** 中日韩文字和全角符号:大约一个字一个 token(和 jade/compact 的估算一致) */
84
+ const WIDE = /[ -鿿가-힯豈-﫿＀-￯]/g;
85
+ /** 粗略估算一段文字发给模型时占多少 token:英文和代码约 4 个字符 1 个,中日韩文字每字约 1 个 */
86
+ export function estimateTokens(text) {
87
+ const wide = text.match(WIDE)?.length ?? 0;
88
+ return Math.ceil((text.length - wide) / 4 + wide);
89
+ }
@@ -16,7 +16,7 @@ import { readdir, readFile, stat } from "node:fs/promises";
16
16
  import os from "node:os";
17
17
  import path from "node:path";
18
18
  import { projectDirs } from "./project.js";
19
- const NAME = /^[a-z0-9][a-z0-9_-]*$/i;
19
+ export const NAME = /^[a-z0-9][a-z0-9_-]*$/i;
20
20
  /** 系统提示词里每个描述的上限 */
21
21
  const MAX_DESCRIPTION = 400;
22
22
  /** skill 工具列出的目录内文件数上限 */
@@ -104,6 +104,8 @@ export function parseSkill(text) {
104
104
  }
105
105
  return { meta, body: body.trim() };
106
106
  }
107
+ /** 系统提示词的 skill 列表里这个 skill 的一行(/skills 按它估算占用) */
108
+ export const skillLine = (s) => `- ${s.name}: ${s.description.replace(/\s+/g, " ")}`;
107
109
  /** 系统提示词里的 skill 列表;没有 skill 时为 undefined */
108
110
  export function skillsPrompt(skills) {
109
111
  if (skills.length === 0)
@@ -114,18 +116,27 @@ export function skillsPrompt(skills) {
114
116
  "When a task matches a skill's description, call the skill tool with its name before starting, then follow the instructions it returns. " +
115
117
  "Files a skill refers to are relative to its directory, which the skill tool tells you.",
116
118
  "",
117
- ...skills.map((s) => `- ${s.name}: ${s.description.replace(/\s+/g, " ")}`),
119
+ ...skills.map(skillLine),
118
120
  ].join("\n");
119
121
  }
120
- /** skill 工具:读入某个 skill 的正文,以及它目录里的文件 */
121
- export function skillTool(skills) {
122
- const byName = new Map(skills.map((s) => [s.name.toLowerCase(), s]));
122
+ /**
123
+ * skill 工具:读入某个 skill 的正文,以及它目录里的文件。
124
+ * 会话里的工具列表在会话创建时就定了,所以不管有没有 skill 都注册它,名字也不写成 enum:
125
+ * 会话中途装的 skill 用 current() 取最新的列表,找不到时先 refresh() 重新查找一次。
126
+ * 说明里告诉模型怎么装 skill(装到 install 给的目录),否则它会照别的工具的习惯放进 .claude/skills
127
+ */
128
+ export function skillTool(current, refresh, install) {
129
+ const lookup = (name) => current().find((s) => s.name.toLowerCase() === name.toLowerCase());
123
130
  return {
124
131
  name: "skill",
125
- description: "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.",
132
+ description: '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. ' +
133
+ "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; " +
134
+ "add `--path <dir>` for one skill inside a repository with several). It installs into " +
135
+ `${install.user}; add \`--project\` to install into ${install.project} for this project only. ` +
136
+ "Do not copy skills into .claude/skills. A newly installed skill can be used right away.",
126
137
  inputSchema: {
127
138
  type: "object",
128
- properties: { name: { type: "string", enum: skills.map((s) => s.name), description: "the skill's name" } },
139
+ properties: { name: { type: "string", description: "the skill's name" } },
129
140
  required: ["name"],
130
141
  additionalProperties: false,
131
142
  },
@@ -134,9 +145,15 @@ export function skillTool(skills) {
134
145
  idempotent: true,
135
146
  async execute(input) {
136
147
  const name = String(input.name ?? "");
137
- const skill = byName.get(name.toLowerCase());
138
- if (!skill)
139
- return { content: `There is no skill named ${JSON.stringify(name)}. Available: ${skills.map((s) => s.name).join(", ")}.`, isError: true };
148
+ let skill = lookup(name);
149
+ if (!skill) {
150
+ await refresh();
151
+ skill = lookup(name);
152
+ }
153
+ if (!skill) {
154
+ const names = current().map((s) => s.name);
155
+ return { content: `There is no skill named ${JSON.stringify(name)}. ${names.length ? `Available: ${names.join(", ")}.` : "No skills are installed."}`, isError: true };
156
+ }
140
157
  let text;
141
158
  try {
142
159
  text = await readFile(path.join(skill.dir, "SKILL.md"), "utf8");
@@ -0,0 +1,135 @@
1
+ // jade/steer:在一轮的中途对模型说话。内核只在空闲时接受用户消息(一轮没完时不能再发一条),
2
+ // 所以不走输入:前端经 steer@1 把话交过来,下一次请求模型时在 context.project 里附在最后一条消息
3
+ // (这时是刚执行完的工具的结果)后面,并写进日志(derived),之后的投影、恢复的会话里它都在同一个位置。
4
+ // 和 prompts@1 的 note 是同一个办法,区别是这里是用户自己说的话,所以项目层插件不能用。
5
+ //
6
+ // 这一轮没有再请求模型就结束了的(模型正在写最后一条回复时说的),话还留在这里:前端在一轮结束后用 take 取回,
7
+ // 当作普通消息发出去。
8
+ import { definePlugin } from "@uncarved/jade-api";
9
+ const ID = "jade/steer";
10
+ /** derived 里:消息的下标 → 附在它后面的话 */
11
+ const KEY = `${ID}/said`;
12
+ /** 附在用户的话前面,告诉模型这是中途说的 */
13
+ export const MARKER = "[The user sent the following while you were working. Take it into account from here on.]";
14
+ /** 打开着的会话。模块每个进程只加载一次,进程级和会话级共用 */
15
+ const sessions = new Map();
16
+ const watchers = new Set();
17
+ function changed() {
18
+ for (const fn of [...watchers]) {
19
+ try {
20
+ fn();
21
+ }
22
+ catch {
23
+ // 订阅者的错不连累这里
24
+ }
25
+ }
26
+ }
27
+ const bold = (s) => `\x1b[1m${s}\x1b[22m`;
28
+ const dim = (s) => `\x1b[2m${s}\x1b[22m`;
29
+ export default definePlugin({
30
+ process(ctx) {
31
+ ctx.provide("steer@1", (caller) => {
32
+ const user = (method) => {
33
+ if (caller.layer === "project")
34
+ throw new Error(`steer.${method}: project plugins cannot speak for the user`);
35
+ };
36
+ return {
37
+ push(session, text) {
38
+ user("push");
39
+ if (typeof text !== "string" || !text.trim())
40
+ throw new Error("steer.push: text must be a non-empty string");
41
+ const s = sessions.get(session);
42
+ if (!s?.running())
43
+ return false;
44
+ s.pending.push(text);
45
+ changed();
46
+ return true;
47
+ },
48
+ pending: (session) => [...(sessions.get(session)?.pending ?? [])],
49
+ take(session) {
50
+ user("take");
51
+ const taken = sessions.get(session)?.pending.splice(0) ?? [];
52
+ if (taken.length > 0)
53
+ changed();
54
+ return taken;
55
+ },
56
+ subscribe(fn) {
57
+ if (typeof fn !== "function")
58
+ throw new Error("steer.subscribe: fn must be a function");
59
+ watchers.add(fn);
60
+ const off = () => void watchers.delete(fn);
61
+ caller.onDispose(off);
62
+ return off;
63
+ },
64
+ };
65
+ });
66
+ // 交给模型的那一刻在对话里显示出来,和用户发的消息一个样子;恢复的会话重新显示时也在原来的位置
67
+ ctx.service("renderers@1")?.event({
68
+ event: "said",
69
+ render(data) {
70
+ const text = data?.text;
71
+ if (typeof text !== "string")
72
+ return undefined;
73
+ return { line: `\n${bold(`› ${text.replace(/\n/g, "\n ")}`)} ${dim("(sent while working)")}` };
74
+ },
75
+ });
76
+ },
77
+ async session(ctx) {
78
+ const id = ctx.session.id;
79
+ const entry = {
80
+ pending: [],
81
+ running() {
82
+ try {
83
+ const phase = ctx.session.state().phase;
84
+ return phase !== "new" && phase !== "idle" && phase !== "ended";
85
+ }
86
+ catch {
87
+ // 会话还没建好,或者已经关了
88
+ return false;
89
+ }
90
+ },
91
+ };
92
+ sessions.set(id, entry);
93
+ await ctx.effect(() => () => {
94
+ if (sessions.get(id) === entry)
95
+ sessions.delete(id);
96
+ if (entry.pending.length > 0)
97
+ changed();
98
+ });
99
+ ctx.kernel.hook({
100
+ kind: "transform",
101
+ point: "context.project",
102
+ // 排在压缩之类改动消息列表的 hook 前面:下标按日志里的消息算
103
+ order: -39,
104
+ fn: async (messages, hook) => {
105
+ let said = hook.derived[KEY] ?? {};
106
+ if (entry.pending.length > 0 && messages.at(-1)?.role === "user") {
107
+ const texts = entry.pending.splice(0);
108
+ const at = String(messages.length - 1);
109
+ said = { ...said, [at]: [...(said[at] ?? []), ...texts] };
110
+ try {
111
+ // 先落盘再用(I-5);事件给前端显示
112
+ await hook.record(KEY, said);
113
+ for (const text of texts)
114
+ await hook.emit("said", { text });
115
+ }
116
+ catch (e) {
117
+ entry.pending.unshift(...texts);
118
+ throw e;
119
+ }
120
+ changed();
121
+ }
122
+ return messages.map((m, i) => {
123
+ const texts = said[i];
124
+ if (!texts?.length || m.role !== "user")
125
+ return m;
126
+ const blocks = [
127
+ { kind: "text", text: MARKER, origin: { by: "plugin", id: ID }, trust: "trusted" },
128
+ ...texts.map((text) => ({ kind: "text", text, origin: { by: "user" }, trust: "trusted" })),
129
+ ];
130
+ return { ...m, content: [...m.content, ...blocks] };
131
+ });
132
+ },
133
+ });
134
+ },
135
+ });
@@ -0,0 +1,12 @@
1
+ {
2
+ "id": "jade/steer",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.js",
6
+ "provides": [
7
+ "steer@1"
8
+ ],
9
+ "optional": [
10
+ "renderers@1"
11
+ ]
12
+ }
@@ -1,13 +1,13 @@
1
1
  // jade/suggest:每一轮正常结束后,预测用户下一条想发的消息,灰色显示在输入框里,Tab 或 → 接受。默认关着(enabled)。
2
2
  //
3
- // 模型经 models@1:配置 model 是 /model 保存过的模型名,不设时用会话的模型。
3
+ // 模型经 models@1:配置 model 是 /model 保存过的模型名或当前服务上的模型名,不设时用会话的模型。
4
4
  // /suggest 在 TUI 里开关、选模型,马上生效,记在 $JADE_HOME/state/suggest.json,盖过 config.json 里的 enabled 和 model。
5
5
  // 对话从 context.project(每次请求模型前的消息)和 model.after(这一轮最后的回复)取,轮次结束从 turn.ended 事件知道。
6
6
  // 从旧 jade 的 examples/plugins/suggest 移植;提示词、对话的整理和截取、回复的清理参考 dsh-ghost-prompt。
7
7
  import { randomBytes } from "node:crypto";
8
8
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
9
9
  import path from "node:path";
10
- import { definePlugin } from "../../dist/api.js";
10
+ import { definePlugin } from "@uncarved/jade-api";
11
11
  export const SYSTEM = [
12
12
  "You predict the next message the USER will type to an AI coding assistant.",
13
13
  "You are given the recent conversation. Write the single message the user is most likely to send next, exactly as they would type it.",
@@ -16,6 +16,9 @@ export const SYSTEM = [
16
16
  "- Match the language and tone the user has been writing in. If the user writes Chinese, answer in Chinese.",
17
17
  "- Keep it short: one sentence, at most about 20 words or 40 CJK characters.",
18
18
  "- Prefer the obvious next step: answering a question the assistant just asked, approving a proposed plan, verifying or continuing the work.",
19
+ "- The user gives instructions; write an instruction or a short answer, not a question.",
20
+ '- Never summarize or describe the work that was done (wrong: "the Title weights are fixed now"). That is the assistant\'s job, not the user\'s.',
21
+ '- Never speak as the assistant: no offers or plans like "want me to...", "I will...", "需要我…吗", "我会…". When the assistant offered something, the user accepts or declines it (assistant: "I can commit this if you want" -> user: "commit it").',
19
22
  "- Never repeat a request the user already made, and never invent facts, file names or numbers not in the conversation.",
20
23
  "- If no next message is reasonably predictable, output exactly: NONE",
21
24
  'Output only the message text on one line. No quotes, no prefix like "User:", no explanation, no Markdown.',
@@ -76,12 +79,13 @@ export function frame(transcript, budget = MAX_CONTEXT_CHARS) {
76
79
  const LEADING_PREFIX = /^(?:user|用户)\s*[::]\s*/i;
77
80
  const LEADING_QUOTES = /^["'“”‘’`「『]+/;
78
81
  const TRAILING_QUOTES = /["'“”‘’`」』]+$/;
79
- /** 模型回复的第一行整理成建议:去掉 "User:" 前缀和包着的引号;NONE 或空的时候 undefined */
82
+ /** 模型回复的第一行整理成建议:去掉 "User:" 前缀和包着的引号;NONE、空或问句的时候 undefined */
80
83
  export function tidy(reply) {
81
84
  let line = reply.trimStart().split(/\r?\n/)[0].trim().replace(LEADING_PREFIX, "");
82
85
  if (LEADING_QUOTES.test(line))
83
86
  line = line.replace(LEADING_QUOTES, "").replace(TRAILING_QUOTES, "").trim();
84
- if (!line || /^none\.?$/i.test(line))
87
+ // 问句多半是模型把助手的"要不要我…?"当成了用户的话,猜中用户真要问什么的少,不显示
88
+ if (!line || /^none\.?$/i.test(line) || /[??]$/.test(line))
85
89
  return undefined;
86
90
  return line.length > 300 ? `${line.slice(0, 299)}…` : line;
87
91
  }
@@ -121,7 +125,7 @@ export default definePlugin({
121
125
  ...(await readState(file)),
122
126
  };
123
127
  const models = ctx.require("models@1");
124
- const describe = () => `suggestions are ${settings.enabled ? "on" : "off"}, predicted by ${settings.model ? `the saved model ${settings.model}` : "the session's model"}`;
128
+ const describe = () => `suggestions are ${settings.enabled ? "on" : "off"}, predicted by ${settings.model ? `the model ${settings.model}` : "the session's model"}`;
125
129
  const update = async (next) => {
126
130
  settings = { ...settings, ...next };
127
131
  for (const fn of changed)
@@ -140,7 +144,9 @@ export default definePlugin({
140
144
  if (sub === "on" || sub === "off")
141
145
  return update({ enabled: sub === "on" });
142
146
  if (sub === "model") {
143
- const saved = (await models.saved?.()) ?? [];
147
+ // 能选的:/model 保存过的,加上当前服务提供的(不用先在 /model 里保存)
148
+ const [saved, listed] = await Promise.all([models.saved?.() ?? [], models.list().catch(() => [])]);
149
+ const names = [...new Set([...saved, ...listed])];
144
150
  let name = rest.join(" ");
145
151
  if (!name) {
146
152
  const SESSION = "\0session";
@@ -148,15 +154,15 @@ export default definePlugin({
148
154
  title: "Which model predicts your next message?",
149
155
  options: [
150
156
  { label: "The session's model", value: SESSION },
151
- ...saved.map((m) => ({ label: m, value: m, ...(m === settings.model ? { hint: "current" } : {}) })),
157
+ ...names.map((m) => ({ label: m, value: m, ...(m === settings.model ? { hint: "current" } : saved.includes(m) ? { hint: "saved" } : {}) })),
152
158
  ],
153
159
  }, c.signal);
154
160
  if (picked === undefined)
155
161
  return;
156
162
  name = picked === SESSION ? undefined : picked;
157
163
  }
158
- else if (models.saved && !saved.includes(name)) {
159
- return `${name} is not a model saved by /model. ${saved.length ? `Saved: ${saved.join(", ")}.` : "Add one with /model first."}`;
164
+ else if (models.saved && !names.includes(name)) {
165
+ return `${name} is not a model saved by /model or offered by the current service. ${names.length ? `Available: ${names.join(", ")}.` : "Add one with /model first."}`;
160
166
  }
161
167
  return update({ model: name });
162
168
  }
@@ -17,7 +17,7 @@
17
17
  },
18
18
  "model": {
19
19
  "default": "",
20
- "description": "the model that predicts, by a name saved with /model; empty uses the session's model; /suggest model overrides it"
20
+ "description": "the model that predicts: a name saved with /model or a model of the current service; empty uses the session's model; /suggest model overrides it"
21
21
  }
22
22
  }
23
23
  }
@@ -1,57 +1,16 @@
1
1
  // jade/task:task 工具,把调研交给只读的子 Agent(见 subagent.ts)。
2
2
  //
3
- // 子 Agent 用哪些工具:插件经 task@1 登记只读工具(jade/fs 登记 read_file、list_dir、glob、grep),
4
- // 登记随登记者的作用域撤销。主会话里的工具对象是各插件私有的,子 Agent 拿到的是登记者另给的一份。
5
- import { definePlugin } from "../../dist/api.js";
3
+ // 子 Agent 用哪些工具:其他插件登记在 tools@1(jade/tools)里的那些(jade/fs 登记 read_file、list_dir、glob、grep),
4
+ // 每次启动子 Agent 时取。主会话里的工具对象是各插件私有的,子 Agent 拿到的是登记者另给的一份。
5
+ import { definePlugin } from "@uncarved/jade-api";
6
6
  import { taskTool } from "./subagent.js";
7
7
  import { clip, dim, red } from "./style.js";
8
8
  const DEFAULT_MAX_STEPS = 40;
9
9
  const MAX_DETAIL_LINES = 40;
10
- /** 登记的只读工具,按登记顺序 */
11
- const registry = [];
12
- /** 这次启动子 Agent 时给它的工具:同名的取最后登记的那个,when 返回 false 或出错的不给 */
13
- function available() {
14
- const latest = new Map();
15
- for (const r of registry) {
16
- latest.delete(r.tool.name);
17
- latest.set(r.tool.name, r);
18
- }
19
- return [...latest.values()].flatMap((r) => {
20
- try {
21
- return !r.when || r.when() ? [r.tool] : [];
22
- }
23
- catch {
24
- return [];
25
- }
26
- });
27
- }
28
10
  /** 子 Agent 的审批一次问一个:并行的几个子 Agent 不同时弹对话框 */
29
11
  let asking = Promise.resolve();
30
12
  export default definePlugin({
31
13
  process(ctx) {
32
- ctx.provide("task@1", (caller) => ({
33
- tool(tool, opts) {
34
- if (typeof tool?.name !== "string" || typeof tool.execute !== "function")
35
- throw new Error("task.tool: a tool needs a name and execute");
36
- if (tool.effect !== "read")
37
- throw new Error(`task.tool: ${tool.name} is not read-only (effect ${JSON.stringify(tool.effect)}); sub-agents only get read-only tools`);
38
- // 同一个插件重复登记是正常的:换会话时新会话先登记,旧会话随后撤销它的那份;取最后登记的
39
- const taken = registry.find((r) => r.tool.name === tool.name && r.plugin !== caller.plugin);
40
- if (taken)
41
- throw new Error(`task.tool: ${tool.name} is already registered by ${taken.plugin}`);
42
- if (opts?.when !== undefined && typeof opts.when !== "function")
43
- throw new Error("task.tool: when must be a function");
44
- const entry = { tool, plugin: caller.plugin, ...(opts?.when ? { when: opts.when } : {}) };
45
- registry.push(entry);
46
- const revoke = () => {
47
- const i = registry.indexOf(entry);
48
- if (i !== -1)
49
- registry.splice(i, 1);
50
- };
51
- caller.onDispose(revoke);
52
- return revoke;
53
- },
54
- }));
55
14
  const renderers = ctx.service("renderers@1");
56
15
  if (renderers) {
57
16
  // 运行中每个只有一行进度(标签、调用过几个工具、正在做什么),并行的几个靠标签分清;结束时把它调用过的工具放进结果的折叠内容里
@@ -104,6 +63,8 @@ export default definePlugin({
104
63
  const usage = new Map();
105
64
  const configured = ctx.config.maxSteps;
106
65
  const maxSteps = typeof configured === "number" && Number.isInteger(configured) && configured > 0 ? configured : DEFAULT_MAX_STEPS;
66
+ // 子 Agent 用的模型:/model 保存过的名字,或当前服务上的另一个模型;不设时用会话的模型
67
+ const model = typeof ctx.config.model === "string" && ctx.config.model ? ctx.config.model : undefined;
107
68
  const approve = (call, signal) => {
108
69
  const ui = ctx.service("ui@1");
109
70
  if (!ui?.interactive)
@@ -124,11 +85,21 @@ export default definePlugin({
124
85
  };
125
86
  ctx.kernel.tool(taskTool({
126
87
  cwd: ctx.cwd,
127
- provider: { id: ctx.plugin, complete: (req, o) => models.complete(req, o) },
128
- tools: available,
88
+ provider: { id: ctx.plugin, complete: (req, o) => models.complete(req, model ? { ...o, model } : o) },
89
+ // 没有 jade/tools、或者它被隔离了(服务已失效,调用会抛错):子 Agent 没有工具
90
+ tools: () => {
91
+ try {
92
+ return ctx.service("tools@1")?.list() ?? [];
93
+ }
94
+ catch {
95
+ return [];
96
+ }
97
+ },
129
98
  maxSteps,
130
99
  approve,
131
100
  allowed: (call) => ctx.service("approval@1")?.allows(ctx.session.id, call) ?? false,
101
+ // 用到的时候再取:prompts@1 的提供者在自己的 session() 里才读指令文件,可能排在本插件后面
102
+ ...(ctx.config.instructions === false ? {} : { instructions: () => ctx.service("prompts@1")?.instructions?.(ctx.session.id) ?? [] }),
132
103
  id: ctx.plugin,
133
104
  usage: (toolUseId, u) => void usage.set(toolUseId, u),
134
105
  contextWindow: () => models.current()?.contextWindow,