@agentforge/skills 0.15.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/LICENSE +22 -0
- package/README.md +29 -0
- package/dist/index.cjs +850 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +682 -0
- package/dist/index.d.ts +682 -0
- package/dist/index.js +828 -0
- package/dist/index.js.map +1 -0
- package/package.json +75 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,850 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var matter = require('gray-matter');
|
|
4
|
+
var fs = require('fs');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
var os = require('os');
|
|
7
|
+
var core = require('@agentforge/core');
|
|
8
|
+
var zod = require('zod');
|
|
9
|
+
|
|
10
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
11
|
+
|
|
12
|
+
var matter__default = /*#__PURE__*/_interopDefault(matter);
|
|
13
|
+
|
|
14
|
+
// src/types.ts
|
|
15
|
+
var TrustPolicyReason = /* @__PURE__ */ ((TrustPolicyReason2) => {
|
|
16
|
+
TrustPolicyReason2["NOT_SCRIPT"] = "not-script";
|
|
17
|
+
TrustPolicyReason2["WORKSPACE_TRUST"] = "workspace-trust";
|
|
18
|
+
TrustPolicyReason2["TRUSTED_ROOT"] = "trusted-root";
|
|
19
|
+
TrustPolicyReason2["UNTRUSTED_SCRIPT_DENIED"] = "untrusted-script-denied";
|
|
20
|
+
TrustPolicyReason2["UNTRUSTED_SCRIPT_ALLOWED"] = "untrusted-script-allowed-override";
|
|
21
|
+
TrustPolicyReason2["UNKNOWN_TRUST_LEVEL"] = "unknown-trust-level";
|
|
22
|
+
return TrustPolicyReason2;
|
|
23
|
+
})(TrustPolicyReason || {});
|
|
24
|
+
var SkillRegistryEvent = /* @__PURE__ */ ((SkillRegistryEvent2) => {
|
|
25
|
+
SkillRegistryEvent2["SKILL_DISCOVERED"] = "skill:discovered";
|
|
26
|
+
SkillRegistryEvent2["SKILL_WARNING"] = "skill:warning";
|
|
27
|
+
SkillRegistryEvent2["SKILL_ACTIVATED"] = "skill:activated";
|
|
28
|
+
SkillRegistryEvent2["SKILL_RESOURCE_LOADED"] = "skill:resource-loaded";
|
|
29
|
+
SkillRegistryEvent2["TRUST_POLICY_DENIED"] = "trust:policy-denied";
|
|
30
|
+
SkillRegistryEvent2["TRUST_POLICY_ALLOWED"] = "trust:policy-allowed";
|
|
31
|
+
return SkillRegistryEvent2;
|
|
32
|
+
})(SkillRegistryEvent || {});
|
|
33
|
+
var SKILL_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
34
|
+
var SKILL_NAME_MAX_LENGTH = 64;
|
|
35
|
+
var SKILL_DESCRIPTION_MAX_LENGTH = 1024;
|
|
36
|
+
function validateSkillName(name) {
|
|
37
|
+
const errors = [];
|
|
38
|
+
if (name === void 0 || name === null) {
|
|
39
|
+
errors.push({ field: "name", message: "name is required" });
|
|
40
|
+
return errors;
|
|
41
|
+
}
|
|
42
|
+
if (typeof name !== "string") {
|
|
43
|
+
errors.push({ field: "name", message: "name must be a string" });
|
|
44
|
+
return errors;
|
|
45
|
+
}
|
|
46
|
+
if (name.length === 0) {
|
|
47
|
+
errors.push({ field: "name", message: "name must not be empty" });
|
|
48
|
+
return errors;
|
|
49
|
+
}
|
|
50
|
+
if (name.length > SKILL_NAME_MAX_LENGTH) {
|
|
51
|
+
errors.push({
|
|
52
|
+
field: "name",
|
|
53
|
+
message: `name must be at most ${SKILL_NAME_MAX_LENGTH} characters (got ${name.length})`
|
|
54
|
+
});
|
|
55
|
+
return errors;
|
|
56
|
+
}
|
|
57
|
+
if (!SKILL_NAME_PATTERN.test(name)) {
|
|
58
|
+
errors.push({
|
|
59
|
+
field: "name",
|
|
60
|
+
message: "name must be lowercase alphanumeric with hyphens, no leading/trailing/consecutive hyphens"
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
if (name.includes("--")) {
|
|
64
|
+
errors.push({
|
|
65
|
+
field: "name",
|
|
66
|
+
message: "name must not contain consecutive hyphens"
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return errors;
|
|
70
|
+
}
|
|
71
|
+
function validateSkillDescription(description) {
|
|
72
|
+
const errors = [];
|
|
73
|
+
if (description === void 0 || description === null) {
|
|
74
|
+
errors.push({ field: "description", message: "description is required" });
|
|
75
|
+
return errors;
|
|
76
|
+
}
|
|
77
|
+
if (typeof description !== "string") {
|
|
78
|
+
errors.push({ field: "description", message: "description must be a string" });
|
|
79
|
+
return errors;
|
|
80
|
+
}
|
|
81
|
+
if (description.trim().length === 0) {
|
|
82
|
+
errors.push({ field: "description", message: "description must not be empty" });
|
|
83
|
+
return errors;
|
|
84
|
+
}
|
|
85
|
+
if (description.length > SKILL_DESCRIPTION_MAX_LENGTH) {
|
|
86
|
+
errors.push({
|
|
87
|
+
field: "description",
|
|
88
|
+
message: `description must be at most ${SKILL_DESCRIPTION_MAX_LENGTH} characters (got ${description.length})`
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return errors;
|
|
92
|
+
}
|
|
93
|
+
function validateSkillNameMatchesDir(name, dirName) {
|
|
94
|
+
if (name !== dirName) {
|
|
95
|
+
return [{
|
|
96
|
+
field: "name",
|
|
97
|
+
message: `name "${name}" must match parent directory name "${dirName}"`
|
|
98
|
+
}];
|
|
99
|
+
}
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
function parseSkillContent(content, dirName) {
|
|
103
|
+
let parsed;
|
|
104
|
+
try {
|
|
105
|
+
parsed = matter__default.default(content);
|
|
106
|
+
} catch (err) {
|
|
107
|
+
return {
|
|
108
|
+
success: false,
|
|
109
|
+
error: `Failed to parse frontmatter: ${err instanceof Error ? err.message : String(err)}`
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const data = parsed.data;
|
|
113
|
+
const errors = [
|
|
114
|
+
...validateSkillName(data.name),
|
|
115
|
+
...validateSkillDescription(data.description)
|
|
116
|
+
];
|
|
117
|
+
if (typeof data.name === "string" && data.name.length > 0 && SKILL_NAME_PATTERN.test(data.name)) {
|
|
118
|
+
errors.push(...validateSkillNameMatchesDir(data.name, dirName));
|
|
119
|
+
}
|
|
120
|
+
if (errors.length > 0) {
|
|
121
|
+
return {
|
|
122
|
+
success: false,
|
|
123
|
+
error: errors.map((e) => `${e.field}: ${e.message}`).join("; ")
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const metadata = {
|
|
127
|
+
name: data.name,
|
|
128
|
+
description: data.description
|
|
129
|
+
};
|
|
130
|
+
if (data.license !== void 0) {
|
|
131
|
+
metadata.license = String(data.license);
|
|
132
|
+
}
|
|
133
|
+
if (Array.isArray(data.compatibility)) {
|
|
134
|
+
metadata.compatibility = data.compatibility.map(String);
|
|
135
|
+
}
|
|
136
|
+
if (data.metadata !== void 0 && typeof data.metadata === "object" && data.metadata !== null) {
|
|
137
|
+
metadata.metadata = data.metadata;
|
|
138
|
+
}
|
|
139
|
+
if (Array.isArray(data["allowed-tools"])) {
|
|
140
|
+
metadata.allowedTools = data["allowed-tools"].map(String);
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
success: true,
|
|
144
|
+
metadata,
|
|
145
|
+
body: parsed.content
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
var logger = core.createLogger("agentforge:skills:scanner", { level: core.LogLevel.INFO });
|
|
149
|
+
function expandHome(p) {
|
|
150
|
+
if (p.startsWith("~/") || p === "~") {
|
|
151
|
+
return path.resolve(os.homedir(), p.slice(2));
|
|
152
|
+
}
|
|
153
|
+
return p;
|
|
154
|
+
}
|
|
155
|
+
function scanSkillRoot(rootPath) {
|
|
156
|
+
const resolvedRoot = path.resolve(expandHome(rootPath));
|
|
157
|
+
const candidates = [];
|
|
158
|
+
if (!fs.existsSync(resolvedRoot)) {
|
|
159
|
+
logger.debug("Skill root does not exist, skipping", { rootPath: resolvedRoot });
|
|
160
|
+
return candidates;
|
|
161
|
+
}
|
|
162
|
+
let entries;
|
|
163
|
+
try {
|
|
164
|
+
entries = fs.readdirSync(resolvedRoot);
|
|
165
|
+
} catch (err) {
|
|
166
|
+
logger.warn("Failed to read skill root directory", {
|
|
167
|
+
rootPath: resolvedRoot,
|
|
168
|
+
error: err instanceof Error ? err.message : String(err)
|
|
169
|
+
});
|
|
170
|
+
return candidates;
|
|
171
|
+
}
|
|
172
|
+
for (const entry of entries) {
|
|
173
|
+
const entryPath = path.resolve(resolvedRoot, entry);
|
|
174
|
+
let stat;
|
|
175
|
+
try {
|
|
176
|
+
stat = fs.statSync(entryPath);
|
|
177
|
+
} catch {
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (!stat.isDirectory()) {
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const skillMdPath = path.resolve(entryPath, "SKILL.md");
|
|
184
|
+
if (!fs.existsSync(skillMdPath)) {
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
const content = fs.readFileSync(skillMdPath, "utf-8");
|
|
189
|
+
candidates.push({
|
|
190
|
+
skillPath: entryPath,
|
|
191
|
+
dirName: path.basename(entryPath),
|
|
192
|
+
content,
|
|
193
|
+
rootPath: resolvedRoot
|
|
194
|
+
});
|
|
195
|
+
} catch (err) {
|
|
196
|
+
logger.warn("Failed to read SKILL.md", {
|
|
197
|
+
path: skillMdPath,
|
|
198
|
+
error: err instanceof Error ? err.message : String(err)
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
logger.debug("Scanned skill root", {
|
|
203
|
+
rootPath: resolvedRoot,
|
|
204
|
+
candidatesFound: candidates.length
|
|
205
|
+
});
|
|
206
|
+
return candidates;
|
|
207
|
+
}
|
|
208
|
+
function scanAllSkillRoots(skillRoots) {
|
|
209
|
+
const allCandidates = [];
|
|
210
|
+
for (const root of skillRoots) {
|
|
211
|
+
const candidates = scanSkillRoot(root);
|
|
212
|
+
allCandidates.push(...candidates);
|
|
213
|
+
}
|
|
214
|
+
logger.info("Skill discovery complete", {
|
|
215
|
+
rootsScanned: skillRoots.length,
|
|
216
|
+
totalCandidates: allCandidates.length
|
|
217
|
+
});
|
|
218
|
+
return allCandidates;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/trust.ts
|
|
222
|
+
var SCRIPT_PATH_PREFIX = "scripts/";
|
|
223
|
+
var SCRIPT_PATH_EXACT = "scripts";
|
|
224
|
+
function normalizeRootConfig(root) {
|
|
225
|
+
if (typeof root === "string") {
|
|
226
|
+
return { path: root, trust: "untrusted" };
|
|
227
|
+
}
|
|
228
|
+
return root;
|
|
229
|
+
}
|
|
230
|
+
function isScriptResource(resourcePath) {
|
|
231
|
+
let normalized = resourcePath.trim().replace(/\\/g, "/");
|
|
232
|
+
normalized = normalized.replace(/\/+/g, "/");
|
|
233
|
+
while (normalized.startsWith("./")) {
|
|
234
|
+
normalized = normalized.slice(2);
|
|
235
|
+
}
|
|
236
|
+
const lower = normalized.toLowerCase();
|
|
237
|
+
return lower === SCRIPT_PATH_EXACT || lower.startsWith(SCRIPT_PATH_PREFIX);
|
|
238
|
+
}
|
|
239
|
+
function evaluateTrustPolicy(resourcePath, trustLevel, allowUntrustedScripts = false) {
|
|
240
|
+
if (!isScriptResource(resourcePath)) {
|
|
241
|
+
return {
|
|
242
|
+
allowed: true,
|
|
243
|
+
reason: "not-script" /* NOT_SCRIPT */,
|
|
244
|
+
message: "Resource is not a script \u2014 no trust check required"
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
switch (trustLevel) {
|
|
248
|
+
case "workspace":
|
|
249
|
+
return {
|
|
250
|
+
allowed: true,
|
|
251
|
+
reason: "workspace-trust" /* WORKSPACE_TRUST */,
|
|
252
|
+
message: "Script allowed \u2014 skill root has workspace trust"
|
|
253
|
+
};
|
|
254
|
+
case "trusted":
|
|
255
|
+
return {
|
|
256
|
+
allowed: true,
|
|
257
|
+
reason: "trusted-root" /* TRUSTED_ROOT */,
|
|
258
|
+
message: "Script allowed \u2014 skill root is explicitly trusted"
|
|
259
|
+
};
|
|
260
|
+
case "untrusted":
|
|
261
|
+
if (allowUntrustedScripts) {
|
|
262
|
+
return {
|
|
263
|
+
allowed: true,
|
|
264
|
+
reason: "untrusted-script-allowed-override" /* UNTRUSTED_SCRIPT_ALLOWED */,
|
|
265
|
+
message: "Script from untrusted root allowed via allowUntrustedScripts override"
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
allowed: false,
|
|
270
|
+
reason: "untrusted-script-denied" /* UNTRUSTED_SCRIPT_DENIED */,
|
|
271
|
+
message: `Script access denied \u2014 skill root is untrusted. Scripts from untrusted roots are blocked by default for security. To allow, set 'allowUntrustedScripts: true' in SkillRegistryConfig or promote the skill root to 'trusted' or 'workspace' trust level.`
|
|
272
|
+
};
|
|
273
|
+
default:
|
|
274
|
+
return {
|
|
275
|
+
allowed: false,
|
|
276
|
+
reason: "unknown-trust-level" /* UNKNOWN_TRUST_LEVEL */,
|
|
277
|
+
message: `Script access denied \u2014 trust level "${trustLevel}" is unknown and is treated as untrusted for security.`
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/activation.ts
|
|
283
|
+
var logger2 = core.createLogger("agentforge:skills:activation", { level: core.LogLevel.INFO });
|
|
284
|
+
var activateSkillSchema = zod.z.object({
|
|
285
|
+
name: zod.z.string().describe('The name of the skill to activate (e.g., "code-review")')
|
|
286
|
+
});
|
|
287
|
+
var readSkillResourceSchema = zod.z.object({
|
|
288
|
+
name: zod.z.string().describe("The name of the skill that owns the resource"),
|
|
289
|
+
path: zod.z.string().describe('Relative path to the resource file within the skill directory (e.g., "references/GUIDE.md", "scripts/setup.sh")')
|
|
290
|
+
});
|
|
291
|
+
function resolveResourcePath(skillPath, resourcePath) {
|
|
292
|
+
if (path.isAbsolute(resourcePath)) {
|
|
293
|
+
return { success: false, error: "Absolute resource paths are not allowed" };
|
|
294
|
+
}
|
|
295
|
+
const segments = resourcePath.split(/[/\\]/);
|
|
296
|
+
if (segments.some((seg) => seg === "..")) {
|
|
297
|
+
return { success: false, error: "Path traversal is not allowed \u2014 resource paths must stay within the skill directory" };
|
|
298
|
+
}
|
|
299
|
+
const resolvedPath = path.resolve(skillPath, resourcePath);
|
|
300
|
+
const resolvedSkillPath = path.resolve(skillPath);
|
|
301
|
+
const rel = path.relative(resolvedSkillPath, resolvedPath);
|
|
302
|
+
if (rel.startsWith("..") || path.resolve(resolvedSkillPath, rel) !== resolvedPath) {
|
|
303
|
+
return { success: false, error: "Path traversal is not allowed \u2014 resource paths must stay within the skill directory" };
|
|
304
|
+
}
|
|
305
|
+
try {
|
|
306
|
+
const realSkillRoot = fs.realpathSync(resolvedSkillPath);
|
|
307
|
+
const realTarget = fs.realpathSync(resolvedPath);
|
|
308
|
+
const realRel = path.relative(realSkillRoot, realTarget);
|
|
309
|
+
if (realRel.startsWith("..") || path.isAbsolute(realRel)) {
|
|
310
|
+
return { success: false, error: "Symlink target escapes the skill directory \u2014 access denied" };
|
|
311
|
+
}
|
|
312
|
+
} catch {
|
|
313
|
+
}
|
|
314
|
+
return { success: true, resolvedPath };
|
|
315
|
+
}
|
|
316
|
+
function createActivateSkillTool(registry) {
|
|
317
|
+
return new core.ToolBuilder().name("activate-skill").description(
|
|
318
|
+
"Activate an Agent Skill by name, loading its full instructions. Returns the complete SKILL.md body content for the named skill. Use this when you see a relevant skill in <available_skills> and want to follow its instructions."
|
|
319
|
+
).category(core.ToolCategory.SKILLS).tags(["skill", "activation", "agent-skills"]).schema(activateSkillSchema).implement(async ({ name }) => {
|
|
320
|
+
const skill = registry.get(name);
|
|
321
|
+
if (!skill) {
|
|
322
|
+
const availableNames = registry.getNames();
|
|
323
|
+
const suggestion = availableNames.length > 0 ? ` Available skills: ${availableNames.join(", ")}` : " No skills are currently registered.";
|
|
324
|
+
const errorMsg = `Skill "${name}" not found.${suggestion}`;
|
|
325
|
+
logger2.warn("Skill activation failed \u2014 not found", { name, availableCount: availableNames.length });
|
|
326
|
+
return errorMsg;
|
|
327
|
+
}
|
|
328
|
+
const skillMdPath = path.resolve(skill.skillPath, "SKILL.md");
|
|
329
|
+
try {
|
|
330
|
+
const content = fs.readFileSync(skillMdPath, "utf-8");
|
|
331
|
+
const body = extractBody(content);
|
|
332
|
+
logger2.info("Skill activated", {
|
|
333
|
+
name: skill.metadata.name,
|
|
334
|
+
skillPath: skill.skillPath,
|
|
335
|
+
bodyLength: body.length
|
|
336
|
+
});
|
|
337
|
+
registry.emitEvent("skill:activated" /* SKILL_ACTIVATED */, {
|
|
338
|
+
name: skill.metadata.name,
|
|
339
|
+
skillPath: skill.skillPath,
|
|
340
|
+
bodyLength: body.length
|
|
341
|
+
});
|
|
342
|
+
return body;
|
|
343
|
+
} catch (error) {
|
|
344
|
+
const errorMsg = `Failed to read skill "${name}" instructions: ${error instanceof Error ? error.message : String(error)}`;
|
|
345
|
+
logger2.error("Skill activation failed \u2014 read error", {
|
|
346
|
+
name,
|
|
347
|
+
skillPath: skill.skillPath,
|
|
348
|
+
error: error instanceof Error ? error.message : String(error)
|
|
349
|
+
});
|
|
350
|
+
return errorMsg;
|
|
351
|
+
}
|
|
352
|
+
}).build();
|
|
353
|
+
}
|
|
354
|
+
function createReadSkillResourceTool(registry) {
|
|
355
|
+
return new core.ToolBuilder().name("read-skill-resource").description(
|
|
356
|
+
"Read a resource file from an activated Agent Skill. Returns the content of a file within the skill directory (e.g., references/, scripts/, assets/). The path must be relative to the skill root and cannot traverse outside it."
|
|
357
|
+
).category(core.ToolCategory.SKILLS).tags(["skill", "resource", "agent-skills"]).schema(readSkillResourceSchema).implement(async ({ name, path: resourcePath }) => {
|
|
358
|
+
const skill = registry.get(name);
|
|
359
|
+
if (!skill) {
|
|
360
|
+
const availableNames = registry.getNames();
|
|
361
|
+
const suggestion = availableNames.length > 0 ? ` Available skills: ${availableNames.join(", ")}` : " No skills are currently registered.";
|
|
362
|
+
const errorMsg = `Skill "${name}" not found.${suggestion}`;
|
|
363
|
+
logger2.warn("Skill resource load failed \u2014 skill not found", { name, resourcePath });
|
|
364
|
+
return errorMsg;
|
|
365
|
+
}
|
|
366
|
+
const pathResult = resolveResourcePath(skill.skillPath, resourcePath);
|
|
367
|
+
if (!pathResult.success) {
|
|
368
|
+
logger2.warn("Skill resource load blocked \u2014 path traversal", {
|
|
369
|
+
name,
|
|
370
|
+
resourcePath,
|
|
371
|
+
error: pathResult.error
|
|
372
|
+
});
|
|
373
|
+
return pathResult.error;
|
|
374
|
+
}
|
|
375
|
+
const policyDecision = evaluateTrustPolicy(
|
|
376
|
+
resourcePath,
|
|
377
|
+
skill.trustLevel,
|
|
378
|
+
registry.getAllowUntrustedScripts()
|
|
379
|
+
);
|
|
380
|
+
if (!policyDecision.allowed) {
|
|
381
|
+
logger2.warn("Skill resource load blocked \u2014 trust policy", {
|
|
382
|
+
name,
|
|
383
|
+
resourcePath,
|
|
384
|
+
trustLevel: skill.trustLevel,
|
|
385
|
+
reason: policyDecision.reason,
|
|
386
|
+
message: policyDecision.message
|
|
387
|
+
});
|
|
388
|
+
registry.emitEvent("trust:policy-denied" /* TRUST_POLICY_DENIED */, {
|
|
389
|
+
name: skill.metadata.name,
|
|
390
|
+
resourcePath,
|
|
391
|
+
trustLevel: skill.trustLevel,
|
|
392
|
+
reason: policyDecision.reason,
|
|
393
|
+
message: policyDecision.message
|
|
394
|
+
});
|
|
395
|
+
return policyDecision.message;
|
|
396
|
+
}
|
|
397
|
+
if (policyDecision.reason !== "not-script" /* NOT_SCRIPT */) {
|
|
398
|
+
logger2.info("Skill resource trust policy \u2014 allowed", {
|
|
399
|
+
name,
|
|
400
|
+
resourcePath,
|
|
401
|
+
trustLevel: skill.trustLevel,
|
|
402
|
+
reason: policyDecision.reason
|
|
403
|
+
});
|
|
404
|
+
registry.emitEvent("trust:policy-allowed" /* TRUST_POLICY_ALLOWED */, {
|
|
405
|
+
name: skill.metadata.name,
|
|
406
|
+
resourcePath,
|
|
407
|
+
trustLevel: skill.trustLevel,
|
|
408
|
+
reason: policyDecision.reason
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
try {
|
|
412
|
+
const content = fs.readFileSync(pathResult.resolvedPath, "utf-8");
|
|
413
|
+
logger2.info("Skill resource loaded", {
|
|
414
|
+
name: skill.metadata.name,
|
|
415
|
+
resourcePath,
|
|
416
|
+
resolvedPath: pathResult.resolvedPath,
|
|
417
|
+
contentLength: content.length
|
|
418
|
+
});
|
|
419
|
+
registry.emitEvent("skill:resource-loaded" /* SKILL_RESOURCE_LOADED */, {
|
|
420
|
+
name: skill.metadata.name,
|
|
421
|
+
resourcePath,
|
|
422
|
+
resolvedPath: pathResult.resolvedPath,
|
|
423
|
+
contentLength: content.length
|
|
424
|
+
});
|
|
425
|
+
return content;
|
|
426
|
+
} catch (error) {
|
|
427
|
+
const errorMsg = `Failed to read resource "${resourcePath}" from skill "${name}": ${error instanceof Error ? error.message : String(error)}`;
|
|
428
|
+
logger2.warn("Skill resource load failed \u2014 file not found or unreadable", {
|
|
429
|
+
name,
|
|
430
|
+
resourcePath,
|
|
431
|
+
error: error instanceof Error ? error.message : String(error)
|
|
432
|
+
});
|
|
433
|
+
return errorMsg;
|
|
434
|
+
}
|
|
435
|
+
}).build();
|
|
436
|
+
}
|
|
437
|
+
function createSkillActivationTools(registry) {
|
|
438
|
+
return [
|
|
439
|
+
createActivateSkillTool(registry),
|
|
440
|
+
createReadSkillResourceTool(registry)
|
|
441
|
+
];
|
|
442
|
+
}
|
|
443
|
+
function extractBody(content) {
|
|
444
|
+
return matter__default.default(content).content.trim();
|
|
445
|
+
}
|
|
446
|
+
var logger3 = core.createLogger("agentforge:skills:registry", { level: core.LogLevel.INFO });
|
|
447
|
+
var SkillRegistry = class {
|
|
448
|
+
skills = /* @__PURE__ */ new Map();
|
|
449
|
+
eventHandlers = /* @__PURE__ */ new Map();
|
|
450
|
+
config;
|
|
451
|
+
scanErrors = [];
|
|
452
|
+
/** Maps resolved root paths → trust levels for skill trust assignment */
|
|
453
|
+
rootTrustMap = /* @__PURE__ */ new Map();
|
|
454
|
+
/**
|
|
455
|
+
* Create a SkillRegistry and immediately scan configured roots for skills.
|
|
456
|
+
*
|
|
457
|
+
* @param config - Registry configuration with skill root paths
|
|
458
|
+
*
|
|
459
|
+
* @example
|
|
460
|
+
* ```ts
|
|
461
|
+
* const registry = new SkillRegistry({
|
|
462
|
+
* skillRoots: ['.agentskills', '~/.agentskills', './project-skills'],
|
|
463
|
+
* });
|
|
464
|
+
* console.log(`Discovered ${registry.size()} skills`);
|
|
465
|
+
* ```
|
|
466
|
+
*/
|
|
467
|
+
constructor(config) {
|
|
468
|
+
this.config = config;
|
|
469
|
+
this.discover();
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Scan all configured roots and populate the registry.
|
|
473
|
+
*
|
|
474
|
+
* Called automatically during construction. Can be called again
|
|
475
|
+
* to re-scan (clears existing skills first).
|
|
476
|
+
*/
|
|
477
|
+
discover() {
|
|
478
|
+
this.skills.clear();
|
|
479
|
+
this.scanErrors = [];
|
|
480
|
+
this.rootTrustMap.clear();
|
|
481
|
+
const normalizedRoots = this.config.skillRoots.map(normalizeRootConfig);
|
|
482
|
+
const plainPaths = normalizedRoots.map((r) => r.path);
|
|
483
|
+
for (const root of normalizedRoots) {
|
|
484
|
+
const resolvedPath = path.resolve(expandHome(root.path));
|
|
485
|
+
this.rootTrustMap.set(resolvedPath, root.trust);
|
|
486
|
+
}
|
|
487
|
+
const candidates = scanAllSkillRoots(plainPaths);
|
|
488
|
+
let successCount = 0;
|
|
489
|
+
let warningCount = 0;
|
|
490
|
+
for (const candidate of candidates) {
|
|
491
|
+
const result = parseSkillContent(candidate.content, candidate.dirName);
|
|
492
|
+
if (!result.success) {
|
|
493
|
+
warningCount++;
|
|
494
|
+
this.scanErrors.push({
|
|
495
|
+
path: candidate.skillPath,
|
|
496
|
+
error: result.error || "Unknown parse error"
|
|
497
|
+
});
|
|
498
|
+
this.emit("skill:warning" /* SKILL_WARNING */, {
|
|
499
|
+
skillPath: candidate.skillPath,
|
|
500
|
+
rootPath: candidate.rootPath,
|
|
501
|
+
error: result.error
|
|
502
|
+
});
|
|
503
|
+
logger3.warn("Skipping invalid skill", {
|
|
504
|
+
skillPath: candidate.skillPath,
|
|
505
|
+
error: result.error
|
|
506
|
+
});
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
const skill = {
|
|
510
|
+
metadata: result.metadata,
|
|
511
|
+
skillPath: candidate.skillPath,
|
|
512
|
+
rootPath: candidate.rootPath,
|
|
513
|
+
trustLevel: this.rootTrustMap.get(candidate.rootPath) ?? "untrusted"
|
|
514
|
+
};
|
|
515
|
+
if (this.skills.has(skill.metadata.name)) {
|
|
516
|
+
const existing = this.skills.get(skill.metadata.name);
|
|
517
|
+
warningCount++;
|
|
518
|
+
const warningMsg = `Duplicate skill name "${skill.metadata.name}" from "${candidate.rootPath}" \u2014 keeping version from "${existing.rootPath}" (first root takes precedence)`;
|
|
519
|
+
this.scanErrors.push({
|
|
520
|
+
path: candidate.skillPath,
|
|
521
|
+
error: warningMsg
|
|
522
|
+
});
|
|
523
|
+
this.emit("skill:warning" /* SKILL_WARNING */, {
|
|
524
|
+
skillPath: candidate.skillPath,
|
|
525
|
+
rootPath: candidate.rootPath,
|
|
526
|
+
duplicateOf: existing.skillPath,
|
|
527
|
+
error: warningMsg
|
|
528
|
+
});
|
|
529
|
+
logger3.warn("Duplicate skill name, keeping first", {
|
|
530
|
+
name: skill.metadata.name,
|
|
531
|
+
kept: existing.skillPath,
|
|
532
|
+
skipped: candidate.skillPath
|
|
533
|
+
});
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
this.skills.set(skill.metadata.name, skill);
|
|
537
|
+
successCount++;
|
|
538
|
+
this.emit("skill:discovered" /* SKILL_DISCOVERED */, skill);
|
|
539
|
+
logger3.debug("Skill discovered", {
|
|
540
|
+
name: skill.metadata.name,
|
|
541
|
+
description: skill.metadata.description.slice(0, 80),
|
|
542
|
+
skillPath: skill.skillPath
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
logger3.info("Skill registry populated", {
|
|
546
|
+
rootsScanned: this.config.skillRoots.length,
|
|
547
|
+
skillsDiscovered: successCount,
|
|
548
|
+
warnings: warningCount
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
// ─── Query API (parallel to ToolRegistry) ──────────────────────────────
|
|
552
|
+
/**
|
|
553
|
+
* Get a skill by name.
|
|
554
|
+
*
|
|
555
|
+
* @param name - The skill name
|
|
556
|
+
* @returns The skill, or undefined if not found
|
|
557
|
+
*
|
|
558
|
+
* @example
|
|
559
|
+
* ```ts
|
|
560
|
+
* const skill = registry.get('code-review');
|
|
561
|
+
* if (skill) {
|
|
562
|
+
* console.log(skill.metadata.description);
|
|
563
|
+
* }
|
|
564
|
+
* ```
|
|
565
|
+
*/
|
|
566
|
+
get(name) {
|
|
567
|
+
return this.skills.get(name);
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* Get all discovered skills.
|
|
571
|
+
*
|
|
572
|
+
* @returns Array of all skills
|
|
573
|
+
*
|
|
574
|
+
* @example
|
|
575
|
+
* ```ts
|
|
576
|
+
* const allSkills = registry.getAll();
|
|
577
|
+
* console.log(`Total skills: ${allSkills.length}`);
|
|
578
|
+
* ```
|
|
579
|
+
*/
|
|
580
|
+
getAll() {
|
|
581
|
+
return Array.from(this.skills.values());
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Check if a skill exists in the registry.
|
|
585
|
+
*
|
|
586
|
+
* @param name - The skill name
|
|
587
|
+
* @returns True if the skill exists
|
|
588
|
+
*
|
|
589
|
+
* @example
|
|
590
|
+
* ```ts
|
|
591
|
+
* if (registry.has('code-review')) {
|
|
592
|
+
* console.log('Skill available!');
|
|
593
|
+
* }
|
|
594
|
+
* ```
|
|
595
|
+
*/
|
|
596
|
+
has(name) {
|
|
597
|
+
return this.skills.has(name);
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* Get the number of discovered skills.
|
|
601
|
+
*
|
|
602
|
+
* @returns Number of skills in the registry
|
|
603
|
+
*
|
|
604
|
+
* @example
|
|
605
|
+
* ```ts
|
|
606
|
+
* console.log(`Registry has ${registry.size()} skills`);
|
|
607
|
+
* ```
|
|
608
|
+
*/
|
|
609
|
+
size() {
|
|
610
|
+
return this.skills.size;
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Get all skill names.
|
|
614
|
+
*
|
|
615
|
+
* @returns Array of skill names
|
|
616
|
+
*/
|
|
617
|
+
getNames() {
|
|
618
|
+
return Array.from(this.skills.keys());
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Get errors/warnings from the last scan.
|
|
622
|
+
*
|
|
623
|
+
* Useful for diagnostics and observability.
|
|
624
|
+
*
|
|
625
|
+
* @returns Array of scan errors with paths
|
|
626
|
+
*/
|
|
627
|
+
getScanErrors() {
|
|
628
|
+
return this.scanErrors;
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Check whether untrusted script access is allowed via config override.
|
|
632
|
+
*
|
|
633
|
+
* Used by activation tools to pass the override flag to trust policy checks.
|
|
634
|
+
*
|
|
635
|
+
* @returns True if `allowUntrustedScripts` is set in config
|
|
636
|
+
*/
|
|
637
|
+
getAllowUntrustedScripts() {
|
|
638
|
+
return this.config.allowUntrustedScripts ?? false;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Get the `allowed-tools` list for a skill.
|
|
642
|
+
*
|
|
643
|
+
* Returns the `allowedTools` array from the skill's frontmatter metadata,
|
|
644
|
+
* enabling agents to filter their tool set based on what the skill expects.
|
|
645
|
+
*
|
|
646
|
+
* @param name - The skill name
|
|
647
|
+
* @returns Array of allowed tool names, or undefined if skill not found or field not set
|
|
648
|
+
*
|
|
649
|
+
* @example
|
|
650
|
+
* ```ts
|
|
651
|
+
* const allowed = registry.getAllowedTools('code-review');
|
|
652
|
+
* if (allowed) {
|
|
653
|
+
* const filteredTools = allTools.filter(t => allowed.includes(t.name));
|
|
654
|
+
* }
|
|
655
|
+
* ```
|
|
656
|
+
*/
|
|
657
|
+
getAllowedTools(name) {
|
|
658
|
+
const skill = this.skills.get(name);
|
|
659
|
+
return skill?.metadata.allowedTools;
|
|
660
|
+
}
|
|
661
|
+
// ─── Prompt Generation ─────────────────────────────────────────────────
|
|
662
|
+
/**
|
|
663
|
+
* Generate an `<available_skills>` XML block for system prompt injection.
|
|
664
|
+
*
|
|
665
|
+
* Returns an empty string when:
|
|
666
|
+
* - `config.enabled` is `false` (default) — agents operate with unmodified prompts
|
|
667
|
+
* - No skills match the filter criteria
|
|
668
|
+
*
|
|
669
|
+
* The output composes naturally with `toolRegistry.generatePrompt()` —
|
|
670
|
+
* simply concatenate both into the system prompt.
|
|
671
|
+
*
|
|
672
|
+
* @param options - Optional filtering (subset of skill names)
|
|
673
|
+
* @returns XML string or empty string
|
|
674
|
+
*
|
|
675
|
+
* @example
|
|
676
|
+
* ```ts
|
|
677
|
+
* // All skills
|
|
678
|
+
* const xml = registry.generatePrompt();
|
|
679
|
+
*
|
|
680
|
+
* // Subset for a focused agent
|
|
681
|
+
* const xml = registry.generatePrompt({ skills: ['code-review', 'testing'] });
|
|
682
|
+
*
|
|
683
|
+
* // Compose with tool prompt
|
|
684
|
+
* const systemPrompt = [
|
|
685
|
+
* toolRegistry.generatePrompt(),
|
|
686
|
+
* skillRegistry.generatePrompt(),
|
|
687
|
+
* ].filter(Boolean).join('\n\n');
|
|
688
|
+
* ```
|
|
689
|
+
*/
|
|
690
|
+
generatePrompt(options) {
|
|
691
|
+
if (!this.config.enabled) {
|
|
692
|
+
logger3.debug("Skill prompt generation skipped (disabled)", {
|
|
693
|
+
enabled: this.config.enabled ?? false
|
|
694
|
+
});
|
|
695
|
+
return "";
|
|
696
|
+
}
|
|
697
|
+
let skills = this.getAll();
|
|
698
|
+
if (options?.skills && options.skills.length > 0) {
|
|
699
|
+
const requested = new Set(options.skills);
|
|
700
|
+
skills = skills.filter((s) => requested.has(s.metadata.name));
|
|
701
|
+
}
|
|
702
|
+
if (this.config.maxDiscoveredSkills !== void 0 && this.config.maxDiscoveredSkills >= 0) {
|
|
703
|
+
skills = skills.slice(0, this.config.maxDiscoveredSkills);
|
|
704
|
+
}
|
|
705
|
+
if (skills.length === 0) {
|
|
706
|
+
logger3.debug("Skill prompt generation produced empty result", {
|
|
707
|
+
totalDiscovered: this.size(),
|
|
708
|
+
filterApplied: !!(options?.skills && options.skills.length > 0),
|
|
709
|
+
maxCap: this.config.maxDiscoveredSkills
|
|
710
|
+
});
|
|
711
|
+
return "";
|
|
712
|
+
}
|
|
713
|
+
const skillEntries = skills.map((skill) => {
|
|
714
|
+
const lines = [
|
|
715
|
+
" <skill>",
|
|
716
|
+
` <name>${escapeXml(skill.metadata.name)}</name>`,
|
|
717
|
+
` <description>${escapeXml(skill.metadata.description)}</description>`,
|
|
718
|
+
` <location>${escapeXml(skill.skillPath)}</location>`,
|
|
719
|
+
" </skill>"
|
|
720
|
+
];
|
|
721
|
+
return lines.join("\n");
|
|
722
|
+
});
|
|
723
|
+
const xml = `<available_skills>
|
|
724
|
+
${skillEntries.join("\n")}
|
|
725
|
+
</available_skills>`;
|
|
726
|
+
const estimatedTokens = Math.ceil(xml.length / 4);
|
|
727
|
+
logger3.info("Skill prompt generated", {
|
|
728
|
+
skillCount: skills.length,
|
|
729
|
+
totalDiscovered: this.size(),
|
|
730
|
+
filterApplied: !!(options?.skills && options.skills.length > 0),
|
|
731
|
+
maxCap: this.config.maxDiscoveredSkills,
|
|
732
|
+
estimatedTokens,
|
|
733
|
+
xmlLength: xml.length
|
|
734
|
+
});
|
|
735
|
+
return xml;
|
|
736
|
+
}
|
|
737
|
+
// ─── Event System ──────────────────────────────────────────────────────
|
|
738
|
+
/**
|
|
739
|
+
* Register an event handler.
|
|
740
|
+
*
|
|
741
|
+
* @param event - The event to listen for
|
|
742
|
+
* @param handler - The handler function
|
|
743
|
+
*
|
|
744
|
+
* @example
|
|
745
|
+
* ```ts
|
|
746
|
+
* registry.on(SkillRegistryEvent.SKILL_DISCOVERED, (skill) => {
|
|
747
|
+
* console.log('Found skill:', skill.metadata.name);
|
|
748
|
+
* });
|
|
749
|
+
* ```
|
|
750
|
+
*/
|
|
751
|
+
on(event, handler) {
|
|
752
|
+
if (!this.eventHandlers.has(event)) {
|
|
753
|
+
this.eventHandlers.set(event, /* @__PURE__ */ new Set());
|
|
754
|
+
}
|
|
755
|
+
this.eventHandlers.get(event).add(handler);
|
|
756
|
+
}
|
|
757
|
+
/**
|
|
758
|
+
* Unregister an event handler.
|
|
759
|
+
*
|
|
760
|
+
* @param event - The event to stop listening for
|
|
761
|
+
* @param handler - The handler function to remove
|
|
762
|
+
*/
|
|
763
|
+
off(event, handler) {
|
|
764
|
+
const handlers = this.eventHandlers.get(event);
|
|
765
|
+
if (handlers) {
|
|
766
|
+
handlers.delete(handler);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Emit an event to all registered handlers.
|
|
771
|
+
*
|
|
772
|
+
* @param event - The event to emit
|
|
773
|
+
* @param data - The event data
|
|
774
|
+
* @private
|
|
775
|
+
*/
|
|
776
|
+
emit(event, data) {
|
|
777
|
+
const handlers = this.eventHandlers.get(event);
|
|
778
|
+
if (handlers) {
|
|
779
|
+
handlers.forEach((handler) => {
|
|
780
|
+
try {
|
|
781
|
+
handler(data);
|
|
782
|
+
} catch (error) {
|
|
783
|
+
logger3.error("Skill event handler error", {
|
|
784
|
+
event,
|
|
785
|
+
error: error instanceof Error ? error.message : String(error),
|
|
786
|
+
stack: error instanceof Error ? error.stack : void 0
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* Emit an event (public API for activation tools).
|
|
794
|
+
*
|
|
795
|
+
* Used by skill activation tools to emit `skill:activated` and
|
|
796
|
+
* `skill:resource-loaded` events through the registry's event system.
|
|
797
|
+
*
|
|
798
|
+
* @param event - The event to emit
|
|
799
|
+
* @param data - The event data
|
|
800
|
+
*/
|
|
801
|
+
emitEvent(event, data) {
|
|
802
|
+
this.emit(event, data);
|
|
803
|
+
}
|
|
804
|
+
// ─── Tool Integration ────────────────────────────────────────────────
|
|
805
|
+
/**
|
|
806
|
+
* Create activation tools pre-wired to this registry instance.
|
|
807
|
+
*
|
|
808
|
+
* Returns `activate-skill` and `read-skill-resource` tools that
|
|
809
|
+
* agents can use to load skill instructions and resources on demand.
|
|
810
|
+
*
|
|
811
|
+
* @returns Array of [activate-skill, read-skill-resource] tools
|
|
812
|
+
*
|
|
813
|
+
* @example
|
|
814
|
+
* ```ts
|
|
815
|
+
* const agent = createReActAgent({
|
|
816
|
+
* model: llm,
|
|
817
|
+
* tools: [
|
|
818
|
+
* ...toolRegistry.toLangChainTools(),
|
|
819
|
+
* ...skillRegistry.toActivationTools(),
|
|
820
|
+
* ],
|
|
821
|
+
* });
|
|
822
|
+
* ```
|
|
823
|
+
*/
|
|
824
|
+
toActivationTools() {
|
|
825
|
+
return createSkillActivationTools(this);
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
function escapeXml(str) {
|
|
829
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
exports.SkillRegistry = SkillRegistry;
|
|
833
|
+
exports.SkillRegistryEvent = SkillRegistryEvent;
|
|
834
|
+
exports.TrustPolicyReason = TrustPolicyReason;
|
|
835
|
+
exports.createActivateSkillTool = createActivateSkillTool;
|
|
836
|
+
exports.createReadSkillResourceTool = createReadSkillResourceTool;
|
|
837
|
+
exports.createSkillActivationTools = createSkillActivationTools;
|
|
838
|
+
exports.evaluateTrustPolicy = evaluateTrustPolicy;
|
|
839
|
+
exports.expandHome = expandHome;
|
|
840
|
+
exports.isScriptResource = isScriptResource;
|
|
841
|
+
exports.normalizeRootConfig = normalizeRootConfig;
|
|
842
|
+
exports.parseSkillContent = parseSkillContent;
|
|
843
|
+
exports.resolveResourcePath = resolveResourcePath;
|
|
844
|
+
exports.scanAllSkillRoots = scanAllSkillRoots;
|
|
845
|
+
exports.scanSkillRoot = scanSkillRoot;
|
|
846
|
+
exports.validateSkillDescription = validateSkillDescription;
|
|
847
|
+
exports.validateSkillName = validateSkillName;
|
|
848
|
+
exports.validateSkillNameMatchesDir = validateSkillNameMatchesDir;
|
|
849
|
+
//# sourceMappingURL=index.cjs.map
|
|
850
|
+
//# sourceMappingURL=index.cjs.map
|