@capybara-hq/plugin-sdk 0.1.0-rc.1 → 0.1.0-rc.11

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 (97) hide show
  1. package/README.md +1 -1
  2. package/agent-docs/agent-templates.md +47 -0
  3. package/agent-docs/concepts.md +63 -0
  4. package/agent-docs/connector-templates.md +48 -0
  5. package/agent-docs/extension-points/channel.md +15 -0
  6. package/agent-docs/extension-points/config-source.md +15 -0
  7. package/agent-docs/extension-points/connector.md +15 -0
  8. package/agent-docs/extension-points/counter.md +15 -0
  9. package/agent-docs/extension-points/directory.md +15 -0
  10. package/agent-docs/extension-points/file-preview.md +15 -0
  11. package/agent-docs/extension-points/identity-source.md +15 -0
  12. package/agent-docs/extension-points/model-provider.md +15 -0
  13. package/agent-docs/extension-points/object-store.md +15 -0
  14. package/agent-docs/extension-points/sandbox.md +15 -0
  15. package/agent-docs/extension-points/secret-store.md +15 -0
  16. package/agent-docs/extension-points/web-fetch.md +15 -0
  17. package/agent-docs/extension-points/web-search.md +15 -0
  18. package/agent-docs/extensions.md +87 -0
  19. package/agent-docs/plugin-format.md +100 -0
  20. package/agent-docs/setup.md +46 -0
  21. package/agent-docs/skills.md +44 -0
  22. package/agent-docs/tool-naming.md +21 -0
  23. package/dist/agent-template.d.ts +85 -0
  24. package/dist/agent-template.js +361 -2
  25. package/dist/cards.d.ts +7 -0
  26. package/dist/cards.js +4 -4
  27. package/dist/channel.d.ts +20 -1
  28. package/dist/client-css.d.ts +36 -0
  29. package/dist/client-css.js +326 -0
  30. package/dist/client-section.d.ts +35 -0
  31. package/dist/client-section.js +133 -0
  32. package/dist/config-ui.d.ts +131 -0
  33. package/dist/config-ui.js +602 -0
  34. package/dist/connector-auth.d.ts +2 -0
  35. package/dist/connector-auth.js +15 -0
  36. package/dist/ctx.d.ts +86 -4
  37. package/dist/define-extension.d.ts +5 -1
  38. package/dist/define-extension.js +1 -0
  39. package/dist/device-protocol.d.ts +118 -0
  40. package/dist/device-protocol.js +276 -0
  41. package/dist/directory.d.ts +11 -2
  42. package/dist/extension-point.d.ts +9 -0
  43. package/dist/extension-point.js +17 -12
  44. package/dist/file-preview.d.ts +9 -1
  45. package/dist/hooks.d.ts +76 -16
  46. package/dist/index.d.ts +18 -1
  47. package/dist/index.js +18 -1
  48. package/dist/marketplace.d.ts +55 -2
  49. package/dist/marketplace.js +73 -3
  50. package/dist/model.d.ts +60 -2
  51. package/dist/model.js +22 -0
  52. package/dist/org-access.d.ts +27 -0
  53. package/dist/org-access.js +35 -0
  54. package/dist/permissions.d.ts +32 -7
  55. package/dist/permissions.js +86 -22
  56. package/dist/plugin-manifest.d.ts +70 -5
  57. package/dist/plugin-manifest.js +186 -6
  58. package/dist/sandbox.d.ts +164 -62
  59. package/dist/sandbox.js +71 -14
  60. package/dist/secret.d.ts +4 -1
  61. package/dist/secret.js +5 -2
  62. package/dist/setup-check.d.ts +115 -0
  63. package/dist/setup-check.js +142 -0
  64. package/dist/setup-guide-parse.d.ts +121 -0
  65. package/dist/setup-guide-parse.js +350 -0
  66. package/dist/setup-guide-render.d.ts +45 -0
  67. package/dist/setup-guide-render.js +351 -0
  68. package/dist/setup-guide.d.ts +94 -0
  69. package/dist/setup-guide.js +336 -0
  70. package/dist/skill-invocation.d.ts +9 -5
  71. package/dist/skill-invocation.js +18 -8
  72. package/dist/skill.d.ts +23 -3
  73. package/dist/skill.js +31 -6
  74. package/dist/theme-assets.d.ts +39 -0
  75. package/dist/theme-assets.js +449 -0
  76. package/dist/theme-readability.d.ts +37 -0
  77. package/dist/theme-readability.js +145 -0
  78. package/dist/theme-tokens.generated.d.ts +275 -0
  79. package/dist/theme-tokens.generated.js +167 -0
  80. package/dist/theme.d.ts +152 -0
  81. package/dist/theme.js +392 -0
  82. package/dist/tool.d.ts +11 -3
  83. package/dist/ui-parts.d.ts +23 -0
  84. package/dist/ui-parts.js +238 -0
  85. package/dist/ui-resolve.d.ts +40 -0
  86. package/dist/ui-resolve.js +54 -0
  87. package/dist/ui-slots.d.ts +55 -0
  88. package/dist/ui-slots.js +247 -0
  89. package/dist/ui.d.ts +143 -37
  90. package/dist/ui.js +65 -5
  91. package/dist/web.d.ts +105 -0
  92. package/dist/web.js +135 -0
  93. package/package.json +10 -2
  94. package/schemas/connector-template.v1.schema.json +3 -0
  95. package/schemas/marketplace.v1.schema.json +50 -0
  96. package/schemas/plugin.v1.schema.json +164 -4
  97. package/schemas/theme.v1.schema.json +225 -0
