@eum-agent/skill-management 0.0.0-stage → 1.0.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.
- package/dist/index.js +3155 -0
- package/package.json +48 -3
- package/ui/ui.js +1804 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,3155 @@
|
|
|
1
|
+
import { chmodSync, closeSync, constants, copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
5
|
+
import { basename, dirname, isAbsolute, join, normalize, posix, relative, resolve, sep, win32 } from "node:path";
|
|
6
|
+
import { unzipSync } from "fflate";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { parse, stringify } from "yaml";
|
|
9
|
+
//#region src/tool-names.ts
|
|
10
|
+
/** Canonical names shared by tool registration and browser presentation. */
|
|
11
|
+
const TOOL_NAMES = [
|
|
12
|
+
"skill_read",
|
|
13
|
+
"skill_write",
|
|
14
|
+
"skill_install",
|
|
15
|
+
"skill_uninstall",
|
|
16
|
+
"skill_set_preload"
|
|
17
|
+
];
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region src/fence.ts
|
|
20
|
+
const FENCE_SERVICE = "fence";
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/guidance.ts
|
|
23
|
+
const GUIDANCE = {
|
|
24
|
+
title: "Skills",
|
|
25
|
+
entries: [
|
|
26
|
+
{
|
|
27
|
+
tools: ["skill_read"],
|
|
28
|
+
text: "`skill_read` reads a listed skill. When a skill matches what you are about to do, read it before starting and follow it."
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
tools: ["skill_install"],
|
|
32
|
+
text: "`skill_install` installs a skill from a skill site, GitHub or a local path. Use it only when the person asks for that skill or agrees when you propose it; the person is asked before anything is installed."
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
tools: ["skill_uninstall"],
|
|
36
|
+
text: "`skill_uninstall` removes an installed skill. Use it only when the person asks."
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
tools: ["skill_write"],
|
|
40
|
+
text: "`skill_write` records a procedure as a skill. Use it only when the person asks, or agrees when you propose one."
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
tools: ["skill_set_preload"],
|
|
44
|
+
text: "`skill_set_preload` changes which installed global or own-agent skills this agent loads by default. Use it when asked to adjust this agent’s skills."
|
|
45
|
+
}
|
|
46
|
+
]
|
|
47
|
+
};
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region src/install/http.ts
|
|
50
|
+
const NETWORK_SERVICE = "network";
|
|
51
|
+
/** A failure whose message is fit to show a person as it is. */
|
|
52
|
+
var InstallError = class extends Error {
|
|
53
|
+
name = "InstallError";
|
|
54
|
+
};
|
|
55
|
+
const USER_AGENT = "yaoguang-skill-install";
|
|
56
|
+
/** How long a search may take. */
|
|
57
|
+
const SEARCH_TIMEOUT_MS = 1e4;
|
|
58
|
+
/** How long a download may go without a new byte. */
|
|
59
|
+
const IDLE_TIMEOUT_MS = 3e4;
|
|
60
|
+
/** Seconds until a rate limit lifts, from whichever header says so. */
|
|
61
|
+
function retryAfter(headers) {
|
|
62
|
+
for (const name of ["retry-after", "ratelimit-reset"]) {
|
|
63
|
+
const value = Number(headers.get(name));
|
|
64
|
+
if (Number.isFinite(value) && value > 0) return Math.ceil(value);
|
|
65
|
+
}
|
|
66
|
+
const reset = Number(headers.get("x-ratelimit-reset"));
|
|
67
|
+
if (Number.isFinite(reset) && reset > 0) {
|
|
68
|
+
const seconds = Math.ceil(reset - Date.now() / 1e3);
|
|
69
|
+
if (seconds > 0) return seconds;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** The sentence for a response that is not a success. */
|
|
73
|
+
function failureOf(label, response, what = "这个技能") {
|
|
74
|
+
const status = response.status;
|
|
75
|
+
if (status === 404) return new InstallError(`找不到${what}(${label})`);
|
|
76
|
+
if (status === 429) {
|
|
77
|
+
const wait = retryAfter(response.headers);
|
|
78
|
+
return new InstallError(wait === void 0 ? `${label} 限流,请稍后重试` : `${label} 限流,约 ${wait} 秒后可重试`);
|
|
79
|
+
}
|
|
80
|
+
if (status === 401 || status === 403) return new InstallError("这个技能需要登录才能下载,本版本暂不支持");
|
|
81
|
+
return new InstallError(`${label} 返回了错误(HTTP ${status})`);
|
|
82
|
+
}
|
|
83
|
+
function unreachable(label, error) {
|
|
84
|
+
if (error instanceof InstallError) return error;
|
|
85
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return new InstallError(`${label} 响应超时`);
|
|
86
|
+
return new InstallError(`连不上 ${label},请检查网络或代理`);
|
|
87
|
+
}
|
|
88
|
+
function createHttp(fetch) {
|
|
89
|
+
const headers = { "user-agent": USER_AGENT };
|
|
90
|
+
return {
|
|
91
|
+
async json(url, label, signal) {
|
|
92
|
+
const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
|
|
93
|
+
let response;
|
|
94
|
+
try {
|
|
95
|
+
response = await fetch(url, {
|
|
96
|
+
headers: {
|
|
97
|
+
...headers,
|
|
98
|
+
accept: "application/json"
|
|
99
|
+
},
|
|
100
|
+
signal: signal === void 0 ? timeout : AbortSignal.any([signal, timeout])
|
|
101
|
+
});
|
|
102
|
+
} catch (error) {
|
|
103
|
+
throw unreachable(label, error);
|
|
104
|
+
}
|
|
105
|
+
if (!response.ok) throw failureOf(label, response);
|
|
106
|
+
try {
|
|
107
|
+
return await response.json();
|
|
108
|
+
} catch {
|
|
109
|
+
throw new InstallError(`${label} 返回的内容无法识别`);
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
async bytes(url, label, options = {}) {
|
|
113
|
+
const idle = new AbortController();
|
|
114
|
+
let timer = setTimeout(() => idle.abort(new DOMException("idle", "TimeoutError")), IDLE_TIMEOUT_MS);
|
|
115
|
+
const bump = () => {
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
timer = setTimeout(() => idle.abort(new DOMException("idle", "TimeoutError")), IDLE_TIMEOUT_MS);
|
|
118
|
+
};
|
|
119
|
+
const signal = options.signal === void 0 ? idle.signal : AbortSignal.any([options.signal, idle.signal]);
|
|
120
|
+
try {
|
|
121
|
+
let response;
|
|
122
|
+
try {
|
|
123
|
+
response = await fetch(url, {
|
|
124
|
+
headers,
|
|
125
|
+
signal,
|
|
126
|
+
redirect: "follow"
|
|
127
|
+
});
|
|
128
|
+
} catch (error) {
|
|
129
|
+
throw unreachable(label, error);
|
|
130
|
+
}
|
|
131
|
+
if (!response.ok && !(options.pass ?? []).includes(response.status)) throw failureOf(label, response, options.what);
|
|
132
|
+
const chunks = [];
|
|
133
|
+
let size = 0;
|
|
134
|
+
try {
|
|
135
|
+
const reader = response.body?.getReader();
|
|
136
|
+
if (reader !== void 0) for (;;) {
|
|
137
|
+
const { done, value } = await reader.read();
|
|
138
|
+
if (done) break;
|
|
139
|
+
bump();
|
|
140
|
+
chunks.push(value);
|
|
141
|
+
size += value.byteLength;
|
|
142
|
+
}
|
|
143
|
+
} catch (error) {
|
|
144
|
+
throw unreachable(label, error);
|
|
145
|
+
}
|
|
146
|
+
const body = new Uint8Array(size);
|
|
147
|
+
let offset = 0;
|
|
148
|
+
for (const chunk of chunks) {
|
|
149
|
+
body.set(chunk, offset);
|
|
150
|
+
offset += chunk.byteLength;
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
response,
|
|
154
|
+
body
|
|
155
|
+
};
|
|
156
|
+
} finally {
|
|
157
|
+
clearTimeout(timer);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
//#region src/install/suggest-id.ts
|
|
164
|
+
/**
|
|
165
|
+
* The name a candidate is offered under: the first of `SKILL.md`'s own
|
|
166
|
+
* `name`, the directory it is in and the archive or repository it came in
|
|
167
|
+
* that yields anything, made into a name the Agent Skills specification
|
|
168
|
+
* accepts — lowercase, `a-z0-9` runs joined by single hyphens, at most 64
|
|
169
|
+
* characters. Empty when none of them yields a letter or a digit; the person
|
|
170
|
+
* then types one.
|
|
171
|
+
*/
|
|
172
|
+
/** The specification's name rule, the same one the host checks. */
|
|
173
|
+
const SKILL_NAME$1 = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
174
|
+
function isStandardName$1(name) {
|
|
175
|
+
return name.length <= 64 && SKILL_NAME$1.test(name);
|
|
176
|
+
}
|
|
177
|
+
function toName(raw) {
|
|
178
|
+
return raw.replace(/\.zip$/i, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64).replace(/-+$/, "");
|
|
179
|
+
}
|
|
180
|
+
function suggestId(sources) {
|
|
181
|
+
for (const source of sources) {
|
|
182
|
+
if (source === void 0) continue;
|
|
183
|
+
const name = toName(source);
|
|
184
|
+
if (name !== "") return name;
|
|
185
|
+
}
|
|
186
|
+
return "";
|
|
187
|
+
}
|
|
188
|
+
//#endregion
|
|
189
|
+
//#region src/install/scan.ts
|
|
190
|
+
/**
|
|
191
|
+
* What a fetched tree holds: a directory with a `SKILL.md` is one candidate.
|
|
192
|
+
* Discovery checks the root, then direct children of its `skills/` directory
|
|
193
|
+
* or the root itself. It never searches deeper for candidates. Each is read the way
|
|
194
|
+
* loading would read it (through the host's `skills.inspect`) so the
|
|
195
|
+
* preview says what an install would actually produce.
|
|
196
|
+
*
|
|
197
|
+
* A candidate holding a symbolic link, or anything that is not a file or a
|
|
198
|
+
* directory, is not offered: it goes to the failures with the entry named.
|
|
199
|
+
* The host refuses the same at install; saying so here is for the person.
|
|
200
|
+
*/
|
|
201
|
+
/** Not skill content, and not worth walking. */
|
|
202
|
+
const SKIPPED = /* @__PURE__ */ new Set([
|
|
203
|
+
".git",
|
|
204
|
+
"node_modules",
|
|
205
|
+
"__pycache__"
|
|
206
|
+
]);
|
|
207
|
+
const SCRIPT = /\.(sh|bash|zsh|py|js|mjs|cjs|ts|rb|pl|ps1|bat|cmd)$/i;
|
|
208
|
+
/**
|
|
209
|
+
* Finds a single skill at `root`, otherwise only immediate child skills of
|
|
210
|
+
* `root/skills` when that directory exists, or of `root` when it does not.
|
|
211
|
+
* Returns logical slash-separated identifiers relative to `root`, with `.` for the root skill.
|
|
212
|
+
* Raw entry names are preserved; filesystem joins remain host-native. Discovery
|
|
213
|
+
* never descends through categories or fixtures and never follows symlinks.
|
|
214
|
+
* Archive callers strip their single outer wrapper before calling this.
|
|
215
|
+
*/
|
|
216
|
+
function findSkillDirectories(root) {
|
|
217
|
+
const namesAt = (directory) => {
|
|
218
|
+
try {
|
|
219
|
+
return readdirSync(directory);
|
|
220
|
+
} catch {
|
|
221
|
+
return [];
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
const names = namesAt(root);
|
|
225
|
+
if (names.includes("SKILL.md")) return ["."];
|
|
226
|
+
const parent = lstatSync(join(root, "skills"), { throwIfNoEntry: false })?.isDirectory() === true ? "skills" : ".";
|
|
227
|
+
return [...parent === "." ? names : namesAt(join(root, parent))].sort().flatMap((name) => {
|
|
228
|
+
if (SKIPPED.has(name)) return [];
|
|
229
|
+
const key = parent === "." ? name : `${parent}/${name}`;
|
|
230
|
+
const directory = join(root, key);
|
|
231
|
+
return lstatSync(directory, { throwIfNoEntry: false })?.isDirectory() === true && namesAt(directory).includes("SKILL.md") ? [key] : [];
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
function walk$1(directory) {
|
|
235
|
+
const files = [];
|
|
236
|
+
const scripts = [];
|
|
237
|
+
const stack = [""];
|
|
238
|
+
while (stack.length > 0) {
|
|
239
|
+
const here = stack.pop();
|
|
240
|
+
for (const name of readdirSync(join(directory, here)).sort()) {
|
|
241
|
+
const rel = here === "" ? name : `${here}/${name}`;
|
|
242
|
+
const stat = lstatSync(join(directory, rel));
|
|
243
|
+
if (stat.isSymbolicLink()) return {
|
|
244
|
+
ok: false,
|
|
245
|
+
reason: `包里有符号链接:${rel}`
|
|
246
|
+
};
|
|
247
|
+
if (stat.isDirectory()) stack.push(rel);
|
|
248
|
+
else if (stat.isFile()) {
|
|
249
|
+
files.push({
|
|
250
|
+
path: rel,
|
|
251
|
+
bytes: stat.size
|
|
252
|
+
});
|
|
253
|
+
if (SCRIPT.test(name) || (stat.mode & 73) !== 0) scripts.push(rel);
|
|
254
|
+
} else return {
|
|
255
|
+
ok: false,
|
|
256
|
+
reason: `包里有不是普通文件的项:${rel}`
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
files.sort((a, b) => a.path.localeCompare(b.path));
|
|
261
|
+
return {
|
|
262
|
+
ok: true,
|
|
263
|
+
files,
|
|
264
|
+
scripts: scripts.sort()
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
/** The candidates and failures of one fetched tree, for the agent `target`
|
|
268
|
+
* names (its two layers decide the conflicts). */
|
|
269
|
+
function scan(tree, skills, target) {
|
|
270
|
+
const taken = skills.layerIds(target);
|
|
271
|
+
const candidates = [];
|
|
272
|
+
const failures = [];
|
|
273
|
+
const directories = findSkillDirectories(tree.root);
|
|
274
|
+
if (directories.length === 0) failures.push({
|
|
275
|
+
path: ".",
|
|
276
|
+
reason: "找不到 SKILL.md"
|
|
277
|
+
});
|
|
278
|
+
for (const key of directories) {
|
|
279
|
+
const directory = key === "." ? tree.root : join(tree.root, key);
|
|
280
|
+
const walked = walk$1(directory);
|
|
281
|
+
if (!walked.ok) {
|
|
282
|
+
failures.push({
|
|
283
|
+
path: key,
|
|
284
|
+
reason: walked.reason
|
|
285
|
+
});
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
const dirName = key === "." ? tree.fallbackName ?? basename(tree.root) : basename(key);
|
|
289
|
+
const first = skills.inspect(directory, "skill");
|
|
290
|
+
if (!first.ok) {
|
|
291
|
+
failures.push({
|
|
292
|
+
path: key,
|
|
293
|
+
reason: first.message
|
|
294
|
+
});
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
const suggestedId = suggestId([
|
|
298
|
+
first.declaredName,
|
|
299
|
+
dirName,
|
|
300
|
+
tree.fallbackName
|
|
301
|
+
]);
|
|
302
|
+
const inspected = suggestedId === "" ? first : skills.inspect(directory, suggestedId);
|
|
303
|
+
if (!inspected.ok) {
|
|
304
|
+
failures.push({
|
|
305
|
+
path: key,
|
|
306
|
+
reason: inspected.message
|
|
307
|
+
});
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
candidates.push({
|
|
311
|
+
key,
|
|
312
|
+
suggestedId,
|
|
313
|
+
description: inspected.description,
|
|
314
|
+
files: walked.files,
|
|
315
|
+
bytes: walked.files.reduce((sum, one) => sum + one.bytes, 0),
|
|
316
|
+
scripts: walked.scripts,
|
|
317
|
+
conflicts: {
|
|
318
|
+
agent: suggestedId !== "" && taken.agent.includes(suggestedId),
|
|
319
|
+
global: suggestedId !== "" && taken.global.includes(suggestedId)
|
|
320
|
+
},
|
|
321
|
+
issues: inspected.issues.filter((issue) => issue.code !== "dir-invalid")
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
candidates,
|
|
326
|
+
failures
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
//#endregion
|
|
330
|
+
//#region src/install/zip.ts
|
|
331
|
+
/**
|
|
332
|
+
* A zip archive, unpacked into a directory — refusing any entry that would
|
|
333
|
+
* land outside it and any symbolic link, and keeping each file's executable
|
|
334
|
+
* bit.
|
|
335
|
+
*
|
|
336
|
+
* `fflate` inflates; the central directory is read here, because it is the
|
|
337
|
+
* only place a zip keeps what an entry *is* (a link, a directory, a file and
|
|
338
|
+
* its mode) and `fflate` does not hand that over. The archive comment is read
|
|
339
|
+
* the same way: GitHub puts the commit an archive was cut from there.
|
|
340
|
+
*/
|
|
341
|
+
const EOCD = 101010256;
|
|
342
|
+
const CENTRAL = 33639248;
|
|
343
|
+
function view(bytes) {
|
|
344
|
+
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
345
|
+
}
|
|
346
|
+
/** Where the end-of-central-directory record starts, searching back over
|
|
347
|
+
* the longest comment a zip can carry. */
|
|
348
|
+
function endRecord(bytes) {
|
|
349
|
+
const data = view(bytes);
|
|
350
|
+
const floor = Math.max(0, bytes.byteLength - 22 - 65535);
|
|
351
|
+
for (let at = bytes.byteLength - 22; at >= floor; at -= 1) if (data.getUint32(at, true) === EOCD) return at;
|
|
352
|
+
throw new InstallError("这个包无法解压");
|
|
353
|
+
}
|
|
354
|
+
/** The archive comment, as text. */
|
|
355
|
+
function zipComment(bytes) {
|
|
356
|
+
const at = endRecord(bytes);
|
|
357
|
+
const length = view(bytes).getUint16(at + 20, true);
|
|
358
|
+
return new TextDecoder().decode(bytes.subarray(at + 22, at + 22 + length));
|
|
359
|
+
}
|
|
360
|
+
function entries(bytes) {
|
|
361
|
+
const data = view(bytes);
|
|
362
|
+
const end = endRecord(bytes);
|
|
363
|
+
const count = data.getUint16(end + 10, true);
|
|
364
|
+
let at = data.getUint32(end + 16, true);
|
|
365
|
+
const found = [];
|
|
366
|
+
const decoder = new TextDecoder();
|
|
367
|
+
for (let index = 0; index < count; index += 1) {
|
|
368
|
+
if (at + 46 > bytes.byteLength || data.getUint32(at, true) !== CENTRAL) throw new InstallError("这个包无法解压");
|
|
369
|
+
const madeBy = data.getUint16(at + 4, true) >> 8;
|
|
370
|
+
const nameLength = data.getUint16(at + 28, true);
|
|
371
|
+
const extraLength = data.getUint16(at + 30, true);
|
|
372
|
+
const commentLength = data.getUint16(at + 32, true);
|
|
373
|
+
const external = data.getUint32(at + 38, true);
|
|
374
|
+
const name = decoder.decode(bytes.subarray(at + 46, at + 46 + nameLength));
|
|
375
|
+
const mode = madeBy === 3 ? external >>> 16 : void 0;
|
|
376
|
+
const type = mode === void 0 ? 0 : mode & 61440;
|
|
377
|
+
found.push({
|
|
378
|
+
name,
|
|
379
|
+
directory: name.endsWith("/") || type === 16384 || (external & 16) !== 0,
|
|
380
|
+
link: type === 40960,
|
|
381
|
+
mode: mode === void 0 ? void 0 : mode & 511
|
|
382
|
+
});
|
|
383
|
+
at += 46 + nameLength + extraLength + commentLength;
|
|
384
|
+
}
|
|
385
|
+
return found;
|
|
386
|
+
}
|
|
387
|
+
/** The path an entry lands at, relative, or `undefined` when it would land
|
|
388
|
+
* anywhere but inside the target. */
|
|
389
|
+
function safeRelative(name) {
|
|
390
|
+
if (name.includes("\\") || name.startsWith("/") || /^[A-Za-z]:/.test(name)) return void 0;
|
|
391
|
+
const clean = normalize(name.replace(/\/+$/, ""));
|
|
392
|
+
if (clean === "." || clean === "") return "";
|
|
393
|
+
if (clean.split(sep).some((part) => part === "..")) return void 0;
|
|
394
|
+
return clean;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Unpacks `bytes` into `target`, which must exist. With every entry under one
|
|
398
|
+
* top-level directory (a GitHub archive's `repo-<commit>/`), that directory
|
|
399
|
+
* is stripped. Refuses the whole archive at the first entry that is a link
|
|
400
|
+
* or that escapes, naming it; nothing is written before every entry has been
|
|
401
|
+
* checked. Answers the stripped directory's name, when one was stripped.
|
|
402
|
+
*/
|
|
403
|
+
function unzipInto(bytes, target) {
|
|
404
|
+
const list = entries(bytes);
|
|
405
|
+
for (const entry of list) {
|
|
406
|
+
if (entry.link) throw new InstallError(`包里有符号链接:${entry.name}`);
|
|
407
|
+
if (safeRelative(entry.name) === void 0) throw new InstallError(`包里有指向包外的路径:${entry.name}`);
|
|
408
|
+
}
|
|
409
|
+
const tops = new Set(list.map((entry) => entry.name.split("/")[0]));
|
|
410
|
+
const [only] = tops;
|
|
411
|
+
const strip = tops.size === 1 && only !== void 0 && list.every((entry) => entry.name.startsWith(`${only}/`)) ? `${only}/` : "";
|
|
412
|
+
let files;
|
|
413
|
+
try {
|
|
414
|
+
files = unzipSync(bytes);
|
|
415
|
+
} catch {
|
|
416
|
+
throw new InstallError("这个包无法解压");
|
|
417
|
+
}
|
|
418
|
+
const modes = new Map(list.map((entry) => [entry.name, entry]));
|
|
419
|
+
for (const entry of list) {
|
|
420
|
+
if (!entry.directory) continue;
|
|
421
|
+
const rel = safeRelative(entry.name.slice(strip.length));
|
|
422
|
+
if (rel) mkdirSync(join(target, rel), { recursive: true });
|
|
423
|
+
}
|
|
424
|
+
for (const [name, content] of Object.entries(files)) {
|
|
425
|
+
const entry = modes.get(name);
|
|
426
|
+
if (entry?.directory === true || name.endsWith("/")) continue;
|
|
427
|
+
const rel = safeRelative(name.slice(strip.length));
|
|
428
|
+
if (rel === void 0) throw new InstallError(`包里有指向包外的路径:${name}`);
|
|
429
|
+
if (rel === "") continue;
|
|
430
|
+
const path = join(target, rel);
|
|
431
|
+
mkdirSync(join(path, ".."), { recursive: true });
|
|
432
|
+
writeFileSync(path, content);
|
|
433
|
+
if (entry?.mode !== void 0 && (entry.mode & 73) !== 0) chmodSync(path, entry.mode | 384);
|
|
434
|
+
}
|
|
435
|
+
return strip === "" ? {} : { top: strip.slice(0, -1) };
|
|
436
|
+
}
|
|
437
|
+
//#endregion
|
|
438
|
+
//#region src/install/sources/staging.ts
|
|
439
|
+
/**
|
|
440
|
+
* Where a fetch unpacks: one fresh directory under the system's temporary
|
|
441
|
+
* directory, owned by the preview that asked for it and removed with it.
|
|
442
|
+
*/
|
|
443
|
+
function scratch$1() {
|
|
444
|
+
const path = mkdtempSync(join(realpathSync(tmpdir()), "yaoguang-skill-"));
|
|
445
|
+
return {
|
|
446
|
+
path,
|
|
447
|
+
dispose: () => rmSync(path, {
|
|
448
|
+
recursive: true,
|
|
449
|
+
force: true
|
|
450
|
+
})
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
//#endregion
|
|
454
|
+
//#region src/install/sources/github.ts
|
|
455
|
+
/**
|
|
456
|
+
* A public GitHub repository, fetched as the archive GitHub cuts for a ref
|
|
457
|
+
* (`github.com/<owner>/<repo>/archive/<ref>.zip`) rather than through the
|
|
458
|
+
* API: the archive is not counted against the anonymous API's hourly limit,
|
|
459
|
+
* and it carries every file, binaries included. The commit it was cut from
|
|
460
|
+
* is the archive's comment.
|
|
461
|
+
*/
|
|
462
|
+
function admitSegment(segment) {
|
|
463
|
+
if (segment === "" || segment === "." || segment === ".." || /[/\\\0]/.test(segment)) throw new InstallError("Invalid path segment in GitHub address");
|
|
464
|
+
}
|
|
465
|
+
function admitAddress(address) {
|
|
466
|
+
for (const identity of [address.owner, address.repo]) {
|
|
467
|
+
admitSegment(identity);
|
|
468
|
+
if (!/^[\w.-]+$/.test(identity)) throw new InstallError("Invalid GitHub repository identity");
|
|
469
|
+
}
|
|
470
|
+
for (const segment of address.rest) admitSegment(segment);
|
|
471
|
+
return address;
|
|
472
|
+
}
|
|
473
|
+
function decodeSegment(segment) {
|
|
474
|
+
try {
|
|
475
|
+
return decodeURIComponent(segment);
|
|
476
|
+
} catch {
|
|
477
|
+
throw new InstallError("Invalid percent encoding in GitHub address");
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
/** Reads a GitHub URL or `owner/repo`, decoding each segment once.
|
|
481
|
+
* Throws InstallError for malformed encoding or unsafe repository/path segments. */
|
|
482
|
+
function parseGitHub(input) {
|
|
483
|
+
const withoutScheme = input.trim().replace(/\/+$/, "").replace(/^https?:\/\//i, "");
|
|
484
|
+
const host = /^([^/]+)\//.exec(withoutScheme)?.[1] ?? "";
|
|
485
|
+
if (host.includes(".") && !/^(www\.)?github\.com$/i.test(host)) throw new InstallError("只支持 github.com 上的仓库地址");
|
|
486
|
+
const [owner, rawRepo, marker, ...rest] = withoutScheme.replace(/^(www\.)?github\.com\//i, "").split("/").map(decodeSegment);
|
|
487
|
+
const repo = rawRepo?.replace(/\.git$/i, "");
|
|
488
|
+
const name = /^[\w.-]+$/;
|
|
489
|
+
if (owner === void 0 || repo === void 0 || !name.test(owner) || !name.test(repo)) throw new InstallError("认不出这个地址,请填 https://github.com/<owner>/<repo>,可带 /tree/<分支>/<目录>");
|
|
490
|
+
if (marker === void 0) return admitAddress({
|
|
491
|
+
owner,
|
|
492
|
+
repo,
|
|
493
|
+
rest: []
|
|
494
|
+
});
|
|
495
|
+
if (marker !== "tree" && marker !== "blob") throw new InstallError("认不出这个地址,请填 https://github.com/<owner>/<repo>,可带 /tree/<分支>/<目录>");
|
|
496
|
+
for (const segment of rest) admitSegment(segment);
|
|
497
|
+
return admitAddress({
|
|
498
|
+
owner,
|
|
499
|
+
repo,
|
|
500
|
+
rest: marker === "blob" ? rest.slice(0, -1) : rest
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
/** Validates decoded address segments before HTTP, then downloads and unpacks the archive.
|
|
504
|
+
* Tries each ref/path split shortest ref first and refuses a directory outside its scratch tree. */
|
|
505
|
+
async function fetchRepository(http, address, label, signal) {
|
|
506
|
+
admitAddress(address);
|
|
507
|
+
const splits = address.rest.length === 0 ? [{
|
|
508
|
+
ref: "HEAD",
|
|
509
|
+
path: ""
|
|
510
|
+
}] : address.rest.map((_, index) => ({
|
|
511
|
+
ref: address.rest.slice(0, index + 1).join("/"),
|
|
512
|
+
path: address.rest.slice(index + 1).join("/")
|
|
513
|
+
}));
|
|
514
|
+
for (const { ref, path } of splits) {
|
|
515
|
+
const url = `https://github.com/${address.owner}/${address.repo}/archive/${ref.split("/").map(encodeURIComponent).join("/")}.zip`;
|
|
516
|
+
const { response, body } = await http.bytes(url, label, {
|
|
517
|
+
...signal === void 0 ? {} : { signal },
|
|
518
|
+
what: "这个仓库或分支",
|
|
519
|
+
pass: [404]
|
|
520
|
+
});
|
|
521
|
+
if (response.status === 404) continue;
|
|
522
|
+
const space = scratch$1();
|
|
523
|
+
try {
|
|
524
|
+
unzipInto(body, space.path);
|
|
525
|
+
const root = path === "" ? space.path : join(space.path, path);
|
|
526
|
+
const selected = relative(space.path, root);
|
|
527
|
+
if (isAbsolute(path) || /^[a-z]:/i.test(path) || isAbsolute(selected) || selected === ".." || selected.startsWith(`..${sep}`)) throw new InstallError("Selected GitHub directory is outside the downloaded repository");
|
|
528
|
+
if (!existsSync(root) || !statSync(root).isDirectory()) throw new InstallError(`仓库里没有这个目录:${path}`);
|
|
529
|
+
const comment = zipComment(body).trim();
|
|
530
|
+
const fromUrl = /\/([0-9a-f]{40})$/.exec(response.url)?.[1];
|
|
531
|
+
const commit = /^[0-9a-f]{40}$/.test(comment) ? comment : fromUrl;
|
|
532
|
+
return {
|
|
533
|
+
root,
|
|
534
|
+
ref,
|
|
535
|
+
...commit === void 0 ? {} : { commit },
|
|
536
|
+
path,
|
|
537
|
+
dispose: space.dispose
|
|
538
|
+
};
|
|
539
|
+
} catch (error) {
|
|
540
|
+
space.dispose();
|
|
541
|
+
throw error;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
throw new InstallError(`找不到这个仓库或分支(${label})`);
|
|
545
|
+
}
|
|
546
|
+
async function fetchGitHub(http, url, signal) {
|
|
547
|
+
const address = parseGitHub(url);
|
|
548
|
+
const repo = `${address.owner}/${address.repo}`;
|
|
549
|
+
const fetched = await fetchRepository(http, address, `GitHub · ${repo}`, signal);
|
|
550
|
+
const where = [fetched.ref === "HEAD" ? "" : `@${fetched.ref}`, fetched.path === "" ? "" : `/${fetched.path}`];
|
|
551
|
+
return {
|
|
552
|
+
root: fetched.root,
|
|
553
|
+
fallbackName: fetched.path === "" ? address.repo : fetched.path.split("/").pop() ?? address.repo,
|
|
554
|
+
label: `GitHub · ${repo}${where.join("")}`,
|
|
555
|
+
sourceKey: `github:${repo.toLowerCase()}`,
|
|
556
|
+
origin: (key, installedAt) => ({
|
|
557
|
+
kind: "github",
|
|
558
|
+
repo,
|
|
559
|
+
ref: fetched.ref,
|
|
560
|
+
...fetched.commit === void 0 ? {} : { commit: fetched.commit },
|
|
561
|
+
path: [fetched.path, key === "." ? "" : key].filter((one) => one !== "").join("/"),
|
|
562
|
+
installedAt
|
|
563
|
+
}),
|
|
564
|
+
dispose: fetched.dispose
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
//#endregion
|
|
568
|
+
//#region src/install/path-semantics.ts
|
|
569
|
+
/** Host path admission shared by local skill preview and installation. */
|
|
570
|
+
/**
|
|
571
|
+
* Accepts absolute POSIX paths or complete Windows drive/UNC roots on the stated host.
|
|
572
|
+
* Rejects NUL, implicit current-drive roots, drive-relative paths and device namespaces.
|
|
573
|
+
* Does not trim, normalize or resolve valid path text; filesystem identity is checked later.
|
|
574
|
+
*/
|
|
575
|
+
function isCompleteSkillSourcePath(path, platform = process.platform) {
|
|
576
|
+
if (path.includes("\0")) return false;
|
|
577
|
+
if (platform !== "win32") return posix.isAbsolute(path);
|
|
578
|
+
if (/^[a-z]:[\\/]/i.test(path)) return true;
|
|
579
|
+
const unc = /^[/\\]{2}([^/\\]+)[/\\]([^/\\]+)(?:[/\\]|$)/.exec(path);
|
|
580
|
+
return unc !== null && ![
|
|
581
|
+
".",
|
|
582
|
+
"..",
|
|
583
|
+
"?"
|
|
584
|
+
].includes(unc[1] ?? "") && ![".", ".."].includes(unc[2] ?? "");
|
|
585
|
+
}
|
|
586
|
+
//#endregion
|
|
587
|
+
//#region src/install/sources/local.ts
|
|
588
|
+
/**
|
|
589
|
+
* A directory or a `.zip` on the machine the gateway runs on. A directory is
|
|
590
|
+
* scanned where it is — the host copies from it at install and never writes
|
|
591
|
+
* to it; a zip is unpacked into a scratch directory first.
|
|
592
|
+
*/
|
|
593
|
+
/** Reads a complete host path without trimming it; invalid roots fail before filesystem access. */
|
|
594
|
+
function fetchLocal(path) {
|
|
595
|
+
if (!isCompleteSkillSourcePath(path)) throw new InstallError("请填写绝对路径");
|
|
596
|
+
let real;
|
|
597
|
+
try {
|
|
598
|
+
real = realpathSync(path);
|
|
599
|
+
} catch {
|
|
600
|
+
throw new InstallError(`路径不存在:${path}`);
|
|
601
|
+
}
|
|
602
|
+
const stat = statSync(real);
|
|
603
|
+
const base = {
|
|
604
|
+
label: `本地 · ${real}`,
|
|
605
|
+
sourceKey: `local:${real}`,
|
|
606
|
+
origin: (_key, installedAt) => ({
|
|
607
|
+
kind: "local",
|
|
608
|
+
path: real,
|
|
609
|
+
installedAt
|
|
610
|
+
})
|
|
611
|
+
};
|
|
612
|
+
if (stat.isDirectory()) return {
|
|
613
|
+
...base,
|
|
614
|
+
root: real,
|
|
615
|
+
fallbackName: basename(real),
|
|
616
|
+
dispose: () => {}
|
|
617
|
+
};
|
|
618
|
+
if (!stat.isFile() || !/\.zip$/i.test(real)) throw new InstallError("这个路径既不是目录也不是 zip 文件");
|
|
619
|
+
const space = scratch$1();
|
|
620
|
+
try {
|
|
621
|
+
const { top } = unzipInto(new Uint8Array(readFileSync(real)), space.path);
|
|
622
|
+
return {
|
|
623
|
+
...base,
|
|
624
|
+
root: space.path,
|
|
625
|
+
fallbackName: top ?? basename(real).replace(/\.zip$/i, ""),
|
|
626
|
+
dispose: space.dispose
|
|
627
|
+
};
|
|
628
|
+
} catch (error) {
|
|
629
|
+
space.dispose();
|
|
630
|
+
throw error;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
//#endregion
|
|
634
|
+
//#region src/install/sources/registries.ts
|
|
635
|
+
/**
|
|
636
|
+
* The three skill sites: searching each, and fetching one skill from it.
|
|
637
|
+
*
|
|
638
|
+
* - **ClawHub** (`clawhub.ai`): a slug is its publisher's, so a download
|
|
639
|
+
* names the publisher (`ownerHandle`); without one, a slug several
|
|
640
|
+
* publishers use answers 409. A package that lives on GitHub comes back as
|
|
641
|
+
* JSON pointing there, and is fetched from there — still recorded as
|
|
642
|
+
* ClawHub's, because ClawHub is where the person chose it.
|
|
643
|
+
* - **Tencent SkillHub** (`api.skillhub.cn`): ClawHub's search and download
|
|
644
|
+
* paths without its discovery document; a download redirects to Tencent's
|
|
645
|
+
* object storage. Results marked `enterprise` need a key this build does
|
|
646
|
+
* not hold, and are offered as needing sign-in.
|
|
647
|
+
* - **skills.sh**: search only, through the anonymous endpoint its own
|
|
648
|
+
* command line uses. It names a GitHub repository and a skill, and the
|
|
649
|
+
* skill is fetched from GitHub: the site's own snapshot leaves binary files
|
|
650
|
+
* out.
|
|
651
|
+
*/
|
|
652
|
+
const REGISTRY_LABEL = {
|
|
653
|
+
clawhub: "ClawHub",
|
|
654
|
+
"tencent-skillhub": "腾讯 SkillHub",
|
|
655
|
+
"skills-sh": "skills.sh"
|
|
656
|
+
};
|
|
657
|
+
const LIMIT = 30;
|
|
658
|
+
function record(value) {
|
|
659
|
+
return typeof value === "object" && value !== null ? value : {};
|
|
660
|
+
}
|
|
661
|
+
function text(value) {
|
|
662
|
+
return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
663
|
+
}
|
|
664
|
+
function list(value) {
|
|
665
|
+
return Array.isArray(value) ? value : [];
|
|
666
|
+
}
|
|
667
|
+
/** Keeps unavailable marketplace statistics absent instead of presenting them as zero. */
|
|
668
|
+
function statistics(one) {
|
|
669
|
+
const stats = record(one.stats);
|
|
670
|
+
const stars = stats.stars ?? one.stars;
|
|
671
|
+
const downloads = stats.downloads ?? one.downloads;
|
|
672
|
+
return {
|
|
673
|
+
...typeof stars === "number" && Number.isFinite(stars) && stars >= 0 ? { stars } : {},
|
|
674
|
+
...typeof downloads === "number" && Number.isFinite(downloads) && downloads >= 0 ? { downloads } : {}
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
async function search(http, registry, query, signal) {
|
|
678
|
+
const q = encodeURIComponent(query.trim());
|
|
679
|
+
const label = REGISTRY_LABEL[registry];
|
|
680
|
+
if (registry === "clawhub") return list(record(await http.json(`https://clawhub.ai/api/v1/search?q=${q}&limit=${LIMIT}`, label, signal)).results).flatMap((raw) => {
|
|
681
|
+
const one = record(raw);
|
|
682
|
+
const slug = text(one.slug);
|
|
683
|
+
if (slug === void 0) return [];
|
|
684
|
+
const owner = text(one.ownerHandle) ?? text(record(one.owner).handle);
|
|
685
|
+
const summary = text(one.summary);
|
|
686
|
+
const version = text(one.version) ?? text(record(one.version).version) ?? text(record(one.latestVersion).version);
|
|
687
|
+
return [{
|
|
688
|
+
...statistics(one),
|
|
689
|
+
name: text(one.displayName) ?? slug,
|
|
690
|
+
...summary === void 0 ? {} : { summary },
|
|
691
|
+
...owner === void 0 ? {} : { publisher: owner },
|
|
692
|
+
...version === void 0 ? {} : { version },
|
|
693
|
+
source: {
|
|
694
|
+
kind: "clawhub",
|
|
695
|
+
slug,
|
|
696
|
+
...owner === void 0 ? {} : { owner }
|
|
697
|
+
}
|
|
698
|
+
}];
|
|
699
|
+
});
|
|
700
|
+
if (registry === "tencent-skillhub") return list(record(await http.json(`https://api.skillhub.cn/api/v1/search?q=${q}&limit=${LIMIT}`, label, signal)).results).flatMap((raw) => {
|
|
701
|
+
const one = record(raw);
|
|
702
|
+
const slug = text(one.slug);
|
|
703
|
+
if (slug === void 0) return [];
|
|
704
|
+
const summary = text(one.summary) ?? text(one.description_zh) ?? text(one.description);
|
|
705
|
+
const version = text(one.version) ?? text(record(one.version).version) ?? text(record(one.latestVersion).version);
|
|
706
|
+
const publisher = text(record(one.publisher).name) ?? text(one.owner_name);
|
|
707
|
+
return [{
|
|
708
|
+
...statistics(one),
|
|
709
|
+
name: text(one.displayName) ?? text(one.name) ?? slug,
|
|
710
|
+
...summary === void 0 ? {} : { summary },
|
|
711
|
+
...publisher === void 0 ? {} : { publisher },
|
|
712
|
+
...version === void 0 ? {} : { version },
|
|
713
|
+
source: {
|
|
714
|
+
kind: "tencent-skillhub",
|
|
715
|
+
slug
|
|
716
|
+
},
|
|
717
|
+
...one.source === "enterprise" ? { needsLogin: true } : {}
|
|
718
|
+
}];
|
|
719
|
+
});
|
|
720
|
+
if (query.trim().length < 2) return [];
|
|
721
|
+
return list(record(await http.json(`https://skills.sh/api/search?q=${q}&limit=${LIMIT}`, label, signal)).skills).flatMap((raw) => {
|
|
722
|
+
const one = record(raw);
|
|
723
|
+
const repo = text(one.source);
|
|
724
|
+
const skill = text(one.skillId) ?? text(one.name);
|
|
725
|
+
if (repo === void 0 || skill === void 0 || !/^[\w.-]+\/[\w.-]+$/.test(repo)) return [];
|
|
726
|
+
return [{
|
|
727
|
+
...statistics(one),
|
|
728
|
+
name: text(one.name) ?? skill,
|
|
729
|
+
publisher: repo,
|
|
730
|
+
source: {
|
|
731
|
+
kind: "skills-sh",
|
|
732
|
+
repo,
|
|
733
|
+
skill
|
|
734
|
+
}
|
|
735
|
+
}];
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
/** A version the package states about itself, in the metadata file a site
|
|
739
|
+
* adds beside `SKILL.md`. */
|
|
740
|
+
function packagedVersion(root, file) {
|
|
741
|
+
try {
|
|
742
|
+
return text(record(JSON.parse(readFileSync(join(root, file), "utf8"))).version);
|
|
743
|
+
} catch {
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/** A GitHub address inside ClawHub's JSON answer, when it hands a package
|
|
748
|
+
* over to GitHub rather than serving it. */
|
|
749
|
+
function gitHubHandoff(body) {
|
|
750
|
+
try {
|
|
751
|
+
const answer = record(JSON.parse(new TextDecoder().decode(body)));
|
|
752
|
+
for (const value of [
|
|
753
|
+
answer.sourceUrl,
|
|
754
|
+
answer.url,
|
|
755
|
+
answer.githubUrl,
|
|
756
|
+
record(answer.source).url
|
|
757
|
+
]) {
|
|
758
|
+
const url = text(value);
|
|
759
|
+
if (url !== void 0 && /github\.com\//i.test(url)) return url;
|
|
760
|
+
}
|
|
761
|
+
} catch {
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
async function fetchClawHub(http, source, signal) {
|
|
766
|
+
const params = new URLSearchParams({ slug: source.slug });
|
|
767
|
+
if (source.owner !== void 0) params.set("ownerHandle", source.owner);
|
|
768
|
+
if (source.version !== void 0) params.set("version", source.version);
|
|
769
|
+
const label = `ClawHub · ${source.owner === void 0 ? "" : `${source.owner}/`}${source.slug}`;
|
|
770
|
+
const { response, body } = await http.bytes(`https://clawhub.ai/api/v1/download?${params}`, label, {
|
|
771
|
+
...signal === void 0 ? {} : { signal },
|
|
772
|
+
pass: [409]
|
|
773
|
+
});
|
|
774
|
+
if (response.status === 409) throw new InstallError("有多个发布者用这个名字,请带上发布者,或从搜索结果里选");
|
|
775
|
+
if ((response.headers.get("content-type") ?? "").includes("json")) {
|
|
776
|
+
const url = gitHubHandoff(body);
|
|
777
|
+
if (url === void 0) throw new InstallError(`${label} 返回的内容无法识别`);
|
|
778
|
+
const repo = await fetchRepository(http, parseGitHub(url), label, signal);
|
|
779
|
+
return {
|
|
780
|
+
root: repo.root,
|
|
781
|
+
fallbackName: source.slug,
|
|
782
|
+
label,
|
|
783
|
+
sourceKey: "clawhub",
|
|
784
|
+
origin: (_key, installedAt) => ({
|
|
785
|
+
kind: "clawhub",
|
|
786
|
+
slug: source.slug,
|
|
787
|
+
...source.owner === void 0 ? {} : { owner: source.owner },
|
|
788
|
+
...source.version === void 0 ? {} : { version: source.version },
|
|
789
|
+
installedAt
|
|
790
|
+
}),
|
|
791
|
+
dispose: repo.dispose
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
const space = scratch$1();
|
|
795
|
+
try {
|
|
796
|
+
unzipInto(body, space.path);
|
|
797
|
+
} catch (error) {
|
|
798
|
+
space.dispose();
|
|
799
|
+
throw error;
|
|
800
|
+
}
|
|
801
|
+
const version = source.version ?? packagedVersion(space.path, "_meta.json");
|
|
802
|
+
return {
|
|
803
|
+
root: space.path,
|
|
804
|
+
fallbackName: source.slug,
|
|
805
|
+
label: version === void 0 ? label : `${label} · ${version}`,
|
|
806
|
+
sourceKey: "clawhub",
|
|
807
|
+
origin: (_key, installedAt) => ({
|
|
808
|
+
kind: "clawhub",
|
|
809
|
+
slug: source.slug,
|
|
810
|
+
...source.owner === void 0 ? {} : { owner: source.owner },
|
|
811
|
+
...version === void 0 ? {} : { version },
|
|
812
|
+
installedAt
|
|
813
|
+
}),
|
|
814
|
+
dispose: space.dispose
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
async function fetchTencent(http, source, signal) {
|
|
818
|
+
const params = new URLSearchParams({ slug: source.slug });
|
|
819
|
+
if (source.version !== void 0) params.set("version", source.version);
|
|
820
|
+
const label = `腾讯 SkillHub · ${source.slug}`;
|
|
821
|
+
const { body } = await http.bytes(`https://api.skillhub.cn/api/v1/download?${params}`, label, { ...signal === void 0 ? {} : { signal } });
|
|
822
|
+
const space = scratch$1();
|
|
823
|
+
try {
|
|
824
|
+
unzipInto(body, space.path);
|
|
825
|
+
} catch (error) {
|
|
826
|
+
space.dispose();
|
|
827
|
+
throw error;
|
|
828
|
+
}
|
|
829
|
+
const version = source.version ?? packagedVersion(space.path, "_skillhub_meta.json");
|
|
830
|
+
return {
|
|
831
|
+
root: space.path,
|
|
832
|
+
fallbackName: source.slug,
|
|
833
|
+
label: version === void 0 ? label : `${label} · ${version}`,
|
|
834
|
+
sourceKey: "tencent-skillhub",
|
|
835
|
+
origin: (_key, installedAt) => ({
|
|
836
|
+
kind: "tencent-skillhub",
|
|
837
|
+
slug: source.slug,
|
|
838
|
+
...version === void 0 ? {} : { version },
|
|
839
|
+
installedAt
|
|
840
|
+
}),
|
|
841
|
+
dispose: space.dispose
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
async function fetchSkillsSh(http, skills, source, signal) {
|
|
845
|
+
const [owner = "", name = ""] = source.repo.split("/");
|
|
846
|
+
const label = `skills.sh · ${source.repo}/${source.skill}`;
|
|
847
|
+
const repo = await fetchRepository(http, {
|
|
848
|
+
owner,
|
|
849
|
+
repo: name,
|
|
850
|
+
rest: []
|
|
851
|
+
}, label, signal);
|
|
852
|
+
const directories = findSkillDirectories(repo.root);
|
|
853
|
+
const key = directories.find((key) => {
|
|
854
|
+
const read = skills.inspect(key === "." ? repo.root : join(repo.root, key), "skill");
|
|
855
|
+
return read.ok && read.declaredName === source.skill;
|
|
856
|
+
}) ?? directories.find((one) => basename(one) === source.skill);
|
|
857
|
+
if (key === void 0) {
|
|
858
|
+
repo.dispose();
|
|
859
|
+
throw failureOf(label, new Response(null, { status: 404 }));
|
|
860
|
+
}
|
|
861
|
+
return {
|
|
862
|
+
root: key === "." ? repo.root : join(repo.root, key),
|
|
863
|
+
fallbackName: source.skill,
|
|
864
|
+
label,
|
|
865
|
+
sourceKey: "skills-sh",
|
|
866
|
+
origin: (_key, installedAt) => ({
|
|
867
|
+
kind: "skills-sh",
|
|
868
|
+
repo: source.repo,
|
|
869
|
+
skill: source.skill,
|
|
870
|
+
...repo.commit === void 0 ? {} : { commit: repo.commit },
|
|
871
|
+
path: key === "." ? "" : key,
|
|
872
|
+
installedAt
|
|
873
|
+
}),
|
|
874
|
+
dispose: repo.dispose
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
//#endregion
|
|
878
|
+
//#region src/install/installer.ts
|
|
879
|
+
/**
|
|
880
|
+
* One installing flow for both ways in — the settings page's methods and the
|
|
881
|
+
* two tools: fetch a source, scan it into a preview, hold the preview until a
|
|
882
|
+
* person decides, and install what they picked through the host.
|
|
883
|
+
*
|
|
884
|
+
* A preview lives in memory only, with the scratch directory its fetch
|
|
885
|
+
* unpacked into. It goes when it is installed, cancelled, idle for thirty
|
|
886
|
+
* minutes, or when this plugin stops; each way removes the directory. A tool
|
|
887
|
+
* keeps its preview under its call's id, so the run after a person's answer
|
|
888
|
+
* finds what the question showed.
|
|
889
|
+
*/
|
|
890
|
+
/** How long a preview waits for a decision after it was last touched. */
|
|
891
|
+
const PREVIEW_IDLE_MS = 18e5;
|
|
892
|
+
function createInstaller(deps) {
|
|
893
|
+
const now = deps.now ?? Date.now;
|
|
894
|
+
const held = /* @__PURE__ */ new Map();
|
|
895
|
+
const expire = () => {
|
|
896
|
+
const cutoff = now() - PREVIEW_IDLE_MS;
|
|
897
|
+
for (const [id, one] of held) if (one.lastUsed < cutoff) {
|
|
898
|
+
held.delete(id);
|
|
899
|
+
one.tree.dispose();
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
const sweeper = setInterval(expire, 6e4);
|
|
903
|
+
sweeper.unref?.();
|
|
904
|
+
const viewOf = (one) => ({
|
|
905
|
+
...one.view,
|
|
906
|
+
expiresAt: one.lastUsed + PREVIEW_IDLE_MS
|
|
907
|
+
});
|
|
908
|
+
const fetchSource = async (source, signal) => {
|
|
909
|
+
switch (source.kind) {
|
|
910
|
+
case "clawhub": return fetchClawHub(deps.http, source, signal);
|
|
911
|
+
case "tencent-skillhub": return fetchTencent(deps.http, source, signal);
|
|
912
|
+
case "skills-sh": return fetchSkillsSh(deps.http, deps.skills, source, signal);
|
|
913
|
+
case "github": return fetchGitHub(deps.http, source.url, signal);
|
|
914
|
+
case "local": return fetchLocal(source.path);
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
const candidateDirectory = (one, key) => key === "." ? one.tree.root : join(one.tree.root, key);
|
|
918
|
+
function freezeLocalCandidates(tree, scanned, target) {
|
|
919
|
+
const space = scratch$1();
|
|
920
|
+
try {
|
|
921
|
+
for (const candidate of scanned.candidates) {
|
|
922
|
+
const from = candidate.key === "." ? tree.root : join(tree.root, candidate.key);
|
|
923
|
+
const into = candidate.key === "." ? space.path : join(space.path, candidate.key);
|
|
924
|
+
cpSync(from, into, {
|
|
925
|
+
recursive: true,
|
|
926
|
+
dereference: false,
|
|
927
|
+
verbatimSymlinks: true
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
const frozen = {
|
|
931
|
+
...tree,
|
|
932
|
+
root: space.path,
|
|
933
|
+
dispose: space.dispose
|
|
934
|
+
};
|
|
935
|
+
const checked = scan(frozen, deps.skills, target);
|
|
936
|
+
tree.dispose();
|
|
937
|
+
return {
|
|
938
|
+
tree: frozen,
|
|
939
|
+
scanned: {
|
|
940
|
+
...checked,
|
|
941
|
+
failures: [...scanned.failures, ...checked.failures]
|
|
942
|
+
}
|
|
943
|
+
};
|
|
944
|
+
} catch (error) {
|
|
945
|
+
space.dispose();
|
|
946
|
+
throw error;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
return {
|
|
950
|
+
search: (registry, query, signal) => search(deps.http, registry, query, signal),
|
|
951
|
+
async preview(source, target, options = {}) {
|
|
952
|
+
expire();
|
|
953
|
+
let tree = await fetchSource(source, options.signal);
|
|
954
|
+
let scanned;
|
|
955
|
+
try {
|
|
956
|
+
scanned = scan(tree, deps.skills, target);
|
|
957
|
+
if (source.kind === "local" && scanned.candidates.length > 0) {
|
|
958
|
+
const frozen = freezeLocalCandidates(tree, scanned, target);
|
|
959
|
+
tree = frozen.tree;
|
|
960
|
+
scanned = frozen.scanned;
|
|
961
|
+
}
|
|
962
|
+
} catch (error) {
|
|
963
|
+
tree.dispose();
|
|
964
|
+
throw error;
|
|
965
|
+
}
|
|
966
|
+
const previewId = options.key ?? randomUUID();
|
|
967
|
+
const previous = held.get(previewId);
|
|
968
|
+
if (previous !== void 0) previous.tree.dispose();
|
|
969
|
+
const one = {
|
|
970
|
+
view: {
|
|
971
|
+
previewId,
|
|
972
|
+
sourceLabel: tree.label,
|
|
973
|
+
...scanned,
|
|
974
|
+
taken: deps.skills.layerIds(target)
|
|
975
|
+
},
|
|
976
|
+
tree,
|
|
977
|
+
sourceKey: tree.sourceKey,
|
|
978
|
+
lastUsed: now()
|
|
979
|
+
};
|
|
980
|
+
held.set(previewId, one);
|
|
981
|
+
return viewOf(one);
|
|
982
|
+
},
|
|
983
|
+
find(previewId) {
|
|
984
|
+
expire();
|
|
985
|
+
const one = held.get(previewId);
|
|
986
|
+
if (one === void 0) return void 0;
|
|
987
|
+
one.lastUsed = now();
|
|
988
|
+
return {
|
|
989
|
+
...viewOf(one),
|
|
990
|
+
sourceKey: one.sourceKey
|
|
991
|
+
};
|
|
992
|
+
},
|
|
993
|
+
digest(previewId, picks, layer) {
|
|
994
|
+
const one = held.get(previewId);
|
|
995
|
+
if (one === void 0) throw new InstallError("预览已过期,请重新获取");
|
|
996
|
+
const hash = createHash("sha256").update(`layer:${layer}\n`);
|
|
997
|
+
for (const pick of [...picks].sort((a, b) => a.key.localeCompare(b.key))) {
|
|
998
|
+
const candidate = one.view.candidates.find((entry) => entry.key === pick.key);
|
|
999
|
+
if (candidate === void 0) continue;
|
|
1000
|
+
hash.update(`skill:${pick.key}:${pick.id}:${pick.onConflict}\n`);
|
|
1001
|
+
const directory = candidateDirectory(one, pick.key);
|
|
1002
|
+
for (const file of candidate.files) {
|
|
1003
|
+
const mode = statSync(join(directory, file.path)).mode & 511;
|
|
1004
|
+
const content = createHash("sha256").update(readFileSync(join(directory, file.path))).digest("hex");
|
|
1005
|
+
hash.update(`${file.path}:${file.bytes}:${mode}:${content}\n`);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
return hash.digest("hex");
|
|
1009
|
+
},
|
|
1010
|
+
async install(previewId, target, layer, picks, approvedAt) {
|
|
1011
|
+
const one = held.get(previewId);
|
|
1012
|
+
if (one === void 0) throw new InstallError("预览已过期,请重新获取");
|
|
1013
|
+
one.lastUsed = now();
|
|
1014
|
+
const installed = [];
|
|
1015
|
+
const skipped = [];
|
|
1016
|
+
const failed = [];
|
|
1017
|
+
const taken = deps.skills.layerIds(target)[layer];
|
|
1018
|
+
const at = approvedAt ?? now();
|
|
1019
|
+
for (const pick of picks) {
|
|
1020
|
+
if (one.view.candidates.find((entry) => entry.key === pick.key) === void 0) {
|
|
1021
|
+
failed.push({
|
|
1022
|
+
key: pick.key,
|
|
1023
|
+
reason: "预览里没有这个技能"
|
|
1024
|
+
});
|
|
1025
|
+
continue;
|
|
1026
|
+
}
|
|
1027
|
+
if (!isStandardName$1(pick.id)) {
|
|
1028
|
+
failed.push({
|
|
1029
|
+
key: pick.key,
|
|
1030
|
+
reason: "标识只能用小写字母、数字和单个连字符,至多 64 个字符"
|
|
1031
|
+
});
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
if (pick.onConflict === "skip" && taken.includes(pick.id)) {
|
|
1035
|
+
skipped.push({ key: pick.key });
|
|
1036
|
+
continue;
|
|
1037
|
+
}
|
|
1038
|
+
const result = await deps.skills.install(target, {
|
|
1039
|
+
layer,
|
|
1040
|
+
id: pick.id,
|
|
1041
|
+
from: candidateDirectory(one, pick.key),
|
|
1042
|
+
replace: pick.onConflict === "replace",
|
|
1043
|
+
origin: one.tree.origin(pick.key, at)
|
|
1044
|
+
});
|
|
1045
|
+
if (result.ok) installed.push({
|
|
1046
|
+
key: pick.key,
|
|
1047
|
+
id: result.id,
|
|
1048
|
+
layer: result.layer
|
|
1049
|
+
});
|
|
1050
|
+
else failed.push({
|
|
1051
|
+
key: pick.key,
|
|
1052
|
+
reason: refusalText(result.reason, result.message)
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
if (installed.length > 0) deps.changed(target, layer);
|
|
1056
|
+
if (failed.length === 0) {
|
|
1057
|
+
held.delete(previewId);
|
|
1058
|
+
one.tree.dispose();
|
|
1059
|
+
}
|
|
1060
|
+
return {
|
|
1061
|
+
installed,
|
|
1062
|
+
skipped,
|
|
1063
|
+
failed
|
|
1064
|
+
};
|
|
1065
|
+
},
|
|
1066
|
+
cancel(previewId) {
|
|
1067
|
+
const one = held.get(previewId);
|
|
1068
|
+
if (one === void 0) return;
|
|
1069
|
+
held.delete(previewId);
|
|
1070
|
+
one.tree.dispose();
|
|
1071
|
+
},
|
|
1072
|
+
dispose() {
|
|
1073
|
+
clearInterval(sweeper);
|
|
1074
|
+
for (const one of held.values()) one.tree.dispose();
|
|
1075
|
+
held.clear();
|
|
1076
|
+
}
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
/** The sentence for a refusal of `skills.install`, from its reason. */
|
|
1080
|
+
function refusalText(reason, message) {
|
|
1081
|
+
switch (reason) {
|
|
1082
|
+
case "exists": return "已有同名技能";
|
|
1083
|
+
case "unsafe-entry": return `包里有指向包外的路径或符号链接:${message}`;
|
|
1084
|
+
case "sealed": return "不能从产品的状态目录安装";
|
|
1085
|
+
case "invalid-id": return "标识只能用小写字母、数字和单个连字符,至多 64 个字符";
|
|
1086
|
+
case "not-a-skill": return "缺少 SKILL.md 或说明";
|
|
1087
|
+
case "no-such-agent": return "这个智能体已不存在";
|
|
1088
|
+
default: return message;
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
//#endregion
|
|
1092
|
+
//#region src/install/types.ts
|
|
1093
|
+
/**
|
|
1094
|
+
* The words installing is spoken in: where a package is (a source), what a
|
|
1095
|
+
* package turned out to hold (candidates), and one fetch waiting for a
|
|
1096
|
+
* person's decision (a preview).
|
|
1097
|
+
*/
|
|
1098
|
+
/** The three skill sites this build knows. */
|
|
1099
|
+
const REGISTRIES = [
|
|
1100
|
+
"clawhub",
|
|
1101
|
+
"tencent-skillhub",
|
|
1102
|
+
"skills-sh"
|
|
1103
|
+
];
|
|
1104
|
+
/** Where a package is. */
|
|
1105
|
+
const SkillSource = z.discriminatedUnion("kind", [
|
|
1106
|
+
z.strictObject({
|
|
1107
|
+
kind: z.literal("clawhub"),
|
|
1108
|
+
slug: z.string().min(1).max(200),
|
|
1109
|
+
owner: z.string().min(1).max(200).optional(),
|
|
1110
|
+
version: z.string().min(1).max(100).optional()
|
|
1111
|
+
}),
|
|
1112
|
+
z.strictObject({
|
|
1113
|
+
kind: z.literal("tencent-skillhub"),
|
|
1114
|
+
slug: z.string().min(1).max(200),
|
|
1115
|
+
version: z.string().min(1).max(100).optional()
|
|
1116
|
+
}),
|
|
1117
|
+
z.strictObject({
|
|
1118
|
+
kind: z.literal("skills-sh"),
|
|
1119
|
+
/** `owner/name` on GitHub. */
|
|
1120
|
+
repo: z.string().regex(/^[\w.-]+\/[\w.-]+$/),
|
|
1121
|
+
skill: z.string().min(1).max(200)
|
|
1122
|
+
}),
|
|
1123
|
+
z.strictObject({
|
|
1124
|
+
kind: z.literal("github"),
|
|
1125
|
+
url: z.string().min(1).max(2e3)
|
|
1126
|
+
}),
|
|
1127
|
+
z.strictObject({
|
|
1128
|
+
kind: z.literal("local"),
|
|
1129
|
+
path: z.string().min(1).max(4096)
|
|
1130
|
+
})
|
|
1131
|
+
]);
|
|
1132
|
+
//#endregion
|
|
1133
|
+
//#region src/methods.ts
|
|
1134
|
+
const Layer = z.enum(["global", "agent"]);
|
|
1135
|
+
const AgentId = z.string().min(1).max(200);
|
|
1136
|
+
const Issue = z.object({
|
|
1137
|
+
code: z.string(),
|
|
1138
|
+
detail: z.string()
|
|
1139
|
+
});
|
|
1140
|
+
const Candidate = z.object({
|
|
1141
|
+
key: z.string(),
|
|
1142
|
+
suggestedId: z.string(),
|
|
1143
|
+
description: z.string(),
|
|
1144
|
+
files: z.array(z.object({
|
|
1145
|
+
path: z.string(),
|
|
1146
|
+
bytes: z.number()
|
|
1147
|
+
})),
|
|
1148
|
+
bytes: z.number(),
|
|
1149
|
+
scripts: z.array(z.string()),
|
|
1150
|
+
conflicts: z.object({
|
|
1151
|
+
agent: z.boolean(),
|
|
1152
|
+
global: z.boolean()
|
|
1153
|
+
}),
|
|
1154
|
+
issues: z.array(Issue)
|
|
1155
|
+
});
|
|
1156
|
+
const Preview = z.object({
|
|
1157
|
+
previewId: z.string(),
|
|
1158
|
+
sourceLabel: z.string(),
|
|
1159
|
+
candidates: z.array(Candidate),
|
|
1160
|
+
failures: z.array(z.object({
|
|
1161
|
+
path: z.string(),
|
|
1162
|
+
reason: z.string()
|
|
1163
|
+
})),
|
|
1164
|
+
taken: z.object({
|
|
1165
|
+
agent: z.array(z.string()),
|
|
1166
|
+
global: z.array(z.string())
|
|
1167
|
+
}),
|
|
1168
|
+
expiresAt: z.number()
|
|
1169
|
+
});
|
|
1170
|
+
const SearchResult = z.object({
|
|
1171
|
+
stars: z.number().nonnegative().optional(),
|
|
1172
|
+
downloads: z.number().nonnegative().optional(),
|
|
1173
|
+
name: z.string(),
|
|
1174
|
+
summary: z.string().optional(),
|
|
1175
|
+
publisher: z.string().optional(),
|
|
1176
|
+
version: z.string().optional(),
|
|
1177
|
+
source: SkillSource,
|
|
1178
|
+
needsLogin: z.boolean().optional()
|
|
1179
|
+
});
|
|
1180
|
+
const SkillsChanged = z.object({
|
|
1181
|
+
agentId: z.string().optional(),
|
|
1182
|
+
layer: Layer
|
|
1183
|
+
});
|
|
1184
|
+
/** The frame's payload for a change in `layer` of the agent `target` names:
|
|
1185
|
+
* the global layer names no agent, because every agent reads it. */
|
|
1186
|
+
function changeOf(skills, target, layer) {
|
|
1187
|
+
if (layer === "global") return { layer };
|
|
1188
|
+
return {
|
|
1189
|
+
layer,
|
|
1190
|
+
agentId: "ctx" in target ? skills.agentOf(target.ctx) : target.agentId
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
function registerSkillFrame(ctx) {
|
|
1194
|
+
return ctx.client.registerFrame({
|
|
1195
|
+
name: "skillsChanged",
|
|
1196
|
+
delivery: "broadcast",
|
|
1197
|
+
payload: SkillsChanged
|
|
1198
|
+
});
|
|
1199
|
+
}
|
|
1200
|
+
function registerSkillMethods(ctx, deps) {
|
|
1201
|
+
const { skills, installer } = deps;
|
|
1202
|
+
ctx.client.registerMethod({
|
|
1203
|
+
name: "search",
|
|
1204
|
+
description: "Searches one skill site by keyword.",
|
|
1205
|
+
params: z.strictObject({
|
|
1206
|
+
registry: z.enum(REGISTRIES),
|
|
1207
|
+
query: z.string().trim().min(1).max(200)
|
|
1208
|
+
}),
|
|
1209
|
+
result: z.object({ results: z.array(SearchResult) }),
|
|
1210
|
+
async handle({ registry, query }, call) {
|
|
1211
|
+
return { results: [...await installer.search(registry, query, call.signal)] };
|
|
1212
|
+
}
|
|
1213
|
+
});
|
|
1214
|
+
ctx.client.registerMethod({
|
|
1215
|
+
name: "preview",
|
|
1216
|
+
description: "Fetches a source and lists the skills it holds, installing nothing.",
|
|
1217
|
+
params: z.strictObject({
|
|
1218
|
+
source: SkillSource,
|
|
1219
|
+
agentId: AgentId
|
|
1220
|
+
}),
|
|
1221
|
+
result: Preview,
|
|
1222
|
+
async handle({ source, agentId }, call) {
|
|
1223
|
+
const view = await installer.preview(source, { agentId }, { signal: call.signal });
|
|
1224
|
+
return {
|
|
1225
|
+
...view,
|
|
1226
|
+
candidates: [...view.candidates],
|
|
1227
|
+
failures: [...view.failures],
|
|
1228
|
+
taken: {
|
|
1229
|
+
agent: [...view.taken.agent],
|
|
1230
|
+
global: [...view.taken.global]
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
});
|
|
1235
|
+
ctx.client.registerMethod({
|
|
1236
|
+
name: "install",
|
|
1237
|
+
description: "Installs the picked skills of a preview into one layer.",
|
|
1238
|
+
params: z.strictObject({
|
|
1239
|
+
previewId: z.string().min(1),
|
|
1240
|
+
agentId: AgentId,
|
|
1241
|
+
layer: Layer,
|
|
1242
|
+
picks: z.array(z.strictObject({
|
|
1243
|
+
key: z.string(),
|
|
1244
|
+
id: z.string(),
|
|
1245
|
+
onConflict: z.enum(["replace", "skip"])
|
|
1246
|
+
})).min(1)
|
|
1247
|
+
}),
|
|
1248
|
+
result: z.object({
|
|
1249
|
+
installed: z.array(z.object({
|
|
1250
|
+
key: z.string(),
|
|
1251
|
+
id: z.string(),
|
|
1252
|
+
layer: Layer
|
|
1253
|
+
})),
|
|
1254
|
+
skipped: z.array(z.object({ key: z.string() })),
|
|
1255
|
+
failed: z.array(z.object({
|
|
1256
|
+
key: z.string(),
|
|
1257
|
+
reason: z.string()
|
|
1258
|
+
}))
|
|
1259
|
+
}),
|
|
1260
|
+
async handle({ previewId, agentId, layer, picks }) {
|
|
1261
|
+
const outcome = await installer.install(previewId, { agentId }, layer, picks);
|
|
1262
|
+
return {
|
|
1263
|
+
installed: [...outcome.installed],
|
|
1264
|
+
skipped: [...outcome.skipped],
|
|
1265
|
+
failed: [...outcome.failed]
|
|
1266
|
+
};
|
|
1267
|
+
}
|
|
1268
|
+
});
|
|
1269
|
+
ctx.client.registerMethod({
|
|
1270
|
+
name: "cancel",
|
|
1271
|
+
description: "Drops a preview and what its fetch put on disk.",
|
|
1272
|
+
params: z.strictObject({ previewId: z.string().min(1) }),
|
|
1273
|
+
result: z.object({}),
|
|
1274
|
+
handle({ previewId }) {
|
|
1275
|
+
installer.cancel(previewId);
|
|
1276
|
+
return {};
|
|
1277
|
+
}
|
|
1278
|
+
});
|
|
1279
|
+
ctx.client.registerMethod({
|
|
1280
|
+
name: "uninstall",
|
|
1281
|
+
description: "Removes one skill from one layer, whole.",
|
|
1282
|
+
params: z.strictObject({
|
|
1283
|
+
agentId: AgentId,
|
|
1284
|
+
layer: Layer,
|
|
1285
|
+
id: z.string().min(1).max(200)
|
|
1286
|
+
}),
|
|
1287
|
+
result: z.object({
|
|
1288
|
+
id: z.string(),
|
|
1289
|
+
layer: Layer
|
|
1290
|
+
}),
|
|
1291
|
+
async handle({ agentId, layer, id }) {
|
|
1292
|
+
const result = await skills.uninstall({ agentId }, {
|
|
1293
|
+
layer,
|
|
1294
|
+
id
|
|
1295
|
+
});
|
|
1296
|
+
if (!result.ok) throw new InstallError(result.reason === "missing" ? "这个技能已不在" : refusalText(result.reason, result.message));
|
|
1297
|
+
deps.changed.emit(changeOf(skills, { agentId }, layer));
|
|
1298
|
+
return {
|
|
1299
|
+
id,
|
|
1300
|
+
layer
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
});
|
|
1304
|
+
ctx.client.registerMethod({
|
|
1305
|
+
name: "normalize",
|
|
1306
|
+
description: "Rewrites one skill's SKILL.md frontmatter to the Agent Skills specification; with dryRun, only says what it would write.",
|
|
1307
|
+
params: z.strictObject({
|
|
1308
|
+
agentId: AgentId,
|
|
1309
|
+
layer: Layer,
|
|
1310
|
+
id: z.string().min(1).max(200),
|
|
1311
|
+
dryRun: z.boolean().optional()
|
|
1312
|
+
}),
|
|
1313
|
+
result: z.object({
|
|
1314
|
+
id: z.string(),
|
|
1315
|
+
layer: Layer,
|
|
1316
|
+
frontmatter: z.string(),
|
|
1317
|
+
remaining: z.array(Issue)
|
|
1318
|
+
}),
|
|
1319
|
+
async handle({ agentId, layer, id, dryRun }) {
|
|
1320
|
+
const run = () => skills.normalize({ agentId }, {
|
|
1321
|
+
layer,
|
|
1322
|
+
id,
|
|
1323
|
+
dryRun: dryRun === true
|
|
1324
|
+
});
|
|
1325
|
+
const result = await run();
|
|
1326
|
+
if (!result.ok) throw new InstallError(result.reason === "missing" ? "这个技能已不在" : refusalText(result.reason, result.message));
|
|
1327
|
+
if (dryRun !== true) deps.changed.emit(changeOf(skills, { agentId }, layer));
|
|
1328
|
+
return {
|
|
1329
|
+
id,
|
|
1330
|
+
layer,
|
|
1331
|
+
frontmatter: result.frontmatter,
|
|
1332
|
+
remaining: [...result.remaining]
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
//#endregion
|
|
1338
|
+
//#region src/skills/read.ts
|
|
1339
|
+
const ReadSkillInput = z.object({
|
|
1340
|
+
id: z.string(),
|
|
1341
|
+
file: z.string().optional()
|
|
1342
|
+
});
|
|
1343
|
+
function readSkillTool(skills) {
|
|
1344
|
+
return {
|
|
1345
|
+
name: "skill_read",
|
|
1346
|
+
description: "Read one skill's full body, by the `id` shown in the skill list in the system prompt. Pass `file` to read one of the files that skill was created with instead, by its plain name — never a path. An `id` that is not currently loaded, or a `file` that is not one of that skill's own files, is reported back as an error.",
|
|
1347
|
+
inputSchema: ReadSkillInput,
|
|
1348
|
+
async execute(input, ctx) {
|
|
1349
|
+
const result = skills.read(ctx, input.id, input.file);
|
|
1350
|
+
if (!result.ok) return {
|
|
1351
|
+
content: result.message,
|
|
1352
|
+
isError: true
|
|
1353
|
+
};
|
|
1354
|
+
return { content: result.content };
|
|
1355
|
+
}
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
//#endregion
|
|
1359
|
+
//#region src/skills/service.ts
|
|
1360
|
+
/** The service key the skills arrive under. Written on both sides — the
|
|
1361
|
+
* host that publishes it cannot import this package. */
|
|
1362
|
+
const SKILLS_SERVICE = "skills";
|
|
1363
|
+
//#endregion
|
|
1364
|
+
//#region src/skills/index.ts
|
|
1365
|
+
function registerSkillTools(ctx, register) {
|
|
1366
|
+
register(readSkillTool(ctx.services.get(SKILLS_SERVICE)));
|
|
1367
|
+
}
|
|
1368
|
+
//#endregion
|
|
1369
|
+
//#region src/runtime/skills/origin.ts
|
|
1370
|
+
/**
|
|
1371
|
+
* Where an installed skill came from: one small file inside the skill's own
|
|
1372
|
+
* directory, written at install. Kept with the skill rather than in the
|
|
1373
|
+
* database because the directory is the only record of a skill there is — a
|
|
1374
|
+
* person who deletes the directory deletes the record with it, and nothing is
|
|
1375
|
+
* left pointing at a skill that is gone.
|
|
1376
|
+
*/
|
|
1377
|
+
const SkillOrigin = z.discriminatedUnion("kind", [
|
|
1378
|
+
z.object({
|
|
1379
|
+
kind: z.literal("clawhub"),
|
|
1380
|
+
slug: z.string().min(1),
|
|
1381
|
+
owner: z.string().min(1).optional(),
|
|
1382
|
+
version: z.string().optional(),
|
|
1383
|
+
installedAt: z.number().int()
|
|
1384
|
+
}),
|
|
1385
|
+
z.object({
|
|
1386
|
+
kind: z.literal("tencent-skillhub"),
|
|
1387
|
+
slug: z.string().min(1),
|
|
1388
|
+
version: z.string().optional(),
|
|
1389
|
+
installedAt: z.number().int()
|
|
1390
|
+
}),
|
|
1391
|
+
z.object({
|
|
1392
|
+
kind: z.literal("skills-sh"),
|
|
1393
|
+
repo: z.string().min(1),
|
|
1394
|
+
skill: z.string().min(1),
|
|
1395
|
+
commit: z.string().optional(),
|
|
1396
|
+
path: z.string(),
|
|
1397
|
+
installedAt: z.number().int()
|
|
1398
|
+
}),
|
|
1399
|
+
z.object({
|
|
1400
|
+
kind: z.literal("github"),
|
|
1401
|
+
repo: z.string().min(1),
|
|
1402
|
+
ref: z.string().min(1),
|
|
1403
|
+
commit: z.string().optional(),
|
|
1404
|
+
path: z.string(),
|
|
1405
|
+
installedAt: z.number().int()
|
|
1406
|
+
}),
|
|
1407
|
+
z.object({
|
|
1408
|
+
kind: z.literal("local"),
|
|
1409
|
+
path: z.string().min(1),
|
|
1410
|
+
installedAt: z.number().int()
|
|
1411
|
+
})
|
|
1412
|
+
]);
|
|
1413
|
+
const ORIGIN_FILE = ".yaoguang-origin.json";
|
|
1414
|
+
function readOrigin(directory) {
|
|
1415
|
+
try {
|
|
1416
|
+
const parsed = SkillOrigin.safeParse(JSON.parse(readFileSync(join(directory, ORIGIN_FILE), "utf8")));
|
|
1417
|
+
return parsed.success ? parsed.data : void 0;
|
|
1418
|
+
} catch {
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
function originText(origin) {
|
|
1423
|
+
return `${JSON.stringify(SkillOrigin.parse(origin), null, 2)}\n`;
|
|
1424
|
+
}
|
|
1425
|
+
//#endregion
|
|
1426
|
+
//#region src/runtime/skills/layout.ts
|
|
1427
|
+
/**
|
|
1428
|
+
* Where the three layers of skills live, for one (agent, workspace) pair.
|
|
1429
|
+
*
|
|
1430
|
+
* Derived from the work root rather than stored: every agent and every
|
|
1431
|
+
* workspace has these directories, and a fact that is always true is a fact
|
|
1432
|
+
* that could go missing.
|
|
1433
|
+
*/
|
|
1434
|
+
/** The three directories a session reads, in merge order. A layer whose
|
|
1435
|
+
* directory is not there yet is still named: an absent directory reads as
|
|
1436
|
+
* "no skills", never as an error. */
|
|
1437
|
+
function skillDirectories(workRoot, agentId, workspaceId) {
|
|
1438
|
+
return [...agentSkillDirectories(workRoot, agentId), {
|
|
1439
|
+
layer: "workspace",
|
|
1440
|
+
path: join(join(workRoot, "workspaces", workspaceId), ".agents", "skills")
|
|
1441
|
+
}];
|
|
1442
|
+
}
|
|
1443
|
+
/** The global and agent layers alone, in merge order: what an agent's
|
|
1444
|
+
* definition reads, independent of any workspace. */
|
|
1445
|
+
function agentSkillDirectories(workRoot, agentId) {
|
|
1446
|
+
return [{
|
|
1447
|
+
layer: "global",
|
|
1448
|
+
path: join(join(workRoot, "global"), "skills")
|
|
1449
|
+
}, {
|
|
1450
|
+
layer: "agent",
|
|
1451
|
+
path: join(join(workRoot, "agents", agentId), "skills")
|
|
1452
|
+
}];
|
|
1453
|
+
}
|
|
1454
|
+
//#endregion
|
|
1455
|
+
//#region src/runtime/skills/normalize.ts
|
|
1456
|
+
/**
|
|
1457
|
+
* A skill's `SKILL.md` frontmatter, read and written by the Agent Skills
|
|
1458
|
+
* specification (agentskills.io/specification).
|
|
1459
|
+
*
|
|
1460
|
+
* Two directions with different rules. Writing is strict: every `SKILL.md`
|
|
1461
|
+
* this product writes passes the specification's own checks. Reading is
|
|
1462
|
+
* lenient: a file that departs from the specification still loads, through
|
|
1463
|
+
* its *standard view* — the fields the specification allows, filled in by
|
|
1464
|
+
* the fixed rules below — and each departure is reported as an issue. What
|
|
1465
|
+
* the model sees is the standard view, so a skill written for another
|
|
1466
|
+
* product reads the same here as it does there.
|
|
1467
|
+
*
|
|
1468
|
+
* The frontmatter is YAML (1.2 core schema), parsed with `yaml`. A block that
|
|
1469
|
+
* is not valid YAML — the single-line `key: value` format this product used
|
|
1470
|
+
* to write, where a value may carry a bare colon — falls back to the old
|
|
1471
|
+
* line reading, and that too is an issue.
|
|
1472
|
+
*/
|
|
1473
|
+
/** A name the specification accepts: 1–64 of `a-z0-9`, single hyphens
|
|
1474
|
+
* between, none at either end. The length is checked beside it. */
|
|
1475
|
+
const SKILL_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
1476
|
+
const DESCRIPTION_MAX = 1024;
|
|
1477
|
+
/** The fields the specification allows, and nothing else. */
|
|
1478
|
+
const ALLOWED = /* @__PURE__ */ new Set([
|
|
1479
|
+
"name",
|
|
1480
|
+
"description",
|
|
1481
|
+
"license",
|
|
1482
|
+
"compatibility",
|
|
1483
|
+
"metadata",
|
|
1484
|
+
"allowed-tools"
|
|
1485
|
+
]);
|
|
1486
|
+
/** Code points rather than UTF-16 units, the way the specification's own
|
|
1487
|
+
* checker counts. */
|
|
1488
|
+
function length(text) {
|
|
1489
|
+
return Array.from(text).length;
|
|
1490
|
+
}
|
|
1491
|
+
function truncate(text, max) {
|
|
1492
|
+
const points = Array.from(text);
|
|
1493
|
+
return points.length <= max ? text : points.slice(0, max).join("");
|
|
1494
|
+
}
|
|
1495
|
+
function isRecord(value) {
|
|
1496
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1497
|
+
}
|
|
1498
|
+
/** A value that is a string in all but type: YAML reads `1.0` as a number
|
|
1499
|
+
* and `true` as a boolean, and a writer who meant the text should get it. */
|
|
1500
|
+
function scalarText(value) {
|
|
1501
|
+
if (typeof value === "string") return value;
|
|
1502
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
1503
|
+
}
|
|
1504
|
+
/** What a value becomes inside `metadata`, which holds strings alone. */
|
|
1505
|
+
function metadataText(value) {
|
|
1506
|
+
return scalarText(value) ?? JSON.stringify(value) ?? String(value);
|
|
1507
|
+
}
|
|
1508
|
+
/** The format this product wrote before: one `key: value` per line, split at
|
|
1509
|
+
* the first colon, lines without one skipped. */
|
|
1510
|
+
function readLines(block) {
|
|
1511
|
+
const fields = {};
|
|
1512
|
+
for (const line of block.split("\n")) {
|
|
1513
|
+
if (line.trim() === "") continue;
|
|
1514
|
+
const colon = line.indexOf(":");
|
|
1515
|
+
if (colon === -1) continue;
|
|
1516
|
+
fields[line.slice(0, colon).trim()] = line.slice(colon + 1).trim();
|
|
1517
|
+
}
|
|
1518
|
+
return fields;
|
|
1519
|
+
}
|
|
1520
|
+
/** Splits `SKILL.md` into its frontmatter and the rest. `undefined` when the
|
|
1521
|
+
* file does not open with a `---` fence closed by another. */
|
|
1522
|
+
function readFrontmatter(text) {
|
|
1523
|
+
const lines = text.replace(/^/, "").split("\n");
|
|
1524
|
+
if (lines[0]?.trim() !== "---") return void 0;
|
|
1525
|
+
const end = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
|
|
1526
|
+
if (end === -1) return void 0;
|
|
1527
|
+
const block = lines.slice(1, end).map((line) => line.replace(/\r$/, "")).join("\n");
|
|
1528
|
+
const rest = lines.slice(end + 1).join("\n");
|
|
1529
|
+
try {
|
|
1530
|
+
const parsed = parse(block);
|
|
1531
|
+
if (parsed === null || parsed === void 0) return {
|
|
1532
|
+
fields: {},
|
|
1533
|
+
syntax: "yaml",
|
|
1534
|
+
rest
|
|
1535
|
+
};
|
|
1536
|
+
if (isRecord(parsed)) return {
|
|
1537
|
+
fields: parsed,
|
|
1538
|
+
syntax: "yaml",
|
|
1539
|
+
rest
|
|
1540
|
+
};
|
|
1541
|
+
} catch {}
|
|
1542
|
+
return {
|
|
1543
|
+
fields: readLines(block),
|
|
1544
|
+
syntax: "lines",
|
|
1545
|
+
rest
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
/** Whether a directory name is one the specification accepts. */
|
|
1549
|
+
function isStandardName(name) {
|
|
1550
|
+
return length(name) <= 64 && SKILL_NAME.test(name);
|
|
1551
|
+
}
|
|
1552
|
+
/** Every way these fields, in a directory named `dirName`, depart from the
|
|
1553
|
+
* specification. Empty means the file already is its standard view. */
|
|
1554
|
+
function conformance(front, dirName) {
|
|
1555
|
+
const issues = [];
|
|
1556
|
+
const { fields } = front;
|
|
1557
|
+
if (front.syntax === "lines") issues.push({
|
|
1558
|
+
code: "syntax",
|
|
1559
|
+
detail: "frontmatter is not YAML"
|
|
1560
|
+
});
|
|
1561
|
+
if (!isStandardName(dirName)) issues.push({
|
|
1562
|
+
code: "dir-invalid",
|
|
1563
|
+
detail: dirName
|
|
1564
|
+
});
|
|
1565
|
+
const name = fields.name;
|
|
1566
|
+
if (name === void 0) issues.push({
|
|
1567
|
+
code: "name-missing",
|
|
1568
|
+
detail: "name"
|
|
1569
|
+
});
|
|
1570
|
+
else if (typeof name !== "string") issues.push({
|
|
1571
|
+
code: "field-type",
|
|
1572
|
+
detail: "name"
|
|
1573
|
+
});
|
|
1574
|
+
else {
|
|
1575
|
+
if (!isStandardName(name)) issues.push({
|
|
1576
|
+
code: "name-invalid",
|
|
1577
|
+
detail: name
|
|
1578
|
+
});
|
|
1579
|
+
if (name !== dirName) issues.push({
|
|
1580
|
+
code: "name-mismatch",
|
|
1581
|
+
detail: name
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
const description = fields.description;
|
|
1585
|
+
if (description !== void 0 && typeof description !== "string") issues.push({
|
|
1586
|
+
code: "field-type",
|
|
1587
|
+
detail: "description"
|
|
1588
|
+
});
|
|
1589
|
+
const descriptionText = scalarText(description);
|
|
1590
|
+
if (descriptionText !== void 0 && length(descriptionText.trim()) > 1024) issues.push({
|
|
1591
|
+
code: "description-long",
|
|
1592
|
+
detail: String(length(descriptionText.trim()))
|
|
1593
|
+
});
|
|
1594
|
+
for (const key of [
|
|
1595
|
+
"license",
|
|
1596
|
+
"compatibility",
|
|
1597
|
+
"allowed-tools"
|
|
1598
|
+
]) {
|
|
1599
|
+
const value = fields[key];
|
|
1600
|
+
if (value !== void 0 && typeof value !== "string") issues.push({
|
|
1601
|
+
code: "field-type",
|
|
1602
|
+
detail: key
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
const compatibility = scalarText(fields.compatibility);
|
|
1606
|
+
if (compatibility !== void 0 && length(compatibility) > 500) issues.push({
|
|
1607
|
+
code: "compatibility-long",
|
|
1608
|
+
detail: String(length(compatibility))
|
|
1609
|
+
});
|
|
1610
|
+
const metadata = fields.metadata;
|
|
1611
|
+
if (metadata !== void 0) {
|
|
1612
|
+
if (!isRecord(metadata)) issues.push({
|
|
1613
|
+
code: "field-type",
|
|
1614
|
+
detail: "metadata"
|
|
1615
|
+
});
|
|
1616
|
+
else for (const [key, value] of Object.entries(metadata)) if (typeof value !== "string") issues.push({
|
|
1617
|
+
code: "metadata-value",
|
|
1618
|
+
detail: key
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
for (const key of Object.keys(fields)) if (!ALLOWED.has(key)) issues.push({
|
|
1622
|
+
code: "extra-field",
|
|
1623
|
+
detail: key
|
|
1624
|
+
});
|
|
1625
|
+
return issues;
|
|
1626
|
+
}
|
|
1627
|
+
/**
|
|
1628
|
+
* The standard view of these fields for a skill named `name`: what loading
|
|
1629
|
+
* reads and what a rewrite writes. `undefined` when there is no description
|
|
1630
|
+
* to speak of — the one departure no rule can fill in, and the one that
|
|
1631
|
+
* still fails a skill's load.
|
|
1632
|
+
*
|
|
1633
|
+
* The rules, in the order they apply: `name` is the directory's (or, at
|
|
1634
|
+
* install, the identifier the person confirmed); a scalar that should be text
|
|
1635
|
+
* becomes its text; `allowed-tools` written as a list becomes the
|
|
1636
|
+
* space-separated string the specification asks for; anything else that is
|
|
1637
|
+
* not a string moves into `metadata` as JSON; a field the specification does
|
|
1638
|
+
* not have moves into `metadata` under its own key, or `x-<key>` when
|
|
1639
|
+
* `metadata` already holds that key; a description over 1024 code points and
|
|
1640
|
+
* a compatibility over 500 are cut to the limit.
|
|
1641
|
+
*/
|
|
1642
|
+
function normalize$1(front, name) {
|
|
1643
|
+
const { fields } = front;
|
|
1644
|
+
const descriptionText = scalarText(fields.description)?.trim() ?? "";
|
|
1645
|
+
if (descriptionText === "") return void 0;
|
|
1646
|
+
const metadata = {};
|
|
1647
|
+
const moved = [];
|
|
1648
|
+
if (fields.metadata !== void 0) {
|
|
1649
|
+
if (isRecord(fields.metadata)) for (const [key, value] of Object.entries(fields.metadata)) metadata[key] = metadataText(value);
|
|
1650
|
+
else moved.push(["metadata", fields.metadata]);
|
|
1651
|
+
}
|
|
1652
|
+
const text = (key) => {
|
|
1653
|
+
const value = fields[key];
|
|
1654
|
+
if (value === void 0 || value === null) return void 0;
|
|
1655
|
+
if (key === "allowed-tools" && Array.isArray(value) && value.every((one) => typeof one === "string")) return value.join(" ");
|
|
1656
|
+
const scalar = scalarText(value);
|
|
1657
|
+
if (scalar !== void 0) return scalar;
|
|
1658
|
+
moved.push([key, value]);
|
|
1659
|
+
};
|
|
1660
|
+
const license = text("license");
|
|
1661
|
+
const compatibilityRaw = text("compatibility");
|
|
1662
|
+
const allowedTools = text("allowed-tools");
|
|
1663
|
+
for (const [key, value] of Object.entries(fields)) if (!ALLOWED.has(key)) moved.push([key, value]);
|
|
1664
|
+
for (const [key, value] of moved) {
|
|
1665
|
+
const target = Object.hasOwn(metadata, key) ? `x-${key}` : key;
|
|
1666
|
+
metadata[target] = metadataText(value);
|
|
1667
|
+
}
|
|
1668
|
+
const compatibility = compatibilityRaw === void 0 ? void 0 : truncate(compatibilityRaw, 500);
|
|
1669
|
+
return {
|
|
1670
|
+
name,
|
|
1671
|
+
description: truncate(descriptionText, DESCRIPTION_MAX),
|
|
1672
|
+
...license === void 0 ? {} : { license },
|
|
1673
|
+
...compatibility === void 0 || compatibility === "" ? {} : { compatibility },
|
|
1674
|
+
...allowedTools === void 0 ? {} : { "allowed-tools": allowedTools },
|
|
1675
|
+
...Object.keys(metadata).length === 0 ? {} : { metadata }
|
|
1676
|
+
};
|
|
1677
|
+
}
|
|
1678
|
+
/** Writes a standard view back as the text of a `SKILL.md`, with `rest` —
|
|
1679
|
+
* everything that followed the closing fence — exactly as it was. */
|
|
1680
|
+
function render(standard, rest) {
|
|
1681
|
+
return `---\n${stringify(standard, { lineWidth: 0 })}---\n${rest}`;
|
|
1682
|
+
}
|
|
1683
|
+
/** The fields of a standard view as a `Frontmatter`, for checking what a
|
|
1684
|
+
* rewrite is about to write. */
|
|
1685
|
+
function asFrontmatter(standard) {
|
|
1686
|
+
return {
|
|
1687
|
+
fields: { ...standard },
|
|
1688
|
+
syntax: "yaml",
|
|
1689
|
+
rest: ""
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
//#endregion
|
|
1693
|
+
//#region src/runtime/skills/parse.ts
|
|
1694
|
+
/**
|
|
1695
|
+
* One skill directory, read.
|
|
1696
|
+
*
|
|
1697
|
+
* A skill is a directory: `SKILL.md` with a frontmatter block, plus whatever
|
|
1698
|
+
* files it wants beside it. The format is the Agent Skills specification's,
|
|
1699
|
+
* read through `normalize.ts`: a file that departs from it still loads, as
|
|
1700
|
+
* its standard view, with every departure listed in `issues`. Only a missing
|
|
1701
|
+
* `SKILL.md`, a missing frontmatter block or a missing description fails the
|
|
1702
|
+
* load — the three things no rule can fill in.
|
|
1703
|
+
*/
|
|
1704
|
+
/** A directory name that is safe to join onto a path: the rule every skill
|
|
1705
|
+
* on disk must meet to load at all. New identifiers meet the stricter
|
|
1706
|
+
* `SKILL_NAME` of `normalize.ts`; a directory that meets only this one
|
|
1707
|
+
* loads and reports `dir-invalid`. */
|
|
1708
|
+
const SKILL_ID = /^[a-z0-9][a-z0-9-]*$/;
|
|
1709
|
+
/** Reads one skill directory. Every way it can be wrong comes back as a
|
|
1710
|
+
* failure rather than a throw: one broken skill must not cost a session its
|
|
1711
|
+
* other skills, or its start. */
|
|
1712
|
+
function readSkill(directory) {
|
|
1713
|
+
const id = basename(directory);
|
|
1714
|
+
const fail = (reason) => ({
|
|
1715
|
+
ok: false,
|
|
1716
|
+
failure: {
|
|
1717
|
+
id,
|
|
1718
|
+
reason
|
|
1719
|
+
}
|
|
1720
|
+
});
|
|
1721
|
+
if (!SKILL_ID.test(id)) return fail("a skill directory is named with lowercase letters, digits and hyphens");
|
|
1722
|
+
let text;
|
|
1723
|
+
try {
|
|
1724
|
+
text = readFileSync(join(directory, "SKILL.md"), "utf8");
|
|
1725
|
+
} catch {
|
|
1726
|
+
return fail("SKILL.md is missing or unreadable");
|
|
1727
|
+
}
|
|
1728
|
+
const front = readFrontmatter(text);
|
|
1729
|
+
if (front === void 0) return fail("SKILL.md must open with a --- frontmatter block");
|
|
1730
|
+
const standard = normalize$1(front, id);
|
|
1731
|
+
if (standard === void 0) return fail("SKILL.md needs a description: one line saying what this skill is for");
|
|
1732
|
+
return {
|
|
1733
|
+
ok: true,
|
|
1734
|
+
skill: {
|
|
1735
|
+
id,
|
|
1736
|
+
description: standard.description,
|
|
1737
|
+
body: front.rest.trim(),
|
|
1738
|
+
directory,
|
|
1739
|
+
issues: conformance(front, id),
|
|
1740
|
+
standard
|
|
1741
|
+
}
|
|
1742
|
+
};
|
|
1743
|
+
}
|
|
1744
|
+
//#endregion
|
|
1745
|
+
//#region src/runtime/skills/load.ts
|
|
1746
|
+
/**
|
|
1747
|
+
* The three layers, merged.
|
|
1748
|
+
*
|
|
1749
|
+
* Read on every model call rather than once per session: a person who edits
|
|
1750
|
+
* a skill sees it on the next step, with no session to reopen and nothing to
|
|
1751
|
+
* restart. That is the same thing the authorized-directories contributor
|
|
1752
|
+
* does, and for the same reason.
|
|
1753
|
+
*/
|
|
1754
|
+
const EMPTY = {
|
|
1755
|
+
loaded: [],
|
|
1756
|
+
shadowed: [],
|
|
1757
|
+
failed: []
|
|
1758
|
+
};
|
|
1759
|
+
/** The subdirectories of one layer, or none at all. A layer whose directory
|
|
1760
|
+
* does not exist has no skills — that is the ordinary state of a fresh
|
|
1761
|
+
* install, not a failure anybody needs to hear about. */
|
|
1762
|
+
function directoriesIn(path) {
|
|
1763
|
+
try {
|
|
1764
|
+
return readdirSync(path, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join(path, entry.name));
|
|
1765
|
+
} catch {
|
|
1766
|
+
return [];
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
/** Merges all layers and removes ids disabled for the executing agent. */
|
|
1770
|
+
function loadSkills(workRoot, agentId, workspaceId, disabled = []) {
|
|
1771
|
+
if (workRoot === void 0) return EMPTY;
|
|
1772
|
+
return merge(skillDirectories(workRoot, agentId, workspaceId), disabled);
|
|
1773
|
+
}
|
|
1774
|
+
/**
|
|
1775
|
+
* The two layers an agent's definition reads: global, then the agent's own,
|
|
1776
|
+
* the agent layer shadowing. No workspace layer, because a definition does
|
|
1777
|
+
* not change with the workspace a session happens to be in — this is what
|
|
1778
|
+
* preloading resolves against and what `config.skill.list` lists, so a
|
|
1779
|
+
* workspace skill of the same id never replaces a preloaded one.
|
|
1780
|
+
*/
|
|
1781
|
+
function loadAgentSkills(workRoot, agentId) {
|
|
1782
|
+
if (workRoot === void 0) return EMPTY;
|
|
1783
|
+
return merge(agentSkillDirectories(workRoot, agentId));
|
|
1784
|
+
}
|
|
1785
|
+
function merge(layers, disabled = []) {
|
|
1786
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1787
|
+
const shadowed = [];
|
|
1788
|
+
const failed = [];
|
|
1789
|
+
for (const { layer, path } of layers) for (const directory of directoriesIn(path)) {
|
|
1790
|
+
const read = readSkill(directory);
|
|
1791
|
+
if (!read.ok) {
|
|
1792
|
+
failed.push({
|
|
1793
|
+
...read.failure,
|
|
1794
|
+
layer
|
|
1795
|
+
});
|
|
1796
|
+
continue;
|
|
1797
|
+
}
|
|
1798
|
+
const previous = byId.get(read.skill.id);
|
|
1799
|
+
if (previous !== void 0 && layer !== "global") shadowed.push({
|
|
1800
|
+
id: previous.id,
|
|
1801
|
+
layer: previous.layer,
|
|
1802
|
+
shadowedBy: layer
|
|
1803
|
+
});
|
|
1804
|
+
byId.set(read.skill.id, {
|
|
1805
|
+
...read.skill,
|
|
1806
|
+
layer
|
|
1807
|
+
});
|
|
1808
|
+
}
|
|
1809
|
+
return {
|
|
1810
|
+
loaded: [...byId.values()].filter((skill) => !disabled.includes(skill.id)).sort((a, b) => a.id.localeCompare(b.id)),
|
|
1811
|
+
shadowed: shadowed.filter((skill) => !disabled.includes(skill.id)),
|
|
1812
|
+
failed: failed.filter((skill) => !disabled.includes(skill.id))
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
//#endregion
|
|
1816
|
+
//#region src/runtime/methods.ts
|
|
1817
|
+
const issue = z.strictObject({
|
|
1818
|
+
code: z.string(),
|
|
1819
|
+
detail: z.string()
|
|
1820
|
+
});
|
|
1821
|
+
const layer = z.enum(["global", "agent"]);
|
|
1822
|
+
/** Complete read-only Agent skill browser view. */
|
|
1823
|
+
const SkillListResult = z.strictObject({
|
|
1824
|
+
layers: z.array(z.strictObject({
|
|
1825
|
+
layer,
|
|
1826
|
+
directory: z.string()
|
|
1827
|
+
})),
|
|
1828
|
+
skills: z.array(z.strictObject({
|
|
1829
|
+
id: z.string(),
|
|
1830
|
+
description: z.string(),
|
|
1831
|
+
layer,
|
|
1832
|
+
origin: SkillOrigin.optional(),
|
|
1833
|
+
issues: z.array(issue)
|
|
1834
|
+
})),
|
|
1835
|
+
failed: z.array(z.strictObject({
|
|
1836
|
+
id: z.string(),
|
|
1837
|
+
layer,
|
|
1838
|
+
reason: z.string()
|
|
1839
|
+
}))
|
|
1840
|
+
});
|
|
1841
|
+
const allLayers = z.enum([
|
|
1842
|
+
"global",
|
|
1843
|
+
"agent",
|
|
1844
|
+
"workspace"
|
|
1845
|
+
]);
|
|
1846
|
+
/** Effective skill metadata and suppressed copies for a session or addressed draft. */
|
|
1847
|
+
const SessionSkillsResult = z.strictObject({
|
|
1848
|
+
loaded: z.array(z.strictObject({
|
|
1849
|
+
id: z.string(),
|
|
1850
|
+
description: z.string(),
|
|
1851
|
+
layer: allLayers
|
|
1852
|
+
})),
|
|
1853
|
+
shadowed: z.array(z.strictObject({
|
|
1854
|
+
id: z.string(),
|
|
1855
|
+
layer: allLayers,
|
|
1856
|
+
shadowedBy: z.enum(["agent", "workspace"])
|
|
1857
|
+
})),
|
|
1858
|
+
failed: z.array(z.strictObject({
|
|
1859
|
+
id: z.string(),
|
|
1860
|
+
layer: allLayers,
|
|
1861
|
+
reason: z.string()
|
|
1862
|
+
}))
|
|
1863
|
+
});
|
|
1864
|
+
/** Registers read-only views without granting filesystem access. */
|
|
1865
|
+
function registerSkillViews(ctx, execution, settings) {
|
|
1866
|
+
ctx.client.registerMethod({
|
|
1867
|
+
name: "list",
|
|
1868
|
+
params: z.strictObject({ agentId: z.string().min(1) }),
|
|
1869
|
+
result: SkillListResult,
|
|
1870
|
+
handle({ agentId }) {
|
|
1871
|
+
if (!execution.agent(agentId)) throw new Error(`no such agent: ${agentId}`);
|
|
1872
|
+
if (execution.workRoot === void 0) return {
|
|
1873
|
+
layers: [],
|
|
1874
|
+
skills: [],
|
|
1875
|
+
failed: []
|
|
1876
|
+
};
|
|
1877
|
+
const set = loadAgentSkills(execution.workRoot, agentId);
|
|
1878
|
+
return {
|
|
1879
|
+
layers: agentSkillDirectories(execution.workRoot, agentId).map(({ layer, path }) => ({
|
|
1880
|
+
layer,
|
|
1881
|
+
directory: path
|
|
1882
|
+
})),
|
|
1883
|
+
skills: set.loaded.map((skill) => ({
|
|
1884
|
+
id: skill.id,
|
|
1885
|
+
description: skill.description,
|
|
1886
|
+
layer: skill.layer,
|
|
1887
|
+
origin: readOrigin(skill.directory),
|
|
1888
|
+
issues: [...skill.issues]
|
|
1889
|
+
})),
|
|
1890
|
+
failed: set.failed.map((one) => ({
|
|
1891
|
+
...one,
|
|
1892
|
+
layer: one.layer
|
|
1893
|
+
}))
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
});
|
|
1897
|
+
const persistedTarget = z.strictObject({ sessionId: z.string().min(1) });
|
|
1898
|
+
const draftTarget = z.strictObject({
|
|
1899
|
+
agentId: z.string().min(1),
|
|
1900
|
+
workspaceId: z.string().min(1)
|
|
1901
|
+
});
|
|
1902
|
+
const target = z.union([persistedTarget, draftTarget]);
|
|
1903
|
+
const targetSet = async (input) => {
|
|
1904
|
+
if ("sessionId" in input) {
|
|
1905
|
+
const address = execution.address(input.sessionId);
|
|
1906
|
+
const agentId = execution.agentOf(input.sessionId, address);
|
|
1907
|
+
return loadSkills(execution.workRoot, agentId, address.workspaceId, settings(agentId).disabledSkills);
|
|
1908
|
+
}
|
|
1909
|
+
const currentAgent = () => {
|
|
1910
|
+
const agent = execution.agent(input.agentId);
|
|
1911
|
+
if (agent === void 0) throw new Error(`no such agent: ${input.agentId}`);
|
|
1912
|
+
if (!agent.startsSessions) throw new Error(`agent cannot start sessions: ${input.agentId}`);
|
|
1913
|
+
};
|
|
1914
|
+
currentAgent();
|
|
1915
|
+
const snapshot = await ctx.services.get("workspace-roots").read(input.workspaceId);
|
|
1916
|
+
currentAgent();
|
|
1917
|
+
const set = loadSkills(execution.workRoot, input.agentId, input.workspaceId, settings(input.agentId).disabledSkills);
|
|
1918
|
+
await snapshot.assertCurrent();
|
|
1919
|
+
currentAgent();
|
|
1920
|
+
return set;
|
|
1921
|
+
};
|
|
1922
|
+
ctx.client.registerMethod({
|
|
1923
|
+
name: "sessionSkills",
|
|
1924
|
+
params: target,
|
|
1925
|
+
result: SessionSkillsResult,
|
|
1926
|
+
async handle(input) {
|
|
1927
|
+
const set = await targetSet(input);
|
|
1928
|
+
return {
|
|
1929
|
+
loaded: set.loaded.map(({ id, description, layer }) => ({
|
|
1930
|
+
id,
|
|
1931
|
+
description,
|
|
1932
|
+
layer
|
|
1933
|
+
})),
|
|
1934
|
+
shadowed: [...set.shadowed],
|
|
1935
|
+
failed: [...set.failed]
|
|
1936
|
+
};
|
|
1937
|
+
}
|
|
1938
|
+
});
|
|
1939
|
+
ctx.client.registerMethod({
|
|
1940
|
+
name: "readSkill",
|
|
1941
|
+
params: z.union([persistedTarget.extend({ id: z.string().min(1) }), draftTarget.extend({ id: z.string().min(1) })]),
|
|
1942
|
+
result: z.strictObject({
|
|
1943
|
+
id: z.string(),
|
|
1944
|
+
description: z.string(),
|
|
1945
|
+
body: z.string()
|
|
1946
|
+
}),
|
|
1947
|
+
async handle(input) {
|
|
1948
|
+
const { id } = input;
|
|
1949
|
+
const set = await targetSet(input);
|
|
1950
|
+
const skill = set.loaded.find((one) => one.id === id);
|
|
1951
|
+
if (skill) return {
|
|
1952
|
+
id,
|
|
1953
|
+
description: skill.description,
|
|
1954
|
+
body: skill.body
|
|
1955
|
+
};
|
|
1956
|
+
const failed = set.failed.find((one) => one.id === id);
|
|
1957
|
+
if (failed) throw new Error(`skill "${id}" cannot be read: ${failed.reason}`);
|
|
1958
|
+
throw new Error(`no skill "${id}" is available to this composer`);
|
|
1959
|
+
}
|
|
1960
|
+
});
|
|
1961
|
+
}
|
|
1962
|
+
//#endregion
|
|
1963
|
+
//#region src/runtime/skills/install.ts
|
|
1964
|
+
/**
|
|
1965
|
+
* Taking a skill into a layer, letting one go, and rewriting one to the
|
|
1966
|
+
* specification — the three writes to a layer that are not `skills.write`.
|
|
1967
|
+
*
|
|
1968
|
+
* The caller hands a layer directory it has already resolved and an
|
|
1969
|
+
* identifier; every path below is joined from those two, never from anything
|
|
1970
|
+
* a plugin supplied. Each write is whole: a model call reads the old skill
|
|
1971
|
+
* or the complete new one, never half of either. That is done by staging
|
|
1972
|
+
* beside the layer (`skillStagingOf`, same filesystem) and finishing with one
|
|
1973
|
+
* rename; a replaced skill is moved aside first and moved back if the rename
|
|
1974
|
+
* in fails.
|
|
1975
|
+
*
|
|
1976
|
+
* Writes to one layer run one at a time. What a preview said about a name
|
|
1977
|
+
* being free can be out of date by the time the install lands, so the check
|
|
1978
|
+
* is made again under the lock, and the loser is told the name is taken.
|
|
1979
|
+
*/
|
|
1980
|
+
const skillStagingOf = (layerDirectory) => join(dirname(layerDirectory), ".skill-staging");
|
|
1981
|
+
/** One lock per layer directory: a queue of writes, each waiting for the
|
|
1982
|
+
* one before it. Process-local, which is enough — one gateway owns the
|
|
1983
|
+
* work root. */
|
|
1984
|
+
const queues = /* @__PURE__ */ new Map();
|
|
1985
|
+
function locked(layerDirectory, work) {
|
|
1986
|
+
const next = (queues.get(layerDirectory) ?? Promise.resolve()).then(work, work);
|
|
1987
|
+
queues.set(layerDirectory, next.catch(() => void 0));
|
|
1988
|
+
return next;
|
|
1989
|
+
}
|
|
1990
|
+
/** Whether `path` is one of the sealed paths or inside one. Both sides are
|
|
1991
|
+
* real paths, so a spelling cannot slip past. */
|
|
1992
|
+
function isSealed(path, sealed) {
|
|
1993
|
+
return sealed.some((one) => path === one || path.startsWith(`${one}${sep}`));
|
|
1994
|
+
}
|
|
1995
|
+
function realSealed(sealed) {
|
|
1996
|
+
return sealed.map((one) => {
|
|
1997
|
+
try {
|
|
1998
|
+
return realpathSync(one);
|
|
1999
|
+
} catch {
|
|
2000
|
+
return one;
|
|
2001
|
+
}
|
|
2002
|
+
});
|
|
2003
|
+
}
|
|
2004
|
+
function scratch(layerDirectory) {
|
|
2005
|
+
const root = skillStagingOf(layerDirectory);
|
|
2006
|
+
mkdirSync(root, {
|
|
2007
|
+
recursive: true,
|
|
2008
|
+
mode: 448
|
|
2009
|
+
});
|
|
2010
|
+
const directory = join(root, randomBytes(8).toString("hex"));
|
|
2011
|
+
mkdirSync(directory, { mode: 448 });
|
|
2012
|
+
return directory;
|
|
2013
|
+
}
|
|
2014
|
+
/** Every entry under `root`, relative to it, refusing a link or a sealed
|
|
2015
|
+
* path anywhere in the tree. `root` is already a real path and no link is
|
|
2016
|
+
* followed, so every entry's path is its real path too. */
|
|
2017
|
+
function walk(root, sealed) {
|
|
2018
|
+
const files = [];
|
|
2019
|
+
const directories = [];
|
|
2020
|
+
const stack = [""];
|
|
2021
|
+
while (stack.length > 0) {
|
|
2022
|
+
const here = stack.pop();
|
|
2023
|
+
for (const entry of readdirSync(join(root, here), { withFileTypes: true })) {
|
|
2024
|
+
const rel = here === "" ? entry.name : join(here, entry.name);
|
|
2025
|
+
if (isSealed(join(root, rel), sealed)) return {
|
|
2026
|
+
ok: false,
|
|
2027
|
+
reason: "sealed",
|
|
2028
|
+
message: `${rel} is inside the product's state directory`
|
|
2029
|
+
};
|
|
2030
|
+
if (entry.isSymbolicLink()) return {
|
|
2031
|
+
ok: false,
|
|
2032
|
+
reason: "unsafe-entry",
|
|
2033
|
+
message: `${rel} is a symbolic link`
|
|
2034
|
+
};
|
|
2035
|
+
if (entry.isDirectory()) {
|
|
2036
|
+
directories.push(rel);
|
|
2037
|
+
stack.push(rel);
|
|
2038
|
+
} else if (entry.isFile()) files.push(rel);
|
|
2039
|
+
else return {
|
|
2040
|
+
ok: false,
|
|
2041
|
+
reason: "unsafe-entry",
|
|
2042
|
+
message: `${rel} is not a regular file`
|
|
2043
|
+
};
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
return {
|
|
2047
|
+
ok: true,
|
|
2048
|
+
files,
|
|
2049
|
+
directories
|
|
2050
|
+
};
|
|
2051
|
+
}
|
|
2052
|
+
/** Copies the skill at `from` into `<layerDirectory>/<id>`, its `SKILL.md`
|
|
2053
|
+
* rewritten to the standard view with `name: <id>`, and the origin record
|
|
2054
|
+
* beside it. `from` must be a complete host path and is read without trimming or changing it.
|
|
2055
|
+
* Invalid roots are refused before filesystem access. */
|
|
2056
|
+
function installSkill(input) {
|
|
2057
|
+
const refuse = (reason, message) => ({
|
|
2058
|
+
ok: false,
|
|
2059
|
+
reason,
|
|
2060
|
+
message
|
|
2061
|
+
});
|
|
2062
|
+
if (!isStandardName(input.id)) return Promise.resolve(refuse("invalid-id", `a skill is named with lowercase letters, digits and single hyphens, at most 64 characters: ${input.id}`));
|
|
2063
|
+
if (!isCompleteSkillSourcePath(input.from)) return Promise.resolve(refuse("not-a-skill", `${input.from} is not absolute`));
|
|
2064
|
+
const origin = originText(input.origin);
|
|
2065
|
+
return locked(input.layerDirectory, () => {
|
|
2066
|
+
let from;
|
|
2067
|
+
try {
|
|
2068
|
+
from = realpathSync(input.from);
|
|
2069
|
+
} catch {
|
|
2070
|
+
return refuse("not-a-skill", `${input.from} does not exist`);
|
|
2071
|
+
}
|
|
2072
|
+
const sealed = realSealed(input.sealed);
|
|
2073
|
+
if (isSealed(from, sealed)) return refuse("sealed", `${input.from} is inside the product's state directory`);
|
|
2074
|
+
if (!lstatSync(from).isDirectory()) return refuse("not-a-skill", `${input.from} is not a directory`);
|
|
2075
|
+
const tree = walk(from, sealed);
|
|
2076
|
+
if (!tree.ok) return refuse(tree.reason, tree.message);
|
|
2077
|
+
if (!tree.files.includes("SKILL.md")) return refuse("not-a-skill", "SKILL.md is missing");
|
|
2078
|
+
const front = readFrontmatter(readFileSync(join(from, "SKILL.md"), "utf8"));
|
|
2079
|
+
const standard = front === void 0 ? void 0 : normalize$1(front, input.id);
|
|
2080
|
+
if (front === void 0 || standard === void 0) return refuse("not-a-skill", "SKILL.md has no description");
|
|
2081
|
+
if (conformance(asFrontmatter(standard), input.id).length > 0) return refuse("io", "the rewritten SKILL.md would not meet the specification");
|
|
2082
|
+
const target = join(input.layerDirectory, input.id);
|
|
2083
|
+
const taken = lstatSync(target, { throwIfNoEntry: false }) !== void 0;
|
|
2084
|
+
if (taken && !input.replace) return refuse("exists", `a skill named ${input.id} is already here`);
|
|
2085
|
+
mkdirSync(input.layerDirectory, { recursive: true });
|
|
2086
|
+
const work = scratch(input.layerDirectory);
|
|
2087
|
+
try {
|
|
2088
|
+
const fresh = join(work, input.id);
|
|
2089
|
+
mkdirSync(fresh);
|
|
2090
|
+
for (const directory of tree.directories) mkdirSync(join(fresh, directory));
|
|
2091
|
+
for (const file of tree.files) {
|
|
2092
|
+
copyFileSync(join(from, file), join(fresh, file));
|
|
2093
|
+
chmodSync(join(fresh, file), statSync(join(from, file)).mode & 511);
|
|
2094
|
+
}
|
|
2095
|
+
writeFileSync(join(fresh, "SKILL.md"), render(standard, front.rest));
|
|
2096
|
+
writeFileSync(join(fresh, ORIGIN_FILE), origin);
|
|
2097
|
+
if (!taken) renameSync(fresh, target);
|
|
2098
|
+
else {
|
|
2099
|
+
const old = join(work, "replaced");
|
|
2100
|
+
renameSync(target, old);
|
|
2101
|
+
try {
|
|
2102
|
+
renameSync(fresh, target);
|
|
2103
|
+
} catch (error) {
|
|
2104
|
+
renameSync(old, target);
|
|
2105
|
+
throw error;
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
return {
|
|
2109
|
+
ok: true,
|
|
2110
|
+
id: input.id,
|
|
2111
|
+
layer: input.layer
|
|
2112
|
+
};
|
|
2113
|
+
} catch (error) {
|
|
2114
|
+
return refuse("io", error instanceof Error ? error.message : String(error));
|
|
2115
|
+
} finally {
|
|
2116
|
+
rmSync(work, {
|
|
2117
|
+
recursive: true,
|
|
2118
|
+
force: true
|
|
2119
|
+
});
|
|
2120
|
+
}
|
|
2121
|
+
});
|
|
2122
|
+
}
|
|
2123
|
+
/** Removes `<layerDirectory>/<id>` whole: moved aside, then deleted. A link
|
|
2124
|
+
* standing there is removed as the link, never followed. */
|
|
2125
|
+
function uninstallSkill(layerDirectory, id) {
|
|
2126
|
+
if (!SKILL_ID.test(id)) return Promise.resolve({
|
|
2127
|
+
ok: false,
|
|
2128
|
+
reason: "invalid-id",
|
|
2129
|
+
message: `no such skill: ${id}`
|
|
2130
|
+
});
|
|
2131
|
+
return locked(layerDirectory, () => {
|
|
2132
|
+
const target = join(layerDirectory, id);
|
|
2133
|
+
if (lstatSync(target, { throwIfNoEntry: false }) === void 0) return {
|
|
2134
|
+
ok: false,
|
|
2135
|
+
reason: "missing",
|
|
2136
|
+
message: `no skill named ${id} here`
|
|
2137
|
+
};
|
|
2138
|
+
const work = scratch(layerDirectory);
|
|
2139
|
+
try {
|
|
2140
|
+
renameSync(target, join(work, id));
|
|
2141
|
+
return { ok: true };
|
|
2142
|
+
} catch (error) {
|
|
2143
|
+
return {
|
|
2144
|
+
ok: false,
|
|
2145
|
+
reason: "io",
|
|
2146
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2147
|
+
};
|
|
2148
|
+
} finally {
|
|
2149
|
+
rmSync(work, {
|
|
2150
|
+
recursive: true,
|
|
2151
|
+
force: true
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
});
|
|
2155
|
+
}
|
|
2156
|
+
/** Rewrites `<layerDirectory>/<id>/SKILL.md` to its standard view, the body
|
|
2157
|
+
* and every other file untouched. With `dryRun` it only says what it would
|
|
2158
|
+
* write. What is left afterwards can only be `dir-invalid`: a directory name
|
|
2159
|
+
* no file can fix. */
|
|
2160
|
+
function normalizeSkill(layerDirectory, id, dryRun) {
|
|
2161
|
+
if (!SKILL_ID.test(id)) return Promise.resolve({
|
|
2162
|
+
ok: false,
|
|
2163
|
+
reason: "invalid-id",
|
|
2164
|
+
message: `no such skill: ${id}`
|
|
2165
|
+
});
|
|
2166
|
+
const run = () => {
|
|
2167
|
+
const directory = join(layerDirectory, id);
|
|
2168
|
+
const file = join(directory, "SKILL.md");
|
|
2169
|
+
const found = lstatSync(file, { throwIfNoEntry: false });
|
|
2170
|
+
if (found === void 0 || !existsSync(directory)) return {
|
|
2171
|
+
ok: false,
|
|
2172
|
+
reason: "missing",
|
|
2173
|
+
message: `no skill named ${id} here`
|
|
2174
|
+
};
|
|
2175
|
+
if (!found.isFile()) return {
|
|
2176
|
+
ok: false,
|
|
2177
|
+
reason: "io",
|
|
2178
|
+
message: "SKILL.md is not a regular file"
|
|
2179
|
+
};
|
|
2180
|
+
const front = readFrontmatter(readFileSync(file, "utf8"));
|
|
2181
|
+
const standard = front === void 0 ? void 0 : normalize$1(front, id);
|
|
2182
|
+
if (front === void 0 || standard === void 0) return {
|
|
2183
|
+
ok: false,
|
|
2184
|
+
reason: "not-a-skill",
|
|
2185
|
+
message: "SKILL.md has no description"
|
|
2186
|
+
};
|
|
2187
|
+
const text = render(standard, front.rest);
|
|
2188
|
+
const frontmatter = text.slice(0, text.length - front.rest.length);
|
|
2189
|
+
const remaining = conformance(asFrontmatter(standard), id);
|
|
2190
|
+
if (!dryRun) {
|
|
2191
|
+
const temporary = join(directory, `.SKILL.md.${randomBytes(6).toString("hex")}`);
|
|
2192
|
+
try {
|
|
2193
|
+
writeFileSync(temporary, text);
|
|
2194
|
+
renameSync(temporary, file);
|
|
2195
|
+
} catch (error) {
|
|
2196
|
+
rmSync(temporary, { force: true });
|
|
2197
|
+
return {
|
|
2198
|
+
ok: false,
|
|
2199
|
+
reason: "io",
|
|
2200
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2201
|
+
};
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
return {
|
|
2205
|
+
ok: true,
|
|
2206
|
+
frontmatter,
|
|
2207
|
+
remaining
|
|
2208
|
+
};
|
|
2209
|
+
};
|
|
2210
|
+
return dryRun ? Promise.resolve().then(run) : locked(layerDirectory, run);
|
|
2211
|
+
}
|
|
2212
|
+
/** Removes whatever a stopped gateway left in the staging directories of
|
|
2213
|
+
* these layers. Called once, when the service is built. */
|
|
2214
|
+
function sweepStaging(layerDirectories) {
|
|
2215
|
+
for (const layer of layerDirectories) rmSync(skillStagingOf(layer), {
|
|
2216
|
+
recursive: true,
|
|
2217
|
+
force: true
|
|
2218
|
+
});
|
|
2219
|
+
}
|
|
2220
|
+
//#endregion
|
|
2221
|
+
//#region src/runtime/skills/path-semantics.ts
|
|
2222
|
+
/** Scope checks for canonical skill paths; object names retain their actual case. */
|
|
2223
|
+
/** Checks a canonical root boundary using the physical host's path separators. */
|
|
2224
|
+
function containsSkillPath(root, target, platform = process.platform) {
|
|
2225
|
+
const paths = platform === "win32" ? win32 : posix;
|
|
2226
|
+
const base = paths.normalize(root);
|
|
2227
|
+
const file = paths.normalize(target);
|
|
2228
|
+
return file === base || file.startsWith(base.endsWith(paths.sep) ? base : `${base}${paths.sep}`);
|
|
2229
|
+
}
|
|
2230
|
+
//#endregion
|
|
2231
|
+
//#region src/runtime/skills/service.ts
|
|
2232
|
+
/**
|
|
2233
|
+
* The `skills` service a plugin receives: what this call can see, the body of
|
|
2234
|
+
* one of them, and writing one down.
|
|
2235
|
+
*
|
|
2236
|
+
* The host computes every path. A plugin names a layer and an identifier and
|
|
2237
|
+
* never a path — which is the whole of the guarantee that a tool cannot write
|
|
2238
|
+
* into another agent's or another workspace's skills, because there is no
|
|
2239
|
+
* field in which to say it.
|
|
2240
|
+
*/
|
|
2241
|
+
/** A name that is safe to join onto a path. Checked before any join, because
|
|
2242
|
+
* it is the only thing a caller supplies that becomes one. */
|
|
2243
|
+
function named(id) {
|
|
2244
|
+
return SKILL_ID.test(id);
|
|
2245
|
+
}
|
|
2246
|
+
function createSkills(deps) {
|
|
2247
|
+
const agentOf = deps.agentOf ?? ((ctx) => ctx.address.agentId);
|
|
2248
|
+
const load = (ctx) => {
|
|
2249
|
+
const agentId = agentOf(ctx);
|
|
2250
|
+
return loadSkills(deps.workRoot, agentId, ctx.address.workspaceId, deps.disabledSkills?.(agentId));
|
|
2251
|
+
};
|
|
2252
|
+
const hasAgent = deps.hasAgent ?? (() => true);
|
|
2253
|
+
const sealed = deps.sealed ?? (() => []);
|
|
2254
|
+
const writePreparedFile = deps.writePreparedFile ?? ((fd, content) => writeFileSync(fd, content));
|
|
2255
|
+
const writeAuthorities = /* @__PURE__ */ new WeakMap();
|
|
2256
|
+
if (deps.workRoot !== void 0) {
|
|
2257
|
+
const root = deps.workRoot;
|
|
2258
|
+
let agentIds = [];
|
|
2259
|
+
try {
|
|
2260
|
+
agentIds = readdirSync(join(root, "agents"), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
2261
|
+
} catch {
|
|
2262
|
+
agentIds = [];
|
|
2263
|
+
}
|
|
2264
|
+
sweepStaging(agentIds.flatMap((id) => agentSkillDirectories(root, id).map((one) => one.path)));
|
|
2265
|
+
sweepStaging([join(root, "global", "skills")]);
|
|
2266
|
+
}
|
|
2267
|
+
/** The layer directory a target names, or why there is none. */
|
|
2268
|
+
const layerOf = (target, layer) => {
|
|
2269
|
+
if (deps.workRoot === void 0) return {
|
|
2270
|
+
ok: false,
|
|
2271
|
+
reason: "no-work-root",
|
|
2272
|
+
message: "this runtime keeps no skills on disk"
|
|
2273
|
+
};
|
|
2274
|
+
const agentId = "ctx" in target ? agentOf(target.ctx) : target.agentId;
|
|
2275
|
+
if (!("ctx" in target) && !hasAgent(agentId)) return {
|
|
2276
|
+
ok: false,
|
|
2277
|
+
reason: "no-such-agent",
|
|
2278
|
+
message: `no such agent: ${agentId}`
|
|
2279
|
+
};
|
|
2280
|
+
const path = agentSkillDirectories(deps.workRoot, agentId).find((one) => one.layer === layer)?.path;
|
|
2281
|
+
if (path === void 0) return {
|
|
2282
|
+
ok: false,
|
|
2283
|
+
reason: "no-work-root",
|
|
2284
|
+
message: "no such layer"
|
|
2285
|
+
};
|
|
2286
|
+
return {
|
|
2287
|
+
ok: true,
|
|
2288
|
+
path
|
|
2289
|
+
};
|
|
2290
|
+
};
|
|
2291
|
+
const directoryOf = (ctx, layer) => {
|
|
2292
|
+
if (deps.workRoot === void 0) return void 0;
|
|
2293
|
+
return skillDirectories(deps.workRoot, agentOf(ctx), ctx.address.workspaceId).find((entry) => entry.layer === layer)?.path;
|
|
2294
|
+
};
|
|
2295
|
+
const physicalPath = (path) => {
|
|
2296
|
+
const missing = [];
|
|
2297
|
+
let current = path;
|
|
2298
|
+
while (!existsSync(current)) {
|
|
2299
|
+
missing.unshift(basename(current));
|
|
2300
|
+
const parent = dirname(current);
|
|
2301
|
+
if (parent === current) throw new Error(`cannot resolve ${path}`);
|
|
2302
|
+
current = parent;
|
|
2303
|
+
}
|
|
2304
|
+
return join(realpathSync(current), ...missing);
|
|
2305
|
+
};
|
|
2306
|
+
const snapshot = (target, layer, id) => {
|
|
2307
|
+
if (!named(id)) return {
|
|
2308
|
+
ok: false,
|
|
2309
|
+
message: `invalid skill name: ${id}`
|
|
2310
|
+
};
|
|
2311
|
+
const layerDirectory = layer === "workspace" ? "ctx" in target ? directoryOf(target.ctx, layer) : void 0 : "ctx" in target ? directoryOf(target.ctx, layer) : (() => {
|
|
2312
|
+
const found = layerOf(target, layer);
|
|
2313
|
+
return found.ok ? found.path : void 0;
|
|
2314
|
+
})();
|
|
2315
|
+
if (layerDirectory === void 0) return {
|
|
2316
|
+
ok: false,
|
|
2317
|
+
message: `the ${layer} skill layer is unavailable`
|
|
2318
|
+
};
|
|
2319
|
+
const root = join(layerDirectory, id);
|
|
2320
|
+
const hash = createHash("sha256");
|
|
2321
|
+
const files = [];
|
|
2322
|
+
const visit = (path, relative) => {
|
|
2323
|
+
const entry = lstatSync(path);
|
|
2324
|
+
hash.update(`${relative}\0${entry.mode & 511}\0`);
|
|
2325
|
+
if (entry.isSymbolicLink()) hash.update(`link\0${readlinkSync(path)}\0`);
|
|
2326
|
+
else if (entry.isDirectory()) {
|
|
2327
|
+
hash.update("directory\0");
|
|
2328
|
+
for (const name of readdirSync(path).sort()) visit(join(path, name), relative === "" ? name : `${relative}/${name}`);
|
|
2329
|
+
} else if (entry.isFile()) {
|
|
2330
|
+
const content = readFileSync(path);
|
|
2331
|
+
hash.update("file\0").update(content);
|
|
2332
|
+
files.push({
|
|
2333
|
+
path: relative,
|
|
2334
|
+
bytes: content.byteLength,
|
|
2335
|
+
executable: (entry.mode & 73) !== 0
|
|
2336
|
+
});
|
|
2337
|
+
} else throw new Error(`${relative} is not a regular file, directory or link`);
|
|
2338
|
+
};
|
|
2339
|
+
try {
|
|
2340
|
+
if (lstatSync(root, { throwIfNoEntry: false }) === void 0) return {
|
|
2341
|
+
ok: true,
|
|
2342
|
+
exists: false,
|
|
2343
|
+
digest: hash.update("missing").digest("hex"),
|
|
2344
|
+
files
|
|
2345
|
+
};
|
|
2346
|
+
visit(root, "");
|
|
2347
|
+
return {
|
|
2348
|
+
ok: true,
|
|
2349
|
+
exists: true,
|
|
2350
|
+
digest: hash.digest("hex"),
|
|
2351
|
+
files
|
|
2352
|
+
};
|
|
2353
|
+
} catch (error) {
|
|
2354
|
+
return {
|
|
2355
|
+
ok: false,
|
|
2356
|
+
message: error instanceof Error ? error.message : String(error)
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2359
|
+
};
|
|
2360
|
+
const prepareWrite = (ctx, input) => {
|
|
2361
|
+
if (!isStandardName(input.id)) return {
|
|
2362
|
+
ok: false,
|
|
2363
|
+
message: `invalid skill name: ${input.id}`
|
|
2364
|
+
};
|
|
2365
|
+
if (input.description.trim() === "") return {
|
|
2366
|
+
ok: false,
|
|
2367
|
+
message: "a skill needs a description"
|
|
2368
|
+
};
|
|
2369
|
+
const layerDirectory = directoryOf(ctx, input.layer);
|
|
2370
|
+
if (layerDirectory === void 0) return {
|
|
2371
|
+
ok: false,
|
|
2372
|
+
message: "this runtime keeps no skills on disk"
|
|
2373
|
+
};
|
|
2374
|
+
const directory = join(layerDirectory, input.id);
|
|
2375
|
+
const entry = join(directory, "SKILL.md");
|
|
2376
|
+
const verdict = deps.fence.allows(ctx, entry, "write");
|
|
2377
|
+
if (!verdict.allowed) {
|
|
2378
|
+
if ("ask" in verdict) return {
|
|
2379
|
+
ok: false,
|
|
2380
|
+
ask: verdict.ask
|
|
2381
|
+
};
|
|
2382
|
+
return {
|
|
2383
|
+
ok: false,
|
|
2384
|
+
message: verdict.message
|
|
2385
|
+
};
|
|
2386
|
+
}
|
|
2387
|
+
const current = snapshot({ ctx }, input.layer, input.id);
|
|
2388
|
+
if (!current.ok) return current;
|
|
2389
|
+
const root = lstatSync(directory, { throwIfNoEntry: false });
|
|
2390
|
+
if (root !== void 0 && !root.isDirectory()) return {
|
|
2391
|
+
ok: false,
|
|
2392
|
+
message: "the skill target is not a directory"
|
|
2393
|
+
};
|
|
2394
|
+
const names = /* @__PURE__ */ new Set();
|
|
2395
|
+
const files = [];
|
|
2396
|
+
const contents = [{
|
|
2397
|
+
name: "SKILL.md",
|
|
2398
|
+
after: render({
|
|
2399
|
+
name: input.id,
|
|
2400
|
+
description: input.description.trim()
|
|
2401
|
+
}, `\n${input.body.trim()}\n`)
|
|
2402
|
+
}, ...(input.files ?? []).map((file) => ({
|
|
2403
|
+
name: file.name,
|
|
2404
|
+
after: file.content
|
|
2405
|
+
}))];
|
|
2406
|
+
for (const file of contents) {
|
|
2407
|
+
if (names.has(file.name) || file.name !== "SKILL.md" && !named(file.name.replace(/\.[a-z0-9]+$/i, ""))) return {
|
|
2408
|
+
ok: false,
|
|
2409
|
+
message: `invalid or duplicate skill file: ${file.name}`
|
|
2410
|
+
};
|
|
2411
|
+
names.add(file.name);
|
|
2412
|
+
const path = join(directory, file.name);
|
|
2413
|
+
const found = lstatSync(path, { throwIfNoEntry: false });
|
|
2414
|
+
if (found !== void 0 && !found.isFile()) return {
|
|
2415
|
+
ok: false,
|
|
2416
|
+
message: `${file.name} is not a regular file`
|
|
2417
|
+
};
|
|
2418
|
+
files.push({
|
|
2419
|
+
name: file.name,
|
|
2420
|
+
...found === void 0 ? {} : { before: readFileSync(path, "utf8") },
|
|
2421
|
+
after: file.after
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
const plan = Object.freeze({
|
|
2425
|
+
input: Object.freeze({
|
|
2426
|
+
...input,
|
|
2427
|
+
...input.files === void 0 ? {} : { files: Object.freeze(input.files.map((file) => Object.freeze({ ...file }))) }
|
|
2428
|
+
}),
|
|
2429
|
+
expectedDigest: current.digest,
|
|
2430
|
+
authorizedEntry: verdict.path,
|
|
2431
|
+
physicalLayerDirectory: physicalPath(layerDirectory),
|
|
2432
|
+
files: Object.freeze(files.map((file) => Object.freeze(file)))
|
|
2433
|
+
});
|
|
2434
|
+
writeAuthorities.set(plan, ctx);
|
|
2435
|
+
return {
|
|
2436
|
+
ok: true,
|
|
2437
|
+
plan
|
|
2438
|
+
};
|
|
2439
|
+
};
|
|
2440
|
+
const checkWrite = (ctx, plan) => {
|
|
2441
|
+
const authorizedContext = writeAuthorities.get(plan);
|
|
2442
|
+
if (authorizedContext === void 0 || authorizedContext.sessionId !== ctx.sessionId || authorizedContext.address.agentId !== ctx.address.agentId || authorizedContext.address.workspaceId !== ctx.address.workspaceId) return false;
|
|
2443
|
+
const layerDirectory = directoryOf(ctx, plan.input.layer);
|
|
2444
|
+
if (layerDirectory === void 0) return false;
|
|
2445
|
+
try {
|
|
2446
|
+
if (physicalPath(layerDirectory) !== plan.physicalLayerDirectory) return false;
|
|
2447
|
+
const entry = join(layerDirectory, plan.input.id, "SKILL.md");
|
|
2448
|
+
const verdict = deps.fence.allows(authorizedContext, entry, "write");
|
|
2449
|
+
if (!verdict.allowed || verdict.path !== plan.authorizedEntry) return false;
|
|
2450
|
+
const current = snapshot({ ctx }, plan.input.layer, plan.input.id);
|
|
2451
|
+
return current.ok && current.digest === plan.expectedDigest;
|
|
2452
|
+
} catch {
|
|
2453
|
+
return false;
|
|
2454
|
+
}
|
|
2455
|
+
};
|
|
2456
|
+
const commitWrite = (ctx, plan) => {
|
|
2457
|
+
if (!checkWrite(ctx, plan)) return {
|
|
2458
|
+
ok: false,
|
|
2459
|
+
message: "the skill path or contents changed after approval"
|
|
2460
|
+
};
|
|
2461
|
+
const layerDirectory = directoryOf(ctx, plan.input.layer);
|
|
2462
|
+
if (layerDirectory === void 0) return {
|
|
2463
|
+
ok: false,
|
|
2464
|
+
message: "this runtime keeps no skills on disk"
|
|
2465
|
+
};
|
|
2466
|
+
const directory = join(layerDirectory, plan.input.id);
|
|
2467
|
+
const written = [];
|
|
2468
|
+
let uncertain;
|
|
2469
|
+
try {
|
|
2470
|
+
mkdirSync(directory, { recursive: true });
|
|
2471
|
+
if (!lstatSync(directory).isDirectory()) return {
|
|
2472
|
+
ok: false,
|
|
2473
|
+
message: "the skill target moved through a link"
|
|
2474
|
+
};
|
|
2475
|
+
const home = realpathSync(directory);
|
|
2476
|
+
if (physicalPath(layerDirectory) !== plan.physicalLayerDirectory) return {
|
|
2477
|
+
ok: false,
|
|
2478
|
+
message: "the skill layer moved after approval"
|
|
2479
|
+
};
|
|
2480
|
+
for (const file of plan.files) {
|
|
2481
|
+
const fd = openSync(join(home, file.name), constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 420);
|
|
2482
|
+
uncertain = file.name;
|
|
2483
|
+
try {
|
|
2484
|
+
writePreparedFile(fd, file.after, file.name);
|
|
2485
|
+
} finally {
|
|
2486
|
+
closeSync(fd);
|
|
2487
|
+
}
|
|
2488
|
+
written.push(file.name);
|
|
2489
|
+
uncertain = void 0;
|
|
2490
|
+
}
|
|
2491
|
+
return {
|
|
2492
|
+
ok: true,
|
|
2493
|
+
id: plan.input.id,
|
|
2494
|
+
layer: plan.input.layer
|
|
2495
|
+
};
|
|
2496
|
+
} catch (error) {
|
|
2497
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2498
|
+
return written.length > 0 || uncertain !== void 0 ? {
|
|
2499
|
+
ok: false,
|
|
2500
|
+
message,
|
|
2501
|
+
partial: true,
|
|
2502
|
+
written,
|
|
2503
|
+
...uncertain ? { uncertain } : {}
|
|
2504
|
+
} : {
|
|
2505
|
+
ok: false,
|
|
2506
|
+
message
|
|
2507
|
+
};
|
|
2508
|
+
}
|
|
2509
|
+
};
|
|
2510
|
+
return {
|
|
2511
|
+
snapshot,
|
|
2512
|
+
prepareWrite,
|
|
2513
|
+
checkWrite,
|
|
2514
|
+
commitWrite,
|
|
2515
|
+
list(ctx) {
|
|
2516
|
+
return load(ctx).loaded.map((skill) => ({
|
|
2517
|
+
id: skill.id,
|
|
2518
|
+
description: skill.description,
|
|
2519
|
+
layer: skill.layer
|
|
2520
|
+
}));
|
|
2521
|
+
},
|
|
2522
|
+
read(ctx, id, file) {
|
|
2523
|
+
if (!named(id)) return {
|
|
2524
|
+
ok: false,
|
|
2525
|
+
message: `no such skill: ${id}`
|
|
2526
|
+
};
|
|
2527
|
+
const set = load(ctx);
|
|
2528
|
+
const skill = set.loaded.find((entry) => entry.id === id);
|
|
2529
|
+
if (skill === void 0) {
|
|
2530
|
+
const names = set.loaded.map((entry) => entry.id).join(", ");
|
|
2531
|
+
return {
|
|
2532
|
+
ok: false,
|
|
2533
|
+
message: names === "" ? `no such skill: ${id}` : `no such skill: ${id}. Available: ${names}`
|
|
2534
|
+
};
|
|
2535
|
+
}
|
|
2536
|
+
if (file === void 0) return {
|
|
2537
|
+
ok: true,
|
|
2538
|
+
content: skill.body
|
|
2539
|
+
};
|
|
2540
|
+
if (isAbsolute(file)) return {
|
|
2541
|
+
ok: false,
|
|
2542
|
+
message: `${file} is not inside the skill`
|
|
2543
|
+
};
|
|
2544
|
+
const target = resolve(skill.directory, file);
|
|
2545
|
+
const root = existsSync(skill.directory) ? realpathSync(skill.directory) : skill.directory;
|
|
2546
|
+
const real = existsSync(target) ? realpathSync(target) : target;
|
|
2547
|
+
if (!containsSkillPath(root, real)) return {
|
|
2548
|
+
ok: false,
|
|
2549
|
+
message: `${file} is not inside the skill ${id}`
|
|
2550
|
+
};
|
|
2551
|
+
try {
|
|
2552
|
+
return {
|
|
2553
|
+
ok: true,
|
|
2554
|
+
content: readFileSync(real, "utf8")
|
|
2555
|
+
};
|
|
2556
|
+
} catch {
|
|
2557
|
+
return {
|
|
2558
|
+
ok: false,
|
|
2559
|
+
message: `${file} could not be read from the skill ${id}`
|
|
2560
|
+
};
|
|
2561
|
+
}
|
|
2562
|
+
},
|
|
2563
|
+
write(ctx, input) {
|
|
2564
|
+
if (!isStandardName(input.id)) return {
|
|
2565
|
+
ok: false,
|
|
2566
|
+
message: `a skill is named with lowercase letters, digits and single hyphens, at most 64 characters: ${input.id}`
|
|
2567
|
+
};
|
|
2568
|
+
if (input.description.trim() === "") return {
|
|
2569
|
+
ok: false,
|
|
2570
|
+
message: "a skill needs a description: one line saying what it is for"
|
|
2571
|
+
};
|
|
2572
|
+
for (const extra of input.files ?? []) if (!named(extra.name.replace(/\.[a-z0-9]+$/i, ""))) return {
|
|
2573
|
+
ok: false,
|
|
2574
|
+
message: `a file beside a skill is named plainly: ${extra.name}`
|
|
2575
|
+
};
|
|
2576
|
+
const layerDirectory = directoryOf(ctx, input.layer);
|
|
2577
|
+
if (layerDirectory === void 0) return {
|
|
2578
|
+
ok: false,
|
|
2579
|
+
message: "this runtime keeps no skills on disk"
|
|
2580
|
+
};
|
|
2581
|
+
const directory = join(layerDirectory, input.id);
|
|
2582
|
+
const entry = join(directory, "SKILL.md");
|
|
2583
|
+
const verdict = deps.fence.allows(ctx, entry, "write");
|
|
2584
|
+
if (!verdict.allowed) {
|
|
2585
|
+
if ("ask" in verdict) return {
|
|
2586
|
+
ok: false,
|
|
2587
|
+
ask: verdict.ask
|
|
2588
|
+
};
|
|
2589
|
+
return {
|
|
2590
|
+
ok: false,
|
|
2591
|
+
message: verdict.message
|
|
2592
|
+
};
|
|
2593
|
+
}
|
|
2594
|
+
mkdirSync(dirname(verdict.path), { recursive: true });
|
|
2595
|
+
const home = realpathSync(dirname(verdict.path));
|
|
2596
|
+
for (const extra of input.files ?? []) {
|
|
2597
|
+
const found = lstatSync(join(home, extra.name), { throwIfNoEntry: false });
|
|
2598
|
+
if (found?.isSymbolicLink()) return {
|
|
2599
|
+
ok: false,
|
|
2600
|
+
message: `${extra.name} in the skill ${input.id} is a link`
|
|
2601
|
+
};
|
|
2602
|
+
if (found?.isDirectory()) return {
|
|
2603
|
+
ok: false,
|
|
2604
|
+
message: `${extra.name} in the skill ${input.id} is a directory`
|
|
2605
|
+
};
|
|
2606
|
+
}
|
|
2607
|
+
const document = render({
|
|
2608
|
+
name: input.id,
|
|
2609
|
+
description: input.description.trim()
|
|
2610
|
+
}, `\n${input.body.trim()}\n`);
|
|
2611
|
+
writeFileSync(verdict.path, document);
|
|
2612
|
+
for (const extra of input.files ?? []) {
|
|
2613
|
+
const fd = openSync(join(home, extra.name), constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 420);
|
|
2614
|
+
try {
|
|
2615
|
+
writeSync(fd, extra.content);
|
|
2616
|
+
} finally {
|
|
2617
|
+
closeSync(fd);
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
return {
|
|
2621
|
+
ok: true,
|
|
2622
|
+
id: input.id,
|
|
2623
|
+
layer: input.layer
|
|
2624
|
+
};
|
|
2625
|
+
},
|
|
2626
|
+
agentOf,
|
|
2627
|
+
async install(target, input) {
|
|
2628
|
+
const layer = layerOf(target, input.layer);
|
|
2629
|
+
if (!layer.ok) return layer;
|
|
2630
|
+
return installSkill({
|
|
2631
|
+
...input,
|
|
2632
|
+
layerDirectory: layer.path,
|
|
2633
|
+
sealed: sealed()
|
|
2634
|
+
});
|
|
2635
|
+
},
|
|
2636
|
+
async uninstall(target, input) {
|
|
2637
|
+
const layer = layerOf(target, input.layer);
|
|
2638
|
+
if (!layer.ok) return layer;
|
|
2639
|
+
return uninstallSkill(layer.path, input.id);
|
|
2640
|
+
},
|
|
2641
|
+
async normalize(target, input) {
|
|
2642
|
+
const layer = layerOf(target, input.layer);
|
|
2643
|
+
if (!layer.ok) return layer;
|
|
2644
|
+
return normalizeSkill(layer.path, input.id, input.dryRun === true);
|
|
2645
|
+
},
|
|
2646
|
+
inspect(directory, id) {
|
|
2647
|
+
let text;
|
|
2648
|
+
try {
|
|
2649
|
+
text = readFileSync(join(directory, "SKILL.md"), "utf8");
|
|
2650
|
+
} catch {
|
|
2651
|
+
return {
|
|
2652
|
+
ok: false,
|
|
2653
|
+
message: "SKILL.md is missing or unreadable"
|
|
2654
|
+
};
|
|
2655
|
+
}
|
|
2656
|
+
const front = readFrontmatter(text);
|
|
2657
|
+
if (front === void 0) return {
|
|
2658
|
+
ok: false,
|
|
2659
|
+
message: "SKILL.md must open with a --- frontmatter block"
|
|
2660
|
+
};
|
|
2661
|
+
const standard = normalize$1(front, id);
|
|
2662
|
+
if (standard === void 0) return {
|
|
2663
|
+
ok: false,
|
|
2664
|
+
message: "SKILL.md has no description"
|
|
2665
|
+
};
|
|
2666
|
+
const declared = front.fields.name;
|
|
2667
|
+
return {
|
|
2668
|
+
ok: true,
|
|
2669
|
+
...typeof declared === "string" ? { declaredName: declared } : {},
|
|
2670
|
+
description: standard.description,
|
|
2671
|
+
issues: conformance(front, id)
|
|
2672
|
+
};
|
|
2673
|
+
},
|
|
2674
|
+
layerIds(target) {
|
|
2675
|
+
const names = (layer) => {
|
|
2676
|
+
const found = layerOf(target, layer);
|
|
2677
|
+
if (!found.ok) return [];
|
|
2678
|
+
try {
|
|
2679
|
+
return readdirSync(found.path, { withFileTypes: true }).filter((entry) => entry.isDirectory() || entry.isSymbolicLink()).map((entry) => entry.name);
|
|
2680
|
+
} catch {
|
|
2681
|
+
return [];
|
|
2682
|
+
}
|
|
2683
|
+
};
|
|
2684
|
+
return {
|
|
2685
|
+
global: names("global"),
|
|
2686
|
+
agent: names("agent")
|
|
2687
|
+
};
|
|
2688
|
+
}
|
|
2689
|
+
};
|
|
2690
|
+
}
|
|
2691
|
+
//#endregion
|
|
2692
|
+
//#region src/runtime/skills/contributor.ts
|
|
2693
|
+
function skillCatalogueContributor(workRoot, agentOf = (view) => view.address.agentId, disabled = () => []) {
|
|
2694
|
+
return {
|
|
2695
|
+
slot: "system",
|
|
2696
|
+
id: "skills",
|
|
2697
|
+
placement: {
|
|
2698
|
+
chapter: "capabilities",
|
|
2699
|
+
order: 0,
|
|
2700
|
+
category: "skills",
|
|
2701
|
+
requires: ["skill_read"]
|
|
2702
|
+
},
|
|
2703
|
+
async contribute(view) {
|
|
2704
|
+
const agentId = agentOf(view);
|
|
2705
|
+
const set = loadSkills(workRoot, agentId, view.address.workspaceId, disabled(agentId));
|
|
2706
|
+
if (set.loaded.length === 0) return {};
|
|
2707
|
+
return { system: [`These skills are available. Each is a way of doing something that somebody wrote down for you. Read one with \`skill_read\` when its line matches what you are about to do — the line is all you have until you do:\n${set.loaded.map((skill) => `- ${skill.id}: ${skill.description}`).join("\n")}`] };
|
|
2708
|
+
}
|
|
2709
|
+
};
|
|
2710
|
+
}
|
|
2711
|
+
//#endregion
|
|
2712
|
+
//#region src/runtime/configuration.ts
|
|
2713
|
+
/** Complete owner configuration; arrays preserve preload order. */
|
|
2714
|
+
const SkillAgentConfiguration = z.strictObject({
|
|
2715
|
+
skills: z.array(z.string()).default([]),
|
|
2716
|
+
disabledSkills: z.array(z.string().min(1).refine((id) => id.trim() !== "", "a disabled skill needs an id")).default([])
|
|
2717
|
+
}).refine((value) => !value.skills.some((id) => value.disabledSkills.includes(id)), "disabled skills cannot be preloaded").default({
|
|
2718
|
+
skills: [],
|
|
2719
|
+
disabledSkills: []
|
|
2720
|
+
});
|
|
2721
|
+
/** Registers atomic Agent saves and the existing preload prompt contribution. */
|
|
2722
|
+
function registerSkillConfiguration(ctx, execution, store) {
|
|
2723
|
+
const read = (agentId) => SkillAgentConfiguration.parse(store.read(ctx.pluginName, agentId) ?? {});
|
|
2724
|
+
ctx.agentConfiguration.register({
|
|
2725
|
+
schema: SkillAgentConfiguration,
|
|
2726
|
+
read,
|
|
2727
|
+
prepare(agentId, value) {
|
|
2728
|
+
const next = {
|
|
2729
|
+
...value,
|
|
2730
|
+
disabledSkills: [...new Set(value.disabledSkills)].sort()
|
|
2731
|
+
};
|
|
2732
|
+
return {
|
|
2733
|
+
apply: () => store.write(ctx.pluginName, agentId, next),
|
|
2734
|
+
abort() {},
|
|
2735
|
+
settle() {}
|
|
2736
|
+
};
|
|
2737
|
+
}
|
|
2738
|
+
});
|
|
2739
|
+
ctx.context.contribute({
|
|
2740
|
+
slot: "system",
|
|
2741
|
+
id: "skill-preload",
|
|
2742
|
+
placement: {
|
|
2743
|
+
chapter: "capabilities",
|
|
2744
|
+
order: 20,
|
|
2745
|
+
category: "skills"
|
|
2746
|
+
},
|
|
2747
|
+
async contribute(view) {
|
|
2748
|
+
const agentId = execution.agentOf(view.state.sessionId, view.address);
|
|
2749
|
+
const { skills, disabledSkills } = read(agentId);
|
|
2750
|
+
const wanted = skills.filter((id) => !disabledSkills.includes(id));
|
|
2751
|
+
const loaded = wanted.length ? loadAgentSkills(execution.workRoot, agentId).loaded : [];
|
|
2752
|
+
return { system: wanted.map((id) => {
|
|
2753
|
+
const skill = loaded.find((one) => one.id === id);
|
|
2754
|
+
return skill ? `Skill ${id}:\n${skill.body}` : `[skill missing: ${id}]`;
|
|
2755
|
+
}) };
|
|
2756
|
+
}
|
|
2757
|
+
});
|
|
2758
|
+
return read;
|
|
2759
|
+
}
|
|
2760
|
+
//#endregion
|
|
2761
|
+
//#region src/tools/install-edit.ts
|
|
2762
|
+
const InstallInput = z.strictObject({
|
|
2763
|
+
source: SkillSource,
|
|
2764
|
+
layer: z.enum(["agent", "global"]).default("agent"),
|
|
2765
|
+
pick: z.array(z.string()).optional(),
|
|
2766
|
+
id: z.string().optional(),
|
|
2767
|
+
replace: z.boolean().optional()
|
|
2768
|
+
});
|
|
2769
|
+
const error = (message) => ({
|
|
2770
|
+
content: message,
|
|
2771
|
+
isError: true
|
|
2772
|
+
});
|
|
2773
|
+
/** Holds fetched Skill bytes until the host has approved and checked their targets. */
|
|
2774
|
+
function installSkillEdit(deps) {
|
|
2775
|
+
return {
|
|
2776
|
+
name: "skill_install",
|
|
2777
|
+
description: "Install skills from ClawHub, Tencent SkillHub, skills.sh, GitHub or a local directory or zip. Choose a layer, optional pick keys and optional replacement; approval covers the selected files and targets.",
|
|
2778
|
+
inputSchema: InstallInput,
|
|
2779
|
+
async execute(input, ctx) {
|
|
2780
|
+
const previewKey = JSON.stringify([
|
|
2781
|
+
ctx.sessionId,
|
|
2782
|
+
ctx.turn,
|
|
2783
|
+
ctx.toolCallId,
|
|
2784
|
+
ctx.address,
|
|
2785
|
+
input.source
|
|
2786
|
+
]);
|
|
2787
|
+
let preview = deps.installer.find(previewKey);
|
|
2788
|
+
if (!preview && ctx.answer?.answers.some((answer) => answer.questionId.startsWith(deps.approval.questionId("install-") ?? "\0"))) return error("The approved source preview expired; request installation again.");
|
|
2789
|
+
if (!preview && input.source.kind === "local") {
|
|
2790
|
+
const verdict = deps.fence.allows(ctx, input.source.path, "read");
|
|
2791
|
+
if (!verdict.allowed) return "ask" in verdict ? verdict.ask : error(verdict.message);
|
|
2792
|
+
}
|
|
2793
|
+
try {
|
|
2794
|
+
preview ??= await deps.installer.preview(input.source, { ctx }, {
|
|
2795
|
+
key: previewKey,
|
|
2796
|
+
signal: ctx.signal
|
|
2797
|
+
});
|
|
2798
|
+
} catch (failure) {
|
|
2799
|
+
return error(failure instanceof InstallError ? failure.message : String(failure));
|
|
2800
|
+
}
|
|
2801
|
+
if (preview === void 0) return error("Skill preview was unavailable.");
|
|
2802
|
+
if (preview.candidates.length === 0) {
|
|
2803
|
+
deps.installer.cancel(preview.previewId);
|
|
2804
|
+
return error("No installable skill was found in this source.");
|
|
2805
|
+
}
|
|
2806
|
+
const selected = input.pick === void 0 ? preview.candidates.length === 1 ? preview.candidates : void 0 : preview.candidates.filter((candidate) => input.pick?.includes(candidate.key));
|
|
2807
|
+
if (selected === void 0) return { content: `Choose pick keys: ${preview.candidates.map((candidate) => `${candidate.key} (${candidate.suggestedId})`).join(", ")}` };
|
|
2808
|
+
if (selected.length === 0) return error("None of the selected keys is in the source.");
|
|
2809
|
+
if (input.id !== void 0 && selected.length !== 1) return error("id can rename only one selected skill.");
|
|
2810
|
+
const picks = [];
|
|
2811
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2812
|
+
for (const candidate of selected) {
|
|
2813
|
+
const id = input.id ?? candidate.suggestedId;
|
|
2814
|
+
if (!isStandardName$1(id)) return error(`Invalid skill name: ${id}`);
|
|
2815
|
+
if (seen.has(id)) return error(`Two selected skills have the same target name: ${id}`);
|
|
2816
|
+
seen.add(id);
|
|
2817
|
+
picks.push({
|
|
2818
|
+
key: candidate.key,
|
|
2819
|
+
id,
|
|
2820
|
+
onConflict: input.replace === true ? "replace" : "skip"
|
|
2821
|
+
});
|
|
2822
|
+
}
|
|
2823
|
+
const targets = [];
|
|
2824
|
+
for (const pick of picks) {
|
|
2825
|
+
const current = deps.skills.snapshot({ ctx }, input.layer, pick.id);
|
|
2826
|
+
if (!current.ok) return error(current.message);
|
|
2827
|
+
targets.push({
|
|
2828
|
+
id: pick.id,
|
|
2829
|
+
digest: current.digest,
|
|
2830
|
+
exists: current.exists,
|
|
2831
|
+
files: current.files
|
|
2832
|
+
});
|
|
2833
|
+
}
|
|
2834
|
+
const active = picks.filter((pick) => input.replace === true || !targets.find((target) => target.id === pick.id)?.exists);
|
|
2835
|
+
if (!active.length) {
|
|
2836
|
+
deps.installer.cancel(preview.previewId);
|
|
2837
|
+
return { content: "All selected skills already exist." };
|
|
2838
|
+
}
|
|
2839
|
+
const sourceDigest = deps.installer.digest(preview.previewId, picks, input.layer);
|
|
2840
|
+
const id = `install-${createHash("sha256").update(JSON.stringify([
|
|
2841
|
+
sourceDigest,
|
|
2842
|
+
targets,
|
|
2843
|
+
input.layer
|
|
2844
|
+
])).digest("hex")}`;
|
|
2845
|
+
if (ctx.answer?.answers.some((answer) => answer.questionId.startsWith(deps.approval.questionId("install-") ?? "\0")) && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(id))) return error("Source or destination changed since approval; request installation again.");
|
|
2846
|
+
const decision = deps.approval.decide(ctx, {
|
|
2847
|
+
id,
|
|
2848
|
+
subject: `Install ${active.map((pick) => pick.id).join(", ")}`,
|
|
2849
|
+
reason: JSON.stringify({
|
|
2850
|
+
source: preview.sourceLabel,
|
|
2851
|
+
layer: input.layer,
|
|
2852
|
+
candidates: selected,
|
|
2853
|
+
targets
|
|
2854
|
+
}),
|
|
2855
|
+
accepts: [
|
|
2856
|
+
"allowed-once",
|
|
2857
|
+
"allowed-session",
|
|
2858
|
+
"allowed-always",
|
|
2859
|
+
"rejected"
|
|
2860
|
+
],
|
|
2861
|
+
remember: {
|
|
2862
|
+
key: `skill-install:${input.source.kind}:${input.layer}:${deps.skills.agentOf(ctx)}`,
|
|
2863
|
+
label: "Install skills"
|
|
2864
|
+
}
|
|
2865
|
+
});
|
|
2866
|
+
if (decision.kind === "ask") return decision.result;
|
|
2867
|
+
if (!decision.result.kind.startsWith("allowed-")) {
|
|
2868
|
+
deps.installer.cancel(preview.previewId);
|
|
2869
|
+
return error("Skill installation was not approved.");
|
|
2870
|
+
}
|
|
2871
|
+
const result = await deps.installer.install(preview.previewId, { ctx }, input.layer, picks, Date.now());
|
|
2872
|
+
return {
|
|
2873
|
+
content: JSON.stringify(result),
|
|
2874
|
+
...result.failed.length ? { isError: true } : {}
|
|
2875
|
+
};
|
|
2876
|
+
}
|
|
2877
|
+
};
|
|
2878
|
+
}
|
|
2879
|
+
//#endregion
|
|
2880
|
+
//#region src/tools/preload-edit.ts
|
|
2881
|
+
const Input$2 = z.strictObject({ ids: z.array(z.string().min(1)) });
|
|
2882
|
+
/** Saves preload choices through the host's normal definition save and approval. */
|
|
2883
|
+
function preloadSkillEdit(deps) {
|
|
2884
|
+
return {
|
|
2885
|
+
name: "skill_set_preload",
|
|
2886
|
+
description: "Choose unique global or own-agent skill ids to preload. Existing missing ids can be retained.",
|
|
2887
|
+
inputSchema: Input$2,
|
|
2888
|
+
async execute(input, ctx) {
|
|
2889
|
+
const current = deps.definitions.read(ctx);
|
|
2890
|
+
const settings = deps.settings(current.agentId);
|
|
2891
|
+
const layers = deps.skills.layerIds({ ctx });
|
|
2892
|
+
const allowed = /* @__PURE__ */ new Set([
|
|
2893
|
+
...layers.global,
|
|
2894
|
+
...layers.agent,
|
|
2895
|
+
...settings.skills
|
|
2896
|
+
]);
|
|
2897
|
+
if (new Set(input.ids).size !== input.ids.length || input.ids.some((id) => !allowed.has(id))) return {
|
|
2898
|
+
content: "Preloaded skill ids must be unique and available in the global or agent layer.",
|
|
2899
|
+
isError: true
|
|
2900
|
+
};
|
|
2901
|
+
return deps.definitions.update(ctx, { extensionData: { "@eum-agent/skill-management": {
|
|
2902
|
+
...settings,
|
|
2903
|
+
skills: input.ids
|
|
2904
|
+
} } });
|
|
2905
|
+
}
|
|
2906
|
+
};
|
|
2907
|
+
}
|
|
2908
|
+
//#endregion
|
|
2909
|
+
//#region src/tools/uninstall-edit.ts
|
|
2910
|
+
const Input$1 = z.strictObject({
|
|
2911
|
+
id: z.string().min(1),
|
|
2912
|
+
layer: z.enum(["agent", "global"]).default("agent")
|
|
2913
|
+
});
|
|
2914
|
+
/** Removes a skill after ordinary approval bound to its directory digest. */
|
|
2915
|
+
function uninstallSkillEdit(deps) {
|
|
2916
|
+
return {
|
|
2917
|
+
name: "skill_uninstall",
|
|
2918
|
+
description: "Remove a complete skill directory after approval.",
|
|
2919
|
+
inputSchema: Input$1,
|
|
2920
|
+
async execute(input, ctx) {
|
|
2921
|
+
const current = deps.skills.snapshot({ ctx }, input.layer, input.id);
|
|
2922
|
+
if (!current.ok) return {
|
|
2923
|
+
content: current.message,
|
|
2924
|
+
isError: true
|
|
2925
|
+
};
|
|
2926
|
+
if (!current.exists) return { content: "Skill is already absent." };
|
|
2927
|
+
const id = `remove-${current.digest}`;
|
|
2928
|
+
if (ctx.answer && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(id))) return {
|
|
2929
|
+
content: "Skill changed since approval; request removal again.",
|
|
2930
|
+
isError: true
|
|
2931
|
+
};
|
|
2932
|
+
const decision = deps.approval.decide(ctx, {
|
|
2933
|
+
id,
|
|
2934
|
+
subject: `Remove ${input.layer} skill ${input.id}`,
|
|
2935
|
+
reason: JSON.stringify(current.files),
|
|
2936
|
+
accepts: [
|
|
2937
|
+
"allowed-once",
|
|
2938
|
+
"allowed-session",
|
|
2939
|
+
"allowed-always",
|
|
2940
|
+
"rejected"
|
|
2941
|
+
],
|
|
2942
|
+
remember: {
|
|
2943
|
+
key: `skill-remove:${input.layer}:${deps.skills.agentOf(ctx)}`,
|
|
2944
|
+
label: "Remove skills"
|
|
2945
|
+
}
|
|
2946
|
+
});
|
|
2947
|
+
if (decision.kind === "ask") return decision.result;
|
|
2948
|
+
if (!decision.result.kind.startsWith("allowed-")) return {
|
|
2949
|
+
content: "Skill removal was not approved.",
|
|
2950
|
+
isError: true
|
|
2951
|
+
};
|
|
2952
|
+
const result = await deps.skills.uninstall({ ctx }, input);
|
|
2953
|
+
if (result.ok) deps.changed(input.layer, deps.skills.agentOf(ctx));
|
|
2954
|
+
return {
|
|
2955
|
+
content: JSON.stringify(result),
|
|
2956
|
+
...!result.ok ? { isError: true } : {}
|
|
2957
|
+
};
|
|
2958
|
+
}
|
|
2959
|
+
};
|
|
2960
|
+
}
|
|
2961
|
+
//#endregion
|
|
2962
|
+
//#region src/tools/write-edit.ts
|
|
2963
|
+
const Input = z.strictObject({
|
|
2964
|
+
layer: z.enum([
|
|
2965
|
+
"global",
|
|
2966
|
+
"agent",
|
|
2967
|
+
"workspace"
|
|
2968
|
+
]),
|
|
2969
|
+
id: z.string(),
|
|
2970
|
+
description: z.string(),
|
|
2971
|
+
body: z.string(),
|
|
2972
|
+
files: z.array(z.strictObject({
|
|
2973
|
+
name: z.string(),
|
|
2974
|
+
content: z.string()
|
|
2975
|
+
})).optional()
|
|
2976
|
+
});
|
|
2977
|
+
/** Writes a skill through its existing filesystem validation and ordinary approval. */
|
|
2978
|
+
function writeSkillEdit(deps) {
|
|
2979
|
+
const pending = /* @__PURE__ */ new Map();
|
|
2980
|
+
return {
|
|
2981
|
+
name: "skill_write",
|
|
2982
|
+
description: "Save a skill in the global, agent or workspace layer after approval of the file changes.",
|
|
2983
|
+
inputSchema: Input,
|
|
2984
|
+
async execute(input, ctx) {
|
|
2985
|
+
const key = JSON.stringify([
|
|
2986
|
+
ctx.sessionId,
|
|
2987
|
+
ctx.turn,
|
|
2988
|
+
ctx.toolCallId,
|
|
2989
|
+
ctx.address,
|
|
2990
|
+
input
|
|
2991
|
+
]);
|
|
2992
|
+
const held = pending.get(key);
|
|
2993
|
+
if (!held && ctx.answer?.answers.some((answer) => answer.questionId.startsWith(deps.approval.questionId("skill-") ?? "\0"))) return {
|
|
2994
|
+
content: "The authorized file preparation expired; request the write again.",
|
|
2995
|
+
isError: true
|
|
2996
|
+
};
|
|
2997
|
+
const prepared = held ? {
|
|
2998
|
+
ok: true,
|
|
2999
|
+
plan: held
|
|
3000
|
+
} : deps.skills.prepareWrite(ctx, input);
|
|
3001
|
+
if (!prepared.ok) return "ask" in prepared ? prepared.ask : {
|
|
3002
|
+
content: prepared.message,
|
|
3003
|
+
isError: true
|
|
3004
|
+
};
|
|
3005
|
+
const changes = prepared.plan.files.filter((file) => file.before !== file.after);
|
|
3006
|
+
if (!changes.length) return { content: "Skill is unchanged." };
|
|
3007
|
+
const id = `skill-${createHash("sha256").update(JSON.stringify([prepared.plan.expectedDigest, changes])).digest("hex")}`;
|
|
3008
|
+
if (ctx.answer?.answers.some((answer) => answer.questionId.startsWith(deps.approval.questionId("skill-") ?? "\0")) && !ctx.answer.answers.some((answer) => answer.questionId === deps.approval.questionId(id))) return {
|
|
3009
|
+
content: "Skill changed since approval; request the write again.",
|
|
3010
|
+
isError: true
|
|
3011
|
+
};
|
|
3012
|
+
const decision = deps.approval.decide(ctx, {
|
|
3013
|
+
id,
|
|
3014
|
+
subject: `Save skill ${input.id}`,
|
|
3015
|
+
reason: JSON.stringify({
|
|
3016
|
+
layer: input.layer,
|
|
3017
|
+
changes
|
|
3018
|
+
}),
|
|
3019
|
+
warning: input.layer === "global" ? "Every agent may use this skill. Executing installed code requires separate permission." : "Executing installed code requires separate permission.",
|
|
3020
|
+
accepts: [
|
|
3021
|
+
"allowed-once",
|
|
3022
|
+
"allowed-session",
|
|
3023
|
+
"allowed-always",
|
|
3024
|
+
"rejected"
|
|
3025
|
+
],
|
|
3026
|
+
remember: {
|
|
3027
|
+
key: `skill-write:${input.layer}:${deps.skills.agentOf(ctx)}`,
|
|
3028
|
+
label: "Write skills"
|
|
3029
|
+
}
|
|
3030
|
+
});
|
|
3031
|
+
if (decision.kind === "ask") {
|
|
3032
|
+
if (pending.size >= 128) pending.delete(pending.keys().next().value);
|
|
3033
|
+
pending.set(key, prepared.plan);
|
|
3034
|
+
return decision.result;
|
|
3035
|
+
}
|
|
3036
|
+
pending.delete(key);
|
|
3037
|
+
if (!decision.result.kind.startsWith("allowed-")) return {
|
|
3038
|
+
content: "Skill write was not approved.",
|
|
3039
|
+
isError: true
|
|
3040
|
+
};
|
|
3041
|
+
const result = deps.skills.commitWrite(ctx, prepared.plan);
|
|
3042
|
+
return {
|
|
3043
|
+
content: JSON.stringify(result),
|
|
3044
|
+
...!result.ok ? { isError: true } : {}
|
|
3045
|
+
};
|
|
3046
|
+
}
|
|
3047
|
+
};
|
|
3048
|
+
}
|
|
3049
|
+
//#endregion
|
|
3050
|
+
//#region src/index.ts
|
|
3051
|
+
/**
|
|
3052
|
+
* `@eum-agent/skill-management` — skills, as one plugin: reading and writing them, and
|
|
3053
|
+
* installing and uninstalling them from skill sites, GitHub, or a local
|
|
3054
|
+
* directory or zip, over the host's `skills` service.
|
|
3055
|
+
*
|
|
3056
|
+
* Members live under `src/`: `skills/` (`skill_read`, `skill_write`),
|
|
3057
|
+
* `install/` (sources, preview, install), `tools/` (`skill_install`,
|
|
3058
|
+
* `skill_uninstall`), `methods.ts` (what the skills tab calls) and `ui/` (the
|
|
3059
|
+
* browser module: the agent editor's whole skills tab). None of them is a
|
|
3060
|
+
* plugin; this file is the only one, and it is what a person's `config.json`
|
|
3061
|
+
* names, what `plugin list` prints, and what the loader imports.
|
|
3062
|
+
*
|
|
3063
|
+
* `@eum-agent/plugin` is the only workspace package any file here imports, and
|
|
3064
|
+
* only its types: everything reached at runtime arrived through `ctx`.
|
|
3065
|
+
*/
|
|
3066
|
+
/**
|
|
3067
|
+
* This plugin's slice of `config.json`.
|
|
3068
|
+
*
|
|
3069
|
+
* `disabled` turns one tool off while the rest of the package stays on —
|
|
3070
|
+
* `enabled: false` on the declaration turns off every one of them. Strict and
|
|
3071
|
+
* enumerated: a misspelled tool name is a load failure naming the field, not
|
|
3072
|
+
* a line that quietly does nothing.
|
|
3073
|
+
*/
|
|
3074
|
+
const SkillConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).default({ disabled: [] });
|
|
3075
|
+
/** Where this package's browser module is, or nothing when it has not been
|
|
3076
|
+
* built. Computed in this entry, which sits one directory below the package
|
|
3077
|
+
* root in source and in the output alike. */
|
|
3078
|
+
function browserModule() {
|
|
3079
|
+
const path = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
3080
|
+
return existsSync(path) ? path : void 0;
|
|
3081
|
+
}
|
|
3082
|
+
const skillPlugin = {
|
|
3083
|
+
name: "@eum-agent/skill-management",
|
|
3084
|
+
requires: [
|
|
3085
|
+
"agent-execution",
|
|
3086
|
+
"workspace-roots",
|
|
3087
|
+
"agent-configuration-store",
|
|
3088
|
+
NETWORK_SERVICE,
|
|
3089
|
+
"approval",
|
|
3090
|
+
"agent-definition",
|
|
3091
|
+
FENCE_SERVICE
|
|
3092
|
+
],
|
|
3093
|
+
provides: ["skills"],
|
|
3094
|
+
configSchema: SkillConfig,
|
|
3095
|
+
apply(ctx, config) {
|
|
3096
|
+
const disabled = new Set(config.disabled);
|
|
3097
|
+
const register = (tool) => disabled.has(tool.name) ? void 0 : ctx.tools.register(tool);
|
|
3098
|
+
const execution = ctx.services.get("agent-execution");
|
|
3099
|
+
const settings = registerSkillConfiguration(ctx, execution, ctx.services.get("agent-configuration-store"));
|
|
3100
|
+
const skills = createSkills({
|
|
3101
|
+
workRoot: execution.workRoot,
|
|
3102
|
+
fence: ctx.services.get(FENCE_SERVICE),
|
|
3103
|
+
agentOf: (call) => execution.agentOf(call.sessionId, call.address),
|
|
3104
|
+
disabledSkills: (agentId) => settings(agentId).disabledSkills,
|
|
3105
|
+
hasAgent: (agentId) => execution.agent(agentId) !== void 0,
|
|
3106
|
+
sealed: execution.sealed
|
|
3107
|
+
});
|
|
3108
|
+
ctx.services.provide(SKILLS_SERVICE, skills);
|
|
3109
|
+
registerSkillViews(ctx, execution, settings);
|
|
3110
|
+
ctx.context.contribute(skillCatalogueContributor(execution.workRoot, (view) => execution.agentOf(view.state.sessionId, view.address), (agentId) => settings(agentId).disabledSkills));
|
|
3111
|
+
register(readSkillTool(skills));
|
|
3112
|
+
const approval = ctx.services.get("approval");
|
|
3113
|
+
const definitions = ctx.services.get("agent-definition");
|
|
3114
|
+
register(writeSkillEdit({
|
|
3115
|
+
skills,
|
|
3116
|
+
approval
|
|
3117
|
+
}));
|
|
3118
|
+
register(preloadSkillEdit({
|
|
3119
|
+
skills,
|
|
3120
|
+
definitions,
|
|
3121
|
+
settings
|
|
3122
|
+
}));
|
|
3123
|
+
const changed = registerSkillFrame(ctx);
|
|
3124
|
+
const installer = createInstaller({
|
|
3125
|
+
http: createHttp(ctx.services.get(NETWORK_SERVICE).fetch),
|
|
3126
|
+
skills,
|
|
3127
|
+
changed: (target, layer) => changed.emit(changeOf(skills, target, layer))
|
|
3128
|
+
});
|
|
3129
|
+
ctx.onDispose(() => installer.dispose());
|
|
3130
|
+
registerSkillMethods(ctx, {
|
|
3131
|
+
skills,
|
|
3132
|
+
installer,
|
|
3133
|
+
changed
|
|
3134
|
+
});
|
|
3135
|
+
register(installSkillEdit({
|
|
3136
|
+
skills,
|
|
3137
|
+
installer,
|
|
3138
|
+
approval,
|
|
3139
|
+
fence: ctx.services.get(FENCE_SERVICE)
|
|
3140
|
+
}));
|
|
3141
|
+
register(uninstallSkillEdit({
|
|
3142
|
+
skills,
|
|
3143
|
+
approval,
|
|
3144
|
+
changed: (layer, agentId) => changed.emit(layer === "global" ? { layer } : {
|
|
3145
|
+
layer,
|
|
3146
|
+
agentId
|
|
3147
|
+
})
|
|
3148
|
+
}));
|
|
3149
|
+
const uiModule = browserModule();
|
|
3150
|
+
if (uiModule !== void 0) ctx.client.registerUi({ module: uiModule });
|
|
3151
|
+
ctx.tools.guide(GUIDANCE);
|
|
3152
|
+
}
|
|
3153
|
+
};
|
|
3154
|
+
//#endregion
|
|
3155
|
+
export { SKILLS_SERVICE, SkillConfig, TOOL_NAMES, skillPlugin as default, skillPlugin, registerSkillTools };
|