fourmis-agents-sdk 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,289 @@
1
+ // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true,
8
+ configurable: true,
9
+ set: (newValue) => all[name] = () => newValue
10
+ });
11
+ };
12
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
13
+ var __require = import.meta.require;
14
+
15
+ // src/skills/frontmatter.ts
16
+ import { parse } from "yaml";
17
+ function normalizeNewlines(value) {
18
+ return value.replace(/\r\n/g, `
19
+ `).replace(/\r/g, `
20
+ `);
21
+ }
22
+ function extractFrontmatter(content) {
23
+ const normalized = normalizeNewlines(content);
24
+ if (!normalized.startsWith("---")) {
25
+ return { yamlString: null, body: normalized };
26
+ }
27
+ const endIndex = normalized.indexOf(`
28
+ ---`, 3);
29
+ if (endIndex === -1) {
30
+ return { yamlString: null, body: normalized };
31
+ }
32
+ return {
33
+ yamlString: normalized.slice(4, endIndex),
34
+ body: normalized.slice(endIndex + 4).trim()
35
+ };
36
+ }
37
+ function parseFrontmatter(content) {
38
+ const { yamlString, body } = extractFrontmatter(content);
39
+ if (!yamlString) {
40
+ return { frontmatter: {}, body };
41
+ }
42
+ const parsed = parse(yamlString);
43
+ return { frontmatter: parsed ?? {}, body };
44
+ }
45
+ function stripFrontmatter(content) {
46
+ return parseFrontmatter(content).body;
47
+ }
48
+
49
+ // src/skills/skills.ts
50
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "fs";
51
+ import { homedir } from "os";
52
+ import { basename, dirname, isAbsolute, join, resolve } from "path";
53
+ var MAX_NAME_LENGTH = 64;
54
+ var MAX_DESCRIPTION_LENGTH = 1024;
55
+ var CONFIG_DIR_NAME = ".claude";
56
+ function shouldIgnore(name) {
57
+ return name.startsWith(".") || name === "node_modules";
58
+ }
59
+ function validateName(name, parentDirName) {
60
+ const errors = [];
61
+ if (name !== parentDirName) {
62
+ errors.push(`name "${name}" does not match parent directory "${parentDirName}"`);
63
+ }
64
+ if (name.length > MAX_NAME_LENGTH) {
65
+ errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);
66
+ }
67
+ if (!/^[a-z0-9-]+$/.test(name)) {
68
+ errors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`);
69
+ }
70
+ if (name.startsWith("-") || name.endsWith("-")) {
71
+ errors.push(`name must not start or end with a hyphen`);
72
+ }
73
+ if (name.includes("--")) {
74
+ errors.push(`name must not contain consecutive hyphens`);
75
+ }
76
+ return errors;
77
+ }
78
+ function validateDescription(description) {
79
+ const errors = [];
80
+ if (!description || description.trim() === "") {
81
+ errors.push("description is required");
82
+ } else if (description.length > MAX_DESCRIPTION_LENGTH) {
83
+ errors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);
84
+ }
85
+ return errors;
86
+ }
87
+ function loadSkillsFromDir(options) {
88
+ return loadSkillsFromDirInternal(options.dir, options.source, true);
89
+ }
90
+ function loadSkillsFromDirInternal(dir, source, includeRootFiles) {
91
+ const skills = [];
92
+ const diagnostics = [];
93
+ if (!existsSync(dir)) {
94
+ return { skills, diagnostics };
95
+ }
96
+ try {
97
+ const entries = readdirSync(dir, { withFileTypes: true });
98
+ for (const entry of entries) {
99
+ if (shouldIgnore(entry.name)) {
100
+ continue;
101
+ }
102
+ const fullPath = join(dir, entry.name);
103
+ let isDirectory = entry.isDirectory();
104
+ let isFile = entry.isFile();
105
+ if (entry.isSymbolicLink()) {
106
+ try {
107
+ const stats = statSync(fullPath);
108
+ isDirectory = stats.isDirectory();
109
+ isFile = stats.isFile();
110
+ } catch {
111
+ continue;
112
+ }
113
+ }
114
+ if (isDirectory) {
115
+ const subResult = loadSkillsFromDirInternal(fullPath, source, false);
116
+ skills.push(...subResult.skills);
117
+ diagnostics.push(...subResult.diagnostics);
118
+ continue;
119
+ }
120
+ if (!isFile)
121
+ continue;
122
+ const isRootMd = includeRootFiles && entry.name.endsWith(".md");
123
+ const isSkillMd = !includeRootFiles && entry.name === "SKILL.md";
124
+ if (!isRootMd && !isSkillMd)
125
+ continue;
126
+ const result = loadSkillFromFile(fullPath, source);
127
+ if (result.skill) {
128
+ skills.push(result.skill);
129
+ }
130
+ diagnostics.push(...result.diagnostics);
131
+ }
132
+ } catch {}
133
+ return { skills, diagnostics };
134
+ }
135
+ function loadSkillFromFile(filePath, source) {
136
+ const diagnostics = [];
137
+ try {
138
+ const rawContent = readFileSync(filePath, "utf-8");
139
+ const { frontmatter } = parseFrontmatter(rawContent);
140
+ const skillDir = dirname(filePath);
141
+ const parentDirName = basename(skillDir);
142
+ const descErrors = validateDescription(frontmatter.description);
143
+ for (const error of descErrors) {
144
+ diagnostics.push({ type: "warning", message: error, path: filePath });
145
+ }
146
+ const name = frontmatter.name || parentDirName;
147
+ const nameErrors = validateName(name, parentDirName);
148
+ for (const error of nameErrors) {
149
+ diagnostics.push({ type: "warning", message: error, path: filePath });
150
+ }
151
+ if (!frontmatter.description || frontmatter.description.trim() === "") {
152
+ return { skill: null, diagnostics };
153
+ }
154
+ return {
155
+ skill: {
156
+ name,
157
+ description: frontmatter.description,
158
+ filePath,
159
+ baseDir: skillDir,
160
+ source,
161
+ disableModelInvocation: frontmatter["disable-model-invocation"] === true
162
+ },
163
+ diagnostics
164
+ };
165
+ } catch (error) {
166
+ const message = error instanceof Error ? error.message : "failed to parse skill file";
167
+ diagnostics.push({ type: "warning", message, path: filePath });
168
+ return { skill: null, diagnostics };
169
+ }
170
+ }
171
+ function normalizePath(input) {
172
+ const trimmed = input.trim();
173
+ if (trimmed === "~")
174
+ return homedir();
175
+ if (trimmed.startsWith("~/"))
176
+ return join(homedir(), trimmed.slice(2));
177
+ if (trimmed.startsWith("~"))
178
+ return join(homedir(), trimmed.slice(1));
179
+ return trimmed;
180
+ }
181
+ function resolveSkillPath(p, cwd) {
182
+ const normalized = normalizePath(p);
183
+ return isAbsolute(normalized) ? normalized : resolve(cwd, normalized);
184
+ }
185
+ function loadSkills(options = {}) {
186
+ const { cwd = process.cwd(), skillPaths = [], includeDefaults = true } = options;
187
+ const skillMap = new Map;
188
+ const realPathSet = new Set;
189
+ const allDiagnostics = [];
190
+ const collisionDiagnostics = [];
191
+ function addSkills(result) {
192
+ allDiagnostics.push(...result.diagnostics);
193
+ for (const skill of result.skills) {
194
+ let realPath;
195
+ try {
196
+ realPath = realpathSync(skill.filePath);
197
+ } catch {
198
+ realPath = skill.filePath;
199
+ }
200
+ if (realPathSet.has(realPath))
201
+ continue;
202
+ const existing = skillMap.get(skill.name);
203
+ if (existing) {
204
+ collisionDiagnostics.push({
205
+ type: "collision",
206
+ message: `name "${skill.name}" collision`,
207
+ path: skill.filePath,
208
+ collision: {
209
+ resourceType: "skill",
210
+ name: skill.name,
211
+ winnerPath: existing.filePath,
212
+ loserPath: skill.filePath
213
+ }
214
+ });
215
+ } else {
216
+ skillMap.set(skill.name, skill);
217
+ realPathSet.add(realPath);
218
+ }
219
+ }
220
+ }
221
+ if (includeDefaults) {
222
+ const userSkillsDir = join(homedir(), CONFIG_DIR_NAME, "skills");
223
+ const projectSkillsDir = resolve(cwd, CONFIG_DIR_NAME, "skills");
224
+ addSkills(loadSkillsFromDirInternal(userSkillsDir, "user", true));
225
+ addSkills(loadSkillsFromDirInternal(projectSkillsDir, "project", true));
226
+ }
227
+ for (const rawPath of skillPaths) {
228
+ const resolvedPath = resolveSkillPath(rawPath, cwd);
229
+ if (!existsSync(resolvedPath)) {
230
+ allDiagnostics.push({ type: "warning", message: "skill path does not exist", path: resolvedPath });
231
+ continue;
232
+ }
233
+ try {
234
+ const stats = statSync(resolvedPath);
235
+ if (stats.isDirectory()) {
236
+ addSkills(loadSkillsFromDirInternal(resolvedPath, "path", true));
237
+ } else if (stats.isFile() && resolvedPath.endsWith(".md")) {
238
+ const result = loadSkillFromFile(resolvedPath, "path");
239
+ if (result.skill) {
240
+ addSkills({ skills: [result.skill], diagnostics: result.diagnostics });
241
+ } else {
242
+ allDiagnostics.push(...result.diagnostics);
243
+ }
244
+ } else {
245
+ allDiagnostics.push({ type: "warning", message: "skill path is not a markdown file", path: resolvedPath });
246
+ }
247
+ } catch (error) {
248
+ const message = error instanceof Error ? error.message : "failed to read skill path";
249
+ allDiagnostics.push({ type: "warning", message, path: resolvedPath });
250
+ }
251
+ }
252
+ return {
253
+ skills: Array.from(skillMap.values()),
254
+ diagnostics: [...allDiagnostics, ...collisionDiagnostics]
255
+ };
256
+ }
257
+ function escapeXml(str) {
258
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
259
+ }
260
+ function formatSkillsForPrompt(skills) {
261
+ const visibleSkills = skills.filter((s) => !s.disableModelInvocation);
262
+ if (visibleSkills.length === 0) {
263
+ return "";
264
+ }
265
+ const lines = [
266
+ "The following skills provide specialized instructions for specific tasks.",
267
+ "Use the read tool to load a skill's file when the task matches its description.",
268
+ "When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.",
269
+ "",
270
+ "<available_skills>"
271
+ ];
272
+ for (const skill of visibleSkills) {
273
+ lines.push(" <skill>");
274
+ lines.push(` <name>${escapeXml(skill.name)}</name>`);
275
+ lines.push(` <description>${escapeXml(skill.description)}</description>`);
276
+ lines.push(` <location>${escapeXml(skill.filePath)}</location>`);
277
+ lines.push(" </skill>");
278
+ }
279
+ lines.push("</available_skills>");
280
+ return lines.join(`
281
+ `);
282
+ }
283
+ export {
284
+ stripFrontmatter,
285
+ parseFrontmatter,
286
+ loadSkillsFromDir,
287
+ loadSkills,
288
+ formatSkillsForPrompt
289
+ };
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Skill loader — discovers, validates, and formats SKILL.md files.
3
+ *
4
+ * Mirrors the Claude SDK (pi-mono) implementation:
5
+ * - Loads from ~/.claude/skills/ (user), .claude/skills/ (project), and explicit paths
6
+ * - SKILL.md frontmatter: name, description, disable-model-invocation
7
+ * - Name validation: lowercase a-z, 0-9, hyphens, max 64 chars
8
+ * - XML-formatted prompt injection for available skills
9
+ */
10
+ export interface SkillFrontmatter {
11
+ name?: string;
12
+ description?: string;
13
+ "disable-model-invocation"?: boolean;
14
+ [key: string]: unknown;
15
+ }
16
+ export interface Skill {
17
+ name: string;
18
+ description: string;
19
+ filePath: string;
20
+ baseDir: string;
21
+ source: string;
22
+ disableModelInvocation: boolean;
23
+ }
24
+ export interface SkillDiagnostic {
25
+ type: "warning" | "collision";
26
+ message: string;
27
+ path: string;
28
+ collision?: {
29
+ resourceType: "skill";
30
+ name: string;
31
+ winnerPath: string;
32
+ loserPath: string;
33
+ };
34
+ }
35
+ export interface LoadSkillsResult {
36
+ skills: Skill[];
37
+ diagnostics: SkillDiagnostic[];
38
+ }
39
+ export interface LoadSkillsFromDirOptions {
40
+ /** Directory to scan for skills */
41
+ dir: string;
42
+ /** Source identifier for these skills */
43
+ source: string;
44
+ }
45
+ export interface LoadSkillsOptions {
46
+ /** Working directory for project-local skills. Default: process.cwd() */
47
+ cwd?: string;
48
+ /** Explicit skill paths (files or directories) */
49
+ skillPaths?: string[];
50
+ /** Include default skills directories (~/.claude/skills, .claude/skills). Default: true */
51
+ includeDefaults?: boolean;
52
+ }
53
+ /**
54
+ * Load skills from a directory.
55
+ *
56
+ * Discovery rules (matches Claude SDK):
57
+ * - Root-level: any .md file directly in the directory
58
+ * - Subdirectories: only SKILL.md files (recursive)
59
+ */
60
+ export declare function loadSkillsFromDir(options: LoadSkillsFromDirOptions): LoadSkillsResult;
61
+ /**
62
+ * Load skills from all configured locations.
63
+ *
64
+ * Default locations (matches Claude SDK):
65
+ * - ~/.claude/skills/ — user-global skills
66
+ * - .claude/skills/ — project-local skills
67
+ *
68
+ * Plus any explicit `skillPaths` (files or directories).
69
+ */
70
+ export declare function loadSkills(options?: LoadSkillsOptions): LoadSkillsResult;
71
+ /**
72
+ * Format skills for inclusion in a system prompt.
73
+ *
74
+ * Uses XML format per Agent Skills standard (matches Claude SDK).
75
+ * Skills with disableModelInvocation=true are excluded.
76
+ */
77
+ export declare function formatSkillsForPrompt(skills: Skill[]): string;
78
+ //# sourceMappingURL=skills.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skills.d.ts","sourceRoot":"","sources":["../../src/skills/skills.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAgBH,MAAM,WAAW,gBAAgB;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,0BAA0B,CAAC,EAAE,OAAO,CAAC;IACrC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,KAAK;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,sBAAsB,EAAE,OAAO,CAAC;CACjC;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,SAAS,GAAG,WAAW,CAAC;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE;QACV,YAAY,EAAE,OAAO,CAAC;QACtB,IAAI,EAAE,MAAM,CAAC;QACb,UAAU,EAAE,MAAM,CAAC;QACnB,SAAS,EAAE,MAAM,CAAC;KACnB,CAAC;CACH;AAED,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,WAAW,EAAE,eAAe,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,wBAAwB;IACvC,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,yCAAyC;IACzC,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,iBAAiB;IAChC,yEAAyE;IACzE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,kDAAkD;IAClD,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,2FAA2F;IAC3F,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAkDD;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,gBAAgB,CAErF;AAgID;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,OAAO,GAAE,iBAAsB,GAAG,gBAAgB,CAkF5E;AAaD;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,CA0B7D"}
@@ -0,0 +1,287 @@
1
+ // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true,
8
+ configurable: true,
9
+ set: (newValue) => all[name] = () => newValue
10
+ });
11
+ };
12
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
13
+ var __require = import.meta.require;
14
+
15
+ // src/skills/frontmatter.ts
16
+ import { parse } from "yaml";
17
+ function normalizeNewlines(value) {
18
+ return value.replace(/\r\n/g, `
19
+ `).replace(/\r/g, `
20
+ `);
21
+ }
22
+ function extractFrontmatter(content) {
23
+ const normalized = normalizeNewlines(content);
24
+ if (!normalized.startsWith("---")) {
25
+ return { yamlString: null, body: normalized };
26
+ }
27
+ const endIndex = normalized.indexOf(`
28
+ ---`, 3);
29
+ if (endIndex === -1) {
30
+ return { yamlString: null, body: normalized };
31
+ }
32
+ return {
33
+ yamlString: normalized.slice(4, endIndex),
34
+ body: normalized.slice(endIndex + 4).trim()
35
+ };
36
+ }
37
+ function parseFrontmatter(content) {
38
+ const { yamlString, body } = extractFrontmatter(content);
39
+ if (!yamlString) {
40
+ return { frontmatter: {}, body };
41
+ }
42
+ const parsed = parse(yamlString);
43
+ return { frontmatter: parsed ?? {}, body };
44
+ }
45
+ function stripFrontmatter(content) {
46
+ return parseFrontmatter(content).body;
47
+ }
48
+
49
+ // src/skills/skills.ts
50
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "fs";
51
+ import { homedir } from "os";
52
+ import { basename, dirname, isAbsolute, join, resolve } from "path";
53
+ var MAX_NAME_LENGTH = 64;
54
+ var MAX_DESCRIPTION_LENGTH = 1024;
55
+ var CONFIG_DIR_NAME = ".claude";
56
+ function shouldIgnore(name) {
57
+ return name.startsWith(".") || name === "node_modules";
58
+ }
59
+ function validateName(name, parentDirName) {
60
+ const errors = [];
61
+ if (name !== parentDirName) {
62
+ errors.push(`name "${name}" does not match parent directory "${parentDirName}"`);
63
+ }
64
+ if (name.length > MAX_NAME_LENGTH) {
65
+ errors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);
66
+ }
67
+ if (!/^[a-z0-9-]+$/.test(name)) {
68
+ errors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`);
69
+ }
70
+ if (name.startsWith("-") || name.endsWith("-")) {
71
+ errors.push(`name must not start or end with a hyphen`);
72
+ }
73
+ if (name.includes("--")) {
74
+ errors.push(`name must not contain consecutive hyphens`);
75
+ }
76
+ return errors;
77
+ }
78
+ function validateDescription(description) {
79
+ const errors = [];
80
+ if (!description || description.trim() === "") {
81
+ errors.push("description is required");
82
+ } else if (description.length > MAX_DESCRIPTION_LENGTH) {
83
+ errors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);
84
+ }
85
+ return errors;
86
+ }
87
+ function loadSkillsFromDir(options) {
88
+ return loadSkillsFromDirInternal(options.dir, options.source, true);
89
+ }
90
+ function loadSkillsFromDirInternal(dir, source, includeRootFiles) {
91
+ const skills = [];
92
+ const diagnostics = [];
93
+ if (!existsSync(dir)) {
94
+ return { skills, diagnostics };
95
+ }
96
+ try {
97
+ const entries = readdirSync(dir, { withFileTypes: true });
98
+ for (const entry of entries) {
99
+ if (shouldIgnore(entry.name)) {
100
+ continue;
101
+ }
102
+ const fullPath = join(dir, entry.name);
103
+ let isDirectory = entry.isDirectory();
104
+ let isFile = entry.isFile();
105
+ if (entry.isSymbolicLink()) {
106
+ try {
107
+ const stats = statSync(fullPath);
108
+ isDirectory = stats.isDirectory();
109
+ isFile = stats.isFile();
110
+ } catch {
111
+ continue;
112
+ }
113
+ }
114
+ if (isDirectory) {
115
+ const subResult = loadSkillsFromDirInternal(fullPath, source, false);
116
+ skills.push(...subResult.skills);
117
+ diagnostics.push(...subResult.diagnostics);
118
+ continue;
119
+ }
120
+ if (!isFile)
121
+ continue;
122
+ const isRootMd = includeRootFiles && entry.name.endsWith(".md");
123
+ const isSkillMd = !includeRootFiles && entry.name === "SKILL.md";
124
+ if (!isRootMd && !isSkillMd)
125
+ continue;
126
+ const result = loadSkillFromFile(fullPath, source);
127
+ if (result.skill) {
128
+ skills.push(result.skill);
129
+ }
130
+ diagnostics.push(...result.diagnostics);
131
+ }
132
+ } catch {}
133
+ return { skills, diagnostics };
134
+ }
135
+ function loadSkillFromFile(filePath, source) {
136
+ const diagnostics = [];
137
+ try {
138
+ const rawContent = readFileSync(filePath, "utf-8");
139
+ const { frontmatter } = parseFrontmatter(rawContent);
140
+ const skillDir = dirname(filePath);
141
+ const parentDirName = basename(skillDir);
142
+ const descErrors = validateDescription(frontmatter.description);
143
+ for (const error of descErrors) {
144
+ diagnostics.push({ type: "warning", message: error, path: filePath });
145
+ }
146
+ const name = frontmatter.name || parentDirName;
147
+ const nameErrors = validateName(name, parentDirName);
148
+ for (const error of nameErrors) {
149
+ diagnostics.push({ type: "warning", message: error, path: filePath });
150
+ }
151
+ if (!frontmatter.description || frontmatter.description.trim() === "") {
152
+ return { skill: null, diagnostics };
153
+ }
154
+ return {
155
+ skill: {
156
+ name,
157
+ description: frontmatter.description,
158
+ filePath,
159
+ baseDir: skillDir,
160
+ source,
161
+ disableModelInvocation: frontmatter["disable-model-invocation"] === true
162
+ },
163
+ diagnostics
164
+ };
165
+ } catch (error) {
166
+ const message = error instanceof Error ? error.message : "failed to parse skill file";
167
+ diagnostics.push({ type: "warning", message, path: filePath });
168
+ return { skill: null, diagnostics };
169
+ }
170
+ }
171
+ function normalizePath(input) {
172
+ const trimmed = input.trim();
173
+ if (trimmed === "~")
174
+ return homedir();
175
+ if (trimmed.startsWith("~/"))
176
+ return join(homedir(), trimmed.slice(2));
177
+ if (trimmed.startsWith("~"))
178
+ return join(homedir(), trimmed.slice(1));
179
+ return trimmed;
180
+ }
181
+ function resolveSkillPath(p, cwd) {
182
+ const normalized = normalizePath(p);
183
+ return isAbsolute(normalized) ? normalized : resolve(cwd, normalized);
184
+ }
185
+ function loadSkills(options = {}) {
186
+ const { cwd = process.cwd(), skillPaths = [], includeDefaults = true } = options;
187
+ const skillMap = new Map;
188
+ const realPathSet = new Set;
189
+ const allDiagnostics = [];
190
+ const collisionDiagnostics = [];
191
+ function addSkills(result) {
192
+ allDiagnostics.push(...result.diagnostics);
193
+ for (const skill of result.skills) {
194
+ let realPath;
195
+ try {
196
+ realPath = realpathSync(skill.filePath);
197
+ } catch {
198
+ realPath = skill.filePath;
199
+ }
200
+ if (realPathSet.has(realPath))
201
+ continue;
202
+ const existing = skillMap.get(skill.name);
203
+ if (existing) {
204
+ collisionDiagnostics.push({
205
+ type: "collision",
206
+ message: `name "${skill.name}" collision`,
207
+ path: skill.filePath,
208
+ collision: {
209
+ resourceType: "skill",
210
+ name: skill.name,
211
+ winnerPath: existing.filePath,
212
+ loserPath: skill.filePath
213
+ }
214
+ });
215
+ } else {
216
+ skillMap.set(skill.name, skill);
217
+ realPathSet.add(realPath);
218
+ }
219
+ }
220
+ }
221
+ if (includeDefaults) {
222
+ const userSkillsDir = join(homedir(), CONFIG_DIR_NAME, "skills");
223
+ const projectSkillsDir = resolve(cwd, CONFIG_DIR_NAME, "skills");
224
+ addSkills(loadSkillsFromDirInternal(userSkillsDir, "user", true));
225
+ addSkills(loadSkillsFromDirInternal(projectSkillsDir, "project", true));
226
+ }
227
+ for (const rawPath of skillPaths) {
228
+ const resolvedPath = resolveSkillPath(rawPath, cwd);
229
+ if (!existsSync(resolvedPath)) {
230
+ allDiagnostics.push({ type: "warning", message: "skill path does not exist", path: resolvedPath });
231
+ continue;
232
+ }
233
+ try {
234
+ const stats = statSync(resolvedPath);
235
+ if (stats.isDirectory()) {
236
+ addSkills(loadSkillsFromDirInternal(resolvedPath, "path", true));
237
+ } else if (stats.isFile() && resolvedPath.endsWith(".md")) {
238
+ const result = loadSkillFromFile(resolvedPath, "path");
239
+ if (result.skill) {
240
+ addSkills({ skills: [result.skill], diagnostics: result.diagnostics });
241
+ } else {
242
+ allDiagnostics.push(...result.diagnostics);
243
+ }
244
+ } else {
245
+ allDiagnostics.push({ type: "warning", message: "skill path is not a markdown file", path: resolvedPath });
246
+ }
247
+ } catch (error) {
248
+ const message = error instanceof Error ? error.message : "failed to read skill path";
249
+ allDiagnostics.push({ type: "warning", message, path: resolvedPath });
250
+ }
251
+ }
252
+ return {
253
+ skills: Array.from(skillMap.values()),
254
+ diagnostics: [...allDiagnostics, ...collisionDiagnostics]
255
+ };
256
+ }
257
+ function escapeXml(str) {
258
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
259
+ }
260
+ function formatSkillsForPrompt(skills) {
261
+ const visibleSkills = skills.filter((s) => !s.disableModelInvocation);
262
+ if (visibleSkills.length === 0) {
263
+ return "";
264
+ }
265
+ const lines = [
266
+ "The following skills provide specialized instructions for specific tasks.",
267
+ "Use the read tool to load a skill's file when the task matches its description.",
268
+ "When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.",
269
+ "",
270
+ "<available_skills>"
271
+ ];
272
+ for (const skill of visibleSkills) {
273
+ lines.push(" <skill>");
274
+ lines.push(` <name>${escapeXml(skill.name)}</name>`);
275
+ lines.push(` <description>${escapeXml(skill.description)}</description>`);
276
+ lines.push(` <location>${escapeXml(skill.filePath)}</location>`);
277
+ lines.push(" </skill>");
278
+ }
279
+ lines.push("</available_skills>");
280
+ return lines.join(`
281
+ `);
282
+ }
283
+ export {
284
+ loadSkillsFromDir,
285
+ loadSkills,
286
+ formatSkillsForPrompt
287
+ };
package/dist/types.d.ts CHANGED
@@ -193,6 +193,22 @@ export type QueryOptions = {
193
193
  hooks?: Partial<Record<import("./hooks.ts").HookEvent, import("./hooks.ts").HookCallbackMatcher[]>>;
194
194
  mcpServers?: Record<string, import("./mcp/types.ts").McpServerConfig>;
195
195
  agents?: Record<string, import("./agents/types.ts").AgentDefinition>;
196
+ /**
197
+ * Paths to skill files or directories to load.
198
+ * Skills are SKILL.md files with YAML frontmatter (name, description).
199
+ * They get injected into the system prompt as available capabilities.
200
+ *
201
+ * By default, also scans ~/.claude/skills/ and .claude/skills/.
202
+ * Set `includeDefaultSkills: false` to disable default locations.
203
+ *
204
+ * Matches the Claude SDK's skill loading behavior.
205
+ */
206
+ skillPaths?: string[];
207
+ /**
208
+ * Whether to include default skill directories (~/.claude/skills, .claude/skills).
209
+ * Default: true
210
+ */
211
+ includeDefaultSkills?: boolean;
196
212
  /**
197
213
  * Absolute path to the memory directory.
198
214
  * When set, enables the memory tool for the agent.