@@ -0,0 +1,336 @@
1
+ /**
2
+ * Plugin setup guides v2 (spec `2026-11-09-setup-guides-v2-design.md`): Markdown documents a plugin
3
+ * ships (`guides/<id>.md`, optional `guides/<id>.zh.md`) that the kernel renders for a place with a
4
+ * fixed set of safe, deterministic variables, mode and audience sections and live check rows. The
5
+ * declaration lives in `plugin.json` `setupGuides` ({@link PluginSetupGuide}); this module holds the
6
+ * place registry, the limits, the validator and the drift hash. The parser is
7
+ * `setup-guide-parse.ts`, the renderer `setup-guide-render.ts`.
8
+ *
9
+ * Variables are `{{name}}` (spaces inside the braces allowed) with `name` matching
10
+ * `[A-Za-z][A-Za-z0-9]*`. There is no other template syntax.
11
+ */
12
+ import { createHash } from "node:crypto";
13
+ import { analyzeSetupGuide, checkMarkerIndex, ENCODED_SENTINEL_RE, lineSelected, normalizeGuideSource, parseGuideMarkdown, preparedGuideText, SENTINEL_RE, scanGuide, visitGuide, } from "./setup-guide-parse.js";
14
+ /**
15
+ * Where a guide is shown. `channel-connection`: 新建渠道 and the channel detail page;
16
+ * `connector-template`: the pages of a connector template and the connectors made from it.
17
+ */
18
+ export const SETUP_GUIDE_PLACES = ["channel-connection", "connector-template"];
19
+ const COMMON_VARIABLES = {
20
+ publicUrl: "url",
21
+ orgName: "text",
22
+ pluginName: "token",
23
+ pluginVersion: "token",
24
+ mode: "token",
25
+ };
26
+ /** The place registry. None of the variables is a secret. */
27
+ export const SETUP_GUIDE_PLACE_INFO = {
28
+ "channel-connection": {
29
+ modes: ["long_connection", "webhook"],
30
+ audiences: ["admin"],
31
+ variables: {
32
+ ...COMMON_VARIABLES,
33
+ webhookUrl: "url",
34
+ signInCallbackUrl: "url",
35
+ connectionName: "text",
36
+ },
37
+ drift: true,
38
+ },
39
+ "connector-template": {
40
+ modes: [],
41
+ audiences: ["admin", "member"],
42
+ variables: {
43
+ ...COMMON_VARIABLES,
44
+ oauthCallbackUrl: "url",
45
+ signInCallbackUrl: "url",
46
+ templateId: "token",
47
+ templateName: "text",
48
+ connectorName: "text",
49
+ },
50
+ drift: true,
51
+ },
52
+ };
53
+ /** Limits of setup guides. */
54
+ export const SETUP_GUIDE_LIMITS = {
55
+ /** Guides per plugin. */
56
+ guides: 8,
57
+ /** Bytes per document (each language). */
58
+ docBytes: 65536,
59
+ /** Fenced code blocks per document. */
60
+ codeBlocks: 24,
61
+ /** Check lines per document. */
62
+ checks: 16,
63
+ /** Sections per document. */
64
+ sections: 16,
65
+ /** Characters of the title and of a heading. */
66
+ titleChars: 100,
67
+ /** Characters of a check label. */
68
+ checkLabelChars: 80,
69
+ /** Characters of a code fence title. */
70
+ fenceTitleChars: 100,
71
+ /** Markdown nesting depth. */
72
+ depth: 16,
73
+ };
74
+ /** The package path of a guide's document: `guides/<id>.md` (en) or `guides/<id>.zh.md` (zh). */
75
+ export function setupGuideDocPath(id, locale) {
76
+ return locale === "zh" ? `guides/${id}.zh.md` : `guides/${id}.md`;
77
+ }
78
+ /**
79
+ * Whether a guide document is usable as a file: present, at most
80
+ * {@link SETUP_GUIDE_LIMITS}`.docBytes`, valid UTF-8 without NUL and without U+E000–U+E0FF. The
81
+ * problem (English, naming the path), or undefined. Shared by the packer and the kernel's reader.
82
+ */
83
+ export function setupGuideDocProblem(path, data) {
84
+ if (data === undefined)
85
+ return `${path} not found in the package`;
86
+ if (data.byteLength > SETUP_GUIDE_LIMITS.docBytes) {
87
+ return `${path} is larger than ${SETUP_GUIDE_LIMITS.docBytes} bytes`;
88
+ }
89
+ let text;
90
+ try {
91
+ text = new TextDecoder("utf-8", { fatal: true }).decode(data);
92
+ }
93
+ catch {
94
+ return `${path} is not valid UTF-8 text`;
95
+ }
96
+ if (text.includes("\u0000"))
97
+ return `${path} is not a text file (it contains NUL)`;
98
+ if (/[-]/.test(text)) {
99
+ return `${path} contains a private-use character (U+E000–U+E0FF), which guides may not use`;
100
+ }
101
+ return undefined;
102
+ }
103
+ const QUOTING_LANGUAGES = new Set(["yaml", "yml", "json"]);
104
+ const firstUrlSentinel = /^(?:|%EE%80%80)(\d+)(?:|%EE%80%81)/i;
105
+ const hasSentinel = (s) => s !== null &&
106
+ s !== undefined &&
107
+ (new RegExp(SENTINEL_RE.source).test(s) || new RegExp(ENCODED_SENTINEL_RE.source, "i").test(s));
108
+ const sentinelIndexes = (s) => [
109
+ ...[...s.matchAll(SENTINEL_RE)].map((m) => Number(m[1])),
110
+ ...[...s.matchAll(ENCODED_SENTINEL_RE)].map((m) => Number(m[1])),
111
+ ];
112
+ /**
113
+ * Validates a guide's documents for a place (spec §4.5): title, sections well formed and known to
114
+ * the place, check lines, fence info strings, no indented code, limits, variables known to the place
115
+ * and allowed where they stand (§6.2), language parity of the zh document (§4.3), and, when
116
+ * `pluginChecks` is given, that every plugin check id is declared there (the extension's
117
+ * `permissions.setupChecks`). Messages name the file (`guides/<id>.md` when `id` is given) and line.
118
+ * `allowUnknownVariables` (the kernel's importer) accepts variables the place does not define: they
119
+ * render as written. Pure.
120
+ */
121
+ export function validateSetupGuide(input) {
122
+ const info = SETUP_GUIDE_PLACE_INFO[input.place];
123
+ const fileOf = (locale) => input.id !== undefined
124
+ ? setupGuideDocPath(input.id, locale)
125
+ : locale === "en"
126
+ ? "the English document"
127
+ : "the Chinese document";
128
+ const out = [];
129
+ const parsedBy = {};
130
+ const one = (locale, source) => {
131
+ const file = fileOf(locale);
132
+ const push = (i) => out.push({
133
+ level: i.level,
134
+ message: i.line !== undefined ? `${file}:${i.line}: ${i.message}` : `${file}: ${i.message}`,
135
+ });
136
+ const bytes = new TextEncoder().encode(source).byteLength;
137
+ if (bytes > SETUP_GUIDE_LIMITS.docBytes) {
138
+ push({ level: "error", message: `is larger than ${SETUP_GUIDE_LIMITS.docBytes} bytes` });
139
+ return;
140
+ }
141
+ const { parsed, scan, tree, uses } = analyzeSetupGuide(source);
142
+ parsedBy[locale] = parsed;
143
+ const issues = [...parsed.issues];
144
+ const err = (line, message, level = "error") => issues.push({ level, ...(line !== undefined && { line }), message });
145
+ for (const s of parsed.sections) {
146
+ if (s.type === "mode" && !info.modes.includes(s.value)) {
147
+ err(s.line, info.modes.length === 0
148
+ ? `place ${input.place} has no modes`
149
+ : `mode "${s.value}" is not one of the modes of place ${input.place}: ${info.modes.join(", ")}`);
150
+ }
151
+ if (s.type === "audience" && !info.audiences.includes(s.value)) {
152
+ err(s.line, `audience "${s.value}" is not one of the audiences of place ${input.place}: ${info.audiences.join(", ")}`);
153
+ }
154
+ }
155
+ if (input.pluginChecks !== undefined) {
156
+ for (const c of parsed.checks) {
157
+ if (c.source === "plugin" && !input.pluginChecks.includes(c.id)) {
158
+ err(c.line, `check ${c.id} is not declared in the extension's permissions.setupChecks`);
159
+ }
160
+ }
161
+ }
162
+ // a check id twice in one rendering
163
+ const dupes = new Set();
164
+ for (const mode of [null, ...info.modes]) {
165
+ for (const audience of info.audiences) {
166
+ const seen = new Set();
167
+ parsed.checks.forEach((c) => {
168
+ if (!lineSelected(scan, c.line - 1, mode, audience))
169
+ return;
170
+ if (seen.has(c.id) && !dupes.has(c.id)) {
171
+ dupes.add(c.id);
172
+ err(c.line, `check ${c.id} appears twice in one rendering of the guide`);
173
+ }
174
+ seen.add(c.id);
175
+ });
176
+ }
177
+ }
178
+ // variables: known to the place, and allowed where they stand
179
+ const reported = new Set();
180
+ for (const u of uses) {
181
+ if (Object.hasOwn(info.variables, u.name) || input.allowUnknownVariables === true)
182
+ continue;
183
+ if (reported.has(u.name))
184
+ continue;
185
+ reported.add(u.name);
186
+ err(u.line, `unknown variable {{${u.name}}} for place ${input.place} (known: ${Object.keys(info.variables).join(", ")})`);
187
+ }
188
+ const typeOf = (n) => {
189
+ const name = uses[n]?.name;
190
+ return name === undefined ? undefined : info.variables[name];
191
+ };
192
+ const nameOf = (n) => `{{${uses[n]?.name ?? "?"}}}`;
193
+ const checkDestination = (url, line) => {
194
+ const all = sentinelIndexes(url);
195
+ if (all.length === 0)
196
+ return;
197
+ const m = firstUrlSentinel.exec(url);
198
+ const ok = m !== null && all.length === 1 && typeOf(Number(m[1])) === "url";
199
+ if (!ok) {
200
+ err(line, `${all.map(nameOf).join(", ")} in a link destination: only a url variable may stand there, at its start`);
201
+ }
202
+ };
203
+ visitGuide(tree, (node) => {
204
+ const line = node.position?.start.line;
205
+ switch (node.type) {
206
+ case "code": {
207
+ const lang = (node.lang ?? "").toLowerCase();
208
+ if (QUOTING_LANGUAGES.has(lang)) {
209
+ // values are JSON-escaped without the quotes: only safe inside a "…" string
210
+ for (const lineText of node.value.split("\n")) {
211
+ for (const m of lineText.matchAll(SENTINEL_RE)) {
212
+ const n = Number(m[1]);
213
+ if (typeOf(n) !== "text")
214
+ continue;
215
+ const before = lineText.slice(0, m.index).replace(/\\./g, "");
216
+ if ((before.match(/"/g)?.length ?? 0) % 2 === 1)
217
+ continue;
218
+ err(line, `the text variable ${nameOf(n)} in a ${lang} code block is not inside double quotes; its value is escaped as a string and may break the block or change its type ("${nameOf(n)}")`, "warning");
219
+ }
220
+ }
221
+ return;
222
+ }
223
+ for (const n of sentinelIndexes(node.value)) {
224
+ if (typeOf(n) === "text") {
225
+ err(line, `the text variable ${nameOf(n)} in a ${lang || "plain"} code block is not quoted; a value with spaces or quotes may break it (use a yaml or json block with "${nameOf(n)}")`, "warning");
226
+ }
227
+ }
228
+ return;
229
+ }
230
+ case "link":
231
+ case "definition":
232
+ checkDestination(node.url, line);
233
+ if (hasSentinel(node.title))
234
+ err(line, "variables are not allowed in a link title");
235
+ return;
236
+ case "image":
237
+ case "imageReference":
238
+ if (hasSentinel(node.alt) ||
239
+ (node.type === "image" && (hasSentinel(node.url) || hasSentinel(node.title)))) {
240
+ err(line, "variables are not allowed in an image");
241
+ }
242
+ return;
243
+ default:
244
+ return;
245
+ }
246
+ });
247
+ issues.sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
248
+ issues.forEach(push);
249
+ };
250
+ one("en", input.en);
251
+ if (input.zh !== undefined)
252
+ one("zh", input.zh);
253
+ const en = parsedBy.en;
254
+ const zh = parsedBy.zh;
255
+ if (en !== undefined && zh !== undefined) {
256
+ const enFile = fileOf("en");
257
+ const zhFile = fileOf("zh");
258
+ const sec = (p) => JSON.stringify(p.sections.map((s) => [s.type, s.value, s.parent]));
259
+ if (sec(en) !== sec(zh)) {
260
+ out.push({
261
+ level: "error",
262
+ message: `${zhFile}: the sections differ from ${enFile}; both languages need the same sections in the same order`,
263
+ });
264
+ }
265
+ const chk = (p) => JSON.stringify(p.checks.map((c) => [c.section, c.id]));
266
+ if (chk(en) !== chk(zh)) {
267
+ out.push({
268
+ level: "error",
269
+ message: `${zhFile}: the checks differ from ${enFile}; both languages need the same check ids in the same sections`,
270
+ });
271
+ }
272
+ if (en.codeBlocks.length !== zh.codeBlocks.length) {
273
+ out.push({
274
+ level: "error",
275
+ message: `${zhFile}: has ${zh.codeBlocks.length} code blocks and ${enFile} has ${en.codeBlocks.length}; code blocks must be identical in every language`,
276
+ });
277
+ }
278
+ else {
279
+ en.codeBlocks.forEach((e, i) => {
280
+ const z = zh.codeBlocks[i];
281
+ if (z === undefined)
282
+ return;
283
+ const n = i + 1;
284
+ const name = `code block ${n}${z.title !== null ? ` ("${z.title}")` : ""}`;
285
+ if (z.section !== e.section) {
286
+ out.push({
287
+ level: "error",
288
+ message: `${zhFile}: ${name} is in another section than ${enFile} block ${n}; code blocks must be identical in every language`,
289
+ });
290
+ return;
291
+ }
292
+ if (z.language === e.language && z.text === e.text)
293
+ return;
294
+ if (z.language !== e.language) {
295
+ out.push({
296
+ level: "error",
297
+ message: `${zhFile}: ${name} is ${z.language || "without a language"} but ${enFile} block ${n} is ${e.language || "without a language"}; code blocks must be identical in every language`,
298
+ });
299
+ return;
300
+ }
301
+ const el = e.text.split("\n");
302
+ const zl = z.text.split("\n");
303
+ let line = 0;
304
+ while (line < el.length && line < zl.length && el[line] === zl[line])
305
+ line++;
306
+ out.push({
307
+ level: "error",
308
+ message: `${zhFile}: ${name} differs from ${enFile} block ${n} at line ${line + 1}; code blocks must be identical in every language`,
309
+ });
310
+ });
311
+ }
312
+ }
313
+ return out;
314
+ }
315
+ /**
316
+ * The drift hash of a guide for one mode and audience (spec §11): sha256 (hex) over the place, guide
317
+ * id, mode and audience, then, in document order after section selection, each fenced code block
318
+ * (language and text, title excluded) and each check id of the English document. Variables are not
319
+ * substituted; line endings are normalized. Prose, headings and check labels do not move it.
320
+ */
321
+ export function setupGuideHash(enSource, input) {
322
+ const scan = scanGuide(normalizeGuideSource(enSource));
323
+ const tree = parseGuideMarkdown(preparedGuideText(scan, (i) => lineSelected(scan, i, input.mode, input.audience)));
324
+ const h = createHash("sha256");
325
+ h.update(`capybara-guide-v2\0${input.place}\0${input.guideId}\0${input.mode ?? ""}\0${input.audience}\0`);
326
+ visitGuide(tree, (node) => {
327
+ if (node.type === "code") {
328
+ h.update(`code\0${node.lang ?? ""}\0${node.value}\0`);
329
+ return;
330
+ }
331
+ const c = checkMarkerIndex(node);
332
+ if (c !== undefined)
333
+ h.update(`check\0${scan.checks[c]?.id ?? ""}\0`);
334
+ });
335
+ return h.digest("hex");
336
+ }
@@ -26,13 +26,15 @@ export declare function skillInvocation(frontmatter: Readonly<Record<string, unk
26
26
  export declare function parseSkillArguments(args: string): string[];
27
27
  /**
28
28
  * A skill body with its arguments substituted (see the file header), without the wrapper.
29
- * `skillName` is the resolved skill's bare name: `${CLAUDE_SKILL_DIR}` becomes
30
- * `/skills/<skillName>` (a qualified `<plugin>:<name>` throws a `TypeError`). `args` is trimmed;
29
+ * `skillName` is the resolved skill's bare name and `digest` its version's `skillDigest`:
30
+ * `${CLAUDE_SKILL_DIR}` becomes `<skillsRoot>/<skillName>@<digest>` (`skillsRoot`: the instance's
31
+ * skills root, default `/skills`; a qualified `<plugin>:<name>` or a digest that is not 12
32
+ * lowercase hex digits throws a `TypeError`). `args` is trimmed;
31
33
  * more than {@link SKILL_INVOCATION_LIMITS.argumentsMaxChars} characters throw a `RangeError`, and
32
34
  * so does a result longer than {@link SKILL_INVOCATION_LIMITS.renderedMaxChars} (checked while
33
35
  * substituting, before the long string is built).
34
36
  */
35
- export declare function renderSkillBody(body: string, invocation: SkillInvocation, args: string, skillName: string): string;
37
+ export declare function renderSkillBody(body: string, invocation: SkillInvocation, args: string, skillName: string, digest: string, skillsRoot?: string): string;
36
38
  /** Input of {@link renderSkillInvocation}. */
37
39
  export interface RenderSkillInvocationInput {
38
40
  /**
@@ -41,10 +43,12 @@ export interface RenderSkillInvocationInput {
41
43
  */
42
44
  name: string;
43
45
  /**
44
- * The resolved skill's bare name (never `<plugin>:<name>`): its sandbox directory
45
- * `/skills/<skillName>/`, used for `${CLAUDE_SKILL_DIR}` and the files line.
46
+ * The resolved skill's bare name (never `<plugin>:<name>`): with `digest`, its sandbox
47
+ * directory `/skills/<skillName>@<digest>/`, used for `${CLAUDE_SKILL_DIR}` and the files line.
46
48
  */
47
49
  skillName: string;
50
+ /** The version's `skillDigest` (12 lowercase hex digits). */
51
+ digest: string;
48
52
  version: number;
49
53
  /** The SKILL.md body (after the frontmatter). */
50
54
  body: string;
@@ -6,12 +6,12 @@
6
6
  * The argument rules follow Claude Code (re-checked 2026-10-27): `$ARGUMENTS` is the whole argument
7
7
  * string, `$ARGUMENTS[N]` / `$N` are 0-based positional values (a missing one stays as written),
8
8
  * `$name` takes its value from frontmatter `arguments` (a missing one becomes empty), `\$` is a
9
- * literal `$`, `${CLAUDE_SKILL_DIR}` is `/skills/<name>` and every other `${…}` stays as written.
9
+ * literal `$`, `${CLAUDE_SKILL_DIR}` is `/skills/<name>@<digest>` and every other `${…}` stays as written.
10
10
  * When the body has no argument placeholder and the arguments are not empty, they are appended as
11
11
  * `ARGUMENTS: <args>`. Substituted text is never scanned again. Nothing is executed: shell
12
12
  * injections (`` !`cmd` ``) stay text, and the model is told how to run them.
13
13
  */
14
- import { isSkillName, SKILL_INVOCATION_LIMITS, SKILLS_SANDBOX_ROOT } from "./skill.js";
14
+ import { isSkillName, SKILL_INVOCATION_LIMITS, SKILLS_SANDBOX_ROOT, skillSandboxDir, } from "./skill.js";
15
15
  import { argumentHintText, SKILL_ARGUMENT_NAME_RE } from "./skill-keys.js";
16
16
  /**
17
17
  * The invocation metadata of a SKILL.md frontmatter. Values of the wrong type are ignored here
@@ -102,17 +102,27 @@ const checkSkillName = (skillName) => {
102
102
  throw new TypeError(`skillName must be a bare skill name (its directory under ${SKILLS_SANDBOX_ROOT}), got "${skillName}"`);
103
103
  }
104
104
  };
105
+ const DIGEST_RE = /^[0-9a-f]{12}$/;
106
+ const checkDigest = (digest) => {
107
+ if (typeof digest !== "string" || !DIGEST_RE.test(digest)) {
108
+ throw new TypeError(`digest must be 12 lowercase hex digits (skillDigest), got "${digest}"`);
109
+ }
110
+ };
105
111
  const tooLong = () => new RangeError(`the rendered skill must be at most ${SKILL_INVOCATION_LIMITS.renderedMaxChars} characters`);
106
112
  /**
107
113
  * A skill body with its arguments substituted (see the file header), without the wrapper.
108
- * `skillName` is the resolved skill's bare name: `${CLAUDE_SKILL_DIR}` becomes
109
- * `/skills/<skillName>` (a qualified `<plugin>:<name>` throws a `TypeError`). `args` is trimmed;
114
+ * `skillName` is the resolved skill's bare name and `digest` its version's `skillDigest`:
115
+ * `${CLAUDE_SKILL_DIR}` becomes `<skillsRoot>/<skillName>@<digest>` (`skillsRoot`: the instance's
116
+ * skills root, default `/skills`; a qualified `<plugin>:<name>` or a digest that is not 12
117
+ * lowercase hex digits throws a `TypeError`). `args` is trimmed;
110
118
  * more than {@link SKILL_INVOCATION_LIMITS.argumentsMaxChars} characters throw a `RangeError`, and
111
119
  * so does a result longer than {@link SKILL_INVOCATION_LIMITS.renderedMaxChars} (checked while
112
120
  * substituting, before the long string is built).
113
121
  */
114
- export function renderSkillBody(body, invocation, args, skillName) {
122
+ export function renderSkillBody(body, invocation, args, skillName, digest, skillsRoot = SKILLS_SANDBOX_ROOT) {
115
123
  checkSkillName(skillName);
124
+ checkDigest(digest);
125
+ const dir = skillSandboxDir(skillName, digest, skillsRoot);
116
126
  const all = trimmedArgs(args);
117
127
  const values = parseSkillArguments(all);
118
128
  const named = invocation.arguments ?? [];
@@ -125,7 +135,7 @@ export function renderSkillBody(body, invocation, args, skillName) {
125
135
  if (m === "\\$")
126
136
  return "$";
127
137
  if (m === "${CLAUDE_SKILL_DIR}")
128
- return `${SKILLS_SANDBOX_ROOT}/${skillName}`;
138
+ return dir;
129
139
  if (m === "$ARGUMENTS") {
130
140
  placeholder = true;
131
141
  return all;
@@ -173,14 +183,14 @@ const escapeAttr = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").repla
173
183
  */
174
184
  export function renderSkillInvocation(i) {
175
185
  const args = trimmedArgs(i.args);
176
- const body = renderSkillBody(i.body, i.invocation, args, i.skillName).replace(CLOSE_TAG_RE, "<\\/$1");
186
+ const body = renderSkillBody(i.body, i.invocation, args, i.skillName, i.digest).replace(CLOSE_TAG_RE, "<\\/$1");
177
187
  const parts = [];
178
188
  if (i.lead !== false) {
179
189
  parts.push(escapeTags(`The user invoked the skill "${i.name}" with /${i.name}${args === "" ? "" : ` ${args}`}. Follow its instructions for this request.`));
180
190
  }
181
191
  parts.push(`<skill_invocation name="${escapeAttr(i.name)}" version="${i.version}">\n${body}\n</skill_invocation>`);
182
192
  if (i.lines.files === "load") {
183
- parts.push(`Its files are not in the sandbox yet: call Skill with "${i.name}" to copy them to ${SKILLS_SANDBOX_ROOT}/${i.skillName}/ before running its scripts.`);
193
+ parts.push(`Its files are not in the sandbox yet: call Skill with "${i.name}" to copy them to ${skillSandboxDir(i.skillName, i.digest)}/ before running its scripts.`);
184
194
  }
185
195
  else if (i.lines.files === "unavailable") {
186
196
  parts.push("Its other files are not available in this conversation.");
package/dist/skill.d.ts CHANGED
@@ -30,12 +30,32 @@ export declare const SKILL_INVOCATION_LIMITS: {
30
30
  };
31
31
  /** 技能入口文件(包根目录,大小写敏感)。 */
32
32
  export declare const SKILL_ENTRY_FILE = "SKILL.md";
33
- /** 沙箱里放技能的根目录:每个技能在 `/skills/<name>/` 下(只读复制)。 */
33
+ /**
34
+ * The sandbox root for skills: each skill version is copied (read-only to commands) to
35
+ * `/skills/<name>@<digest>/` ({@link skillSandboxDir}).
36
+ */
34
37
  export declare const SKILLS_SANDBOX_ROOT = "/skills";
35
38
  /** 是否为合法的技能名(见文件头的规范说明)。 */
36
39
  export declare function isSkillName(s: unknown): s is string;
37
- /** 技能文件在沙箱里的路径:`/skills/<name>/<path>`。 */
38
- export declare function skillSandboxPath(name: string, path: string): string;
40
+ /**
41
+ * The digest of a skill version's file manifest: the first 12 hex digits of the sha256 of its
42
+ * files sorted by path (JavaScript string order), one `${path} ${size} ${sha256}\n` line each. Two
43
+ * versions with the same files get the same digest, so their sandbox directories coincide; any
44
+ * other change gives a different directory, so two versions of one skill never overwrite each
45
+ * other in a shared file system.
46
+ */
47
+ export declare function skillDigest(files: {
48
+ path: string;
49
+ size: number;
50
+ sha256: string;
51
+ }[]): string;
52
+ /**
53
+ * A skill version's directory in the sandbox: `<root>/<name>@<digest>` ({@link skillDigest});
54
+ * `root` is the instance's skills root (`SandboxRoots.skills`, default `/skills`).
55
+ */
56
+ export declare function skillSandboxDir(name: string, digest: string, root?: string): string;
57
+ /** A skill file's path in the sandbox: `<root>/<name>@<digest>/<path>` ({@link skillSandboxDir}). */
58
+ export declare function skillSandboxPath(name: string, digest: string, path: string, root?: string): string;
39
59
  /** {@link parseSkillMd} 成功时的结果。 */
40
60
  export interface ParsedSkillMd {
41
61
  name: string;
package/dist/skill.js CHANGED
@@ -16,8 +16,9 @@
16
16
  * whose types are checked because the kernel uses them (`skillInvocation`, phase D). Matching the
17
17
  * directory name is not enforced: an uploaded zip's outer directory often has another name (GitHub's
18
18
  * `repo-main/`); the skill's name is always the frontmatter `name`, and its sandbox directory is
19
- * `/skills/<name>/`.
19
+ * `/skills/<name>@<digest>/` ({@link skillSandboxDir}, {@link skillDigest}).
20
20
  */
21
+ import { createHash } from "node:crypto";
21
22
  import { readFrontmatter } from "./frontmatter.js";
22
23
  import { hasControlChars } from "./model.js";
23
24
  import { validateSandboxPath } from "./sandbox.js";
@@ -54,7 +55,10 @@ export const SKILL_INVOCATION_LIMITS = {
54
55
  };
55
56
  /** 技能入口文件(包根目录,大小写敏感)。 */
56
57
  export const SKILL_ENTRY_FILE = "SKILL.md";
57
- /** 沙箱里放技能的根目录:每个技能在 `/skills/<name>/` 下(只读复制)。 */
58
+ /**
59
+ * The sandbox root for skills: each skill version is copied (read-only to commands) to
60
+ * `/skills/<name>@<digest>/` ({@link skillSandboxDir}).
61
+ */
58
62
  export const SKILLS_SANDBOX_ROOT = "/skills";
59
63
  const NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
60
64
  const XML_TAG_RE = /<\/?[A-Za-z][^<>]*>/;
@@ -63,9 +67,30 @@ const DRIVE_RE = /^[A-Za-z]:/;
63
67
  export function isSkillName(s) {
64
68
  return typeof s === "string" && s.length <= SKILL_LIMITS.nameMaxChars && NAME_RE.test(s);
65
69
  }
66
- /** 技能文件在沙箱里的路径:`/skills/<name>/<path>`。 */
67
- export function skillSandboxPath(name, path) {
68
- return `${SKILLS_SANDBOX_ROOT}/${name}/${path}`;
70
+ /**
71
+ * The digest of a skill version's file manifest: the first 12 hex digits of the sha256 of its
72
+ * files sorted by path (JavaScript string order), one `${path} ${size} ${sha256}\n` line each. Two
73
+ * versions with the same files get the same digest, so their sandbox directories coincide; any
74
+ * other change gives a different directory, so two versions of one skill never overwrite each
75
+ * other in a shared file system.
76
+ */
77
+ export function skillDigest(files) {
78
+ const lines = [...files]
79
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
80
+ .map((f) => `${f.path} ${f.size} ${f.sha256}\n`)
81
+ .join("");
82
+ return createHash("sha256").update(lines).digest("hex").slice(0, 12);
83
+ }
84
+ /**
85
+ * A skill version's directory in the sandbox: `<root>/<name>@<digest>` ({@link skillDigest});
86
+ * `root` is the instance's skills root (`SandboxRoots.skills`, default `/skills`).
87
+ */
88
+ export function skillSandboxDir(name, digest, root = SKILLS_SANDBOX_ROOT) {
89
+ return `${root}/${name}@${digest}`;
90
+ }
91
+ /** A skill file's path in the sandbox: `<root>/<name>@<digest>/<path>` ({@link skillSandboxDir}). */
92
+ export function skillSandboxPath(name, digest, path, root = SKILLS_SANDBOX_ROOT) {
93
+ return `${skillSandboxDir(name, digest, root)}/${path}`;
69
94
  }
70
95
  const chars = (s) => [...s].length;
71
96
  /**
@@ -179,7 +204,7 @@ function pathProblem(p) {
179
204
  return "path must not contain '.' or '..' segments";
180
205
  }
181
206
  // 再按沙箱路径规则核一遍(百分号编码的 `..` 等)
182
- const errs = validateSandboxPath(skillSandboxPath("skill", p));
207
+ const errs = validateSandboxPath(skillSandboxPath("skill", "000000000000", p));
183
208
  return errs[0] ?? null;
184
209
  }
185
210
  /**
@@ -0,0 +1,39 @@
1
+ import { type ParsedTheme } from "./theme.js";
2
+ /**
3
+ * Parses a logo SVG (UTF-8, ≤ {@link THEME_LIMITS}`.svgBytes`) with a strict, namespace-aware
4
+ * XML parser and re-serializes it. The root must be an `svg` element in the SVG namespace with a
5
+ * numeric `viewBox`; its `width`, `height` and `class` are dropped. Rejected: a DOCTYPE (and so
6
+ * any entity declaration), processing instructions, a non-UTF-8 encoding, elements outside the
7
+ * SVG allowlist (`script`, `foreignObject`, `style`, …) or in the XHTML namespace, `style` and
8
+ * `on*` attributes, `href` / `xlink:href` not starting with `#`, `javascript:` / `vbscript:` in
9
+ * any value, quotes or a backslash in attribute values, any function other than `url(#id)`, colors
10
+ * (`rgb`, `rgba`, `hsl`, `hsla`) and transforms (`translate`, `rotate`, `scale`, `matrix`,
11
+ * `skewX`, `skewY`), a viewBox longer than 128 characters, and animation of `href`, `style` or event
12
+ * handlers. Comments, the XML declaration and elements / attributes in other namespaces (editor
13
+ * metadata) are dropped; CDATA becomes escaped text. Never throws.
14
+ */
15
+ export declare function sanitizeThemeSvg(bytes: Uint8Array): {
16
+ svg: string;
17
+ } | {
18
+ error: string;
19
+ };
20
+ /** A woff2 font: the `wOF2` signature and at most {@link THEME_LIMITS}`.fontBytes`. */
21
+ export declare function checkWoff2(bytes: Uint8Array): string | undefined;
22
+ /**
23
+ * A PNG logo: the PNG signature, an `IHDR` first chunk with a height of at least
24
+ * {@link THEME_LIMITS}`.pngMinHeight` pixels, and at most {@link THEME_LIMITS}`.pngBytes`.
25
+ */
26
+ export declare function checkPng(bytes: Uint8Array): string | undefined;
27
+ /**
28
+ * Resolves and checks the asset files of a parsed theme: each `fonts[].file` ({@link checkWoff2})
29
+ * and `logo.mark` / `logo.favicon` (`.svg` through {@link sanitizeThemeSvg}, `.png` through
30
+ * {@link checkPng}); the favicon must be square (SVG viewBox or PNG width = height). `files` holds the plugin's files keyed by their path without a leading
31
+ * `./`; the returned `assets` (the sanitized SVG bytes, the other files unchanged) use the same
32
+ * keys. Errors are `<field>: <reason>`, English; the total input size of the theme's distinct
33
+ * assets must stay within {@link THEME_LIMITS}`.assetsBytes`. That limit is per plugin, so a
34
+ * caller reading several themes also checks the sum over all of them (distinct paths).
35
+ */
36
+ export declare function validateThemeAssets(theme: ParsedTheme, files: Map<string, Uint8Array>): {
37
+ assets: Map<string, Uint8Array>;
38
+ errors: string[];
39
+ };