skpm-cli 1.4.6

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/cli.mjs ADDED
@@ -0,0 +1,4333 @@
1
+ #!/usr/bin/env node
2
+ import { r as __toESM } from "./_chunks/rolldown-runtime.mjs";
3
+ import { l as pD, u as require_picocolors } from "./_chunks/libs/@clack/core.mjs";
4
+ import { a as Y, c as ve, i as Se, l as xe, n as M, o as be, r as Me, s as fe, t as Ie, u as ye } from "./_chunks/libs/@clack/prompts.mjs";
5
+ import "./_chunks/libs/@kwsites/file-exists.mjs";
6
+ import "./_chunks/libs/@kwsites/promise-deferred.mjs";
7
+ import { t as esm_default } from "./_chunks/libs/simple-git.mjs";
8
+ import { t as require_gray_matter } from "./_chunks/libs/gray-matter.mjs";
9
+ import "./_chunks/libs/extend-shallow.mjs";
10
+ import "./_chunks/libs/esprima.mjs";
11
+ import { t as xdgConfig } from "./_chunks/libs/xdg-basedir.mjs";
12
+ import { execSync, spawnSync } from "child_process";
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
14
+ import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "path";
15
+ import { homedir, platform, tmpdir } from "os";
16
+ import { fileURLToPath } from "url";
17
+ import * as readline from "readline";
18
+ import { Writable } from "stream";
19
+ import { access, cp, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rm, stat, symlink, writeFile } from "fs/promises";
20
+ import { createHash } from "crypto";
21
+ var import_picocolors = /* @__PURE__ */ __toESM(require_picocolors(), 1);
22
+ function getOwnerRepo(parsed) {
23
+ if (parsed.type === "local") return null;
24
+ const sshMatch = parsed.url.match(/^git@[^:]+:(.+)$/);
25
+ if (sshMatch) {
26
+ let path = sshMatch[1];
27
+ path = path.replace(/\.git$/, "");
28
+ if (path.includes("/")) return path;
29
+ return null;
30
+ }
31
+ if (!parsed.url.startsWith("http://") && !parsed.url.startsWith("https://")) return null;
32
+ try {
33
+ let path = new URL(parsed.url).pathname.slice(1);
34
+ path = path.replace(/\.git$/, "");
35
+ if (path.includes("/")) return path;
36
+ } catch {}
37
+ return null;
38
+ }
39
+ function parseOwnerRepo(ownerRepo) {
40
+ const match = ownerRepo.match(/^([^/]+)\/([^/]+)$/);
41
+ if (match) return {
42
+ owner: match[1],
43
+ repo: match[2]
44
+ };
45
+ return null;
46
+ }
47
+ async function isRepoPrivate(owner, repo) {
48
+ try {
49
+ const res = await fetch(`https://api.github.com/repos/${owner}/${repo}`);
50
+ if (!res.ok) return null;
51
+ return (await res.json()).private === true;
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+ function sanitizeSubpath(subpath) {
57
+ const segments = subpath.replace(/\\/g, "/").split("/");
58
+ for (const segment of segments) if (segment === "..") throw new Error(`Unsafe subpath: "${subpath}" contains path traversal segments. Subpaths must not contain ".." components.`);
59
+ return subpath;
60
+ }
61
+ function isLocalPath(input) {
62
+ return isAbsolute(input) || input.startsWith("./") || input.startsWith("../") || input === "." || input === ".." || /^[a-zA-Z]:[/\\]/.test(input);
63
+ }
64
+ const SOURCE_ALIASES = { "coinbase/agentWallet": "coinbase/agentic-wallet-skills" };
65
+ function parseSource(input) {
66
+ const alias = SOURCE_ALIASES[input];
67
+ if (alias) input = alias;
68
+ const githubPrefixMatch = input.match(/^github:(.+)$/);
69
+ if (githubPrefixMatch) return parseSource(githubPrefixMatch[1]);
70
+ const gitlabPrefixMatch = input.match(/^gitlab:(.+)$/);
71
+ if (gitlabPrefixMatch) return parseSource(`https://gitlab.com/${gitlabPrefixMatch[1]}`);
72
+ if (isLocalPath(input)) {
73
+ const resolvedPath = resolve(input);
74
+ return {
75
+ type: "local",
76
+ url: resolvedPath,
77
+ localPath: resolvedPath
78
+ };
79
+ }
80
+ const githubTreeWithPathMatch = input.match(/github\.com\/([^/]+)\/([^/]+)\/tree\/([^/]+)\/(.+)/);
81
+ if (githubTreeWithPathMatch) {
82
+ const [, owner, repo, ref, subpath] = githubTreeWithPathMatch;
83
+ return {
84
+ type: "github",
85
+ url: `https://github.com/${owner}/${repo}.git`,
86
+ ref,
87
+ subpath: subpath ? sanitizeSubpath(subpath) : subpath
88
+ };
89
+ }
90
+ const githubTreeMatch = input.match(/github\.com\/([^/]+)\/([^/]+)\/tree\/([^/]+)$/);
91
+ if (githubTreeMatch) {
92
+ const [, owner, repo, ref] = githubTreeMatch;
93
+ return {
94
+ type: "github",
95
+ url: `https://github.com/${owner}/${repo}.git`,
96
+ ref
97
+ };
98
+ }
99
+ const githubRepoMatch = input.match(/github\.com\/([^/]+)\/([^/]+)/);
100
+ if (githubRepoMatch) {
101
+ const [, owner, repo] = githubRepoMatch;
102
+ return {
103
+ type: "github",
104
+ url: `https://github.com/${owner}/${repo.replace(/\.git$/, "")}.git`
105
+ };
106
+ }
107
+ const gitlabTreeWithPathMatch = input.match(/^(https?):\/\/([^/]+)\/(.+?)\/-\/tree\/([^/]+)\/(.+)/);
108
+ if (gitlabTreeWithPathMatch) {
109
+ const [, protocol, hostname, repoPath, ref, subpath] = gitlabTreeWithPathMatch;
110
+ if (hostname !== "github.com" && repoPath) return {
111
+ type: "gitlab",
112
+ url: `${protocol}://${hostname}/${repoPath.replace(/\.git$/, "")}.git`,
113
+ ref,
114
+ subpath: subpath ? sanitizeSubpath(subpath) : subpath
115
+ };
116
+ }
117
+ const gitlabTreeMatch = input.match(/^(https?):\/\/([^/]+)\/(.+?)\/-\/tree\/([^/]+)$/);
118
+ if (gitlabTreeMatch) {
119
+ const [, protocol, hostname, repoPath, ref] = gitlabTreeMatch;
120
+ if (hostname !== "github.com" && repoPath) return {
121
+ type: "gitlab",
122
+ url: `${protocol}://${hostname}/${repoPath.replace(/\.git$/, "")}.git`,
123
+ ref
124
+ };
125
+ }
126
+ const gitlabRepoMatch = input.match(/gitlab\.com\/(.+?)(?:\.git)?\/?$/);
127
+ if (gitlabRepoMatch) {
128
+ const repoPath = gitlabRepoMatch[1];
129
+ if (repoPath.includes("/")) return {
130
+ type: "gitlab",
131
+ url: `https://gitlab.com/${repoPath}.git`
132
+ };
133
+ }
134
+ const atSkillMatch = input.match(/^([^/]+)\/([^/@]+)@(.+)$/);
135
+ if (atSkillMatch && !input.includes(":") && !input.startsWith(".") && !input.startsWith("/")) {
136
+ const [, owner, repo, skillFilter] = atSkillMatch;
137
+ return {
138
+ type: "github",
139
+ url: `https://github.com/${owner}/${repo}.git`,
140
+ skillFilter
141
+ };
142
+ }
143
+ const shorthandMatch = input.match(/^([^/]+)\/([^/]+)(?:\/(.+))?$/);
144
+ if (shorthandMatch && !input.includes(":") && !input.startsWith(".") && !input.startsWith("/")) {
145
+ const [, owner, repo, subpath] = shorthandMatch;
146
+ return {
147
+ type: "github",
148
+ url: `https://github.com/${owner}/${repo}.git`,
149
+ subpath: subpath ? sanitizeSubpath(subpath) : subpath
150
+ };
151
+ }
152
+ if (isWellKnownUrl(input)) return {
153
+ type: "well-known",
154
+ url: input
155
+ };
156
+ return {
157
+ type: "git",
158
+ url: input
159
+ };
160
+ }
161
+ function isWellKnownUrl(input) {
162
+ if (!input.startsWith("http://") && !input.startsWith("https://")) return false;
163
+ try {
164
+ const parsed = new URL(input);
165
+ if ([
166
+ "github.com",
167
+ "gitlab.com",
168
+ "raw.githubusercontent.com"
169
+ ].includes(parsed.hostname)) return false;
170
+ if (input.endsWith(".git")) return false;
171
+ return true;
172
+ } catch {
173
+ return false;
174
+ }
175
+ }
176
+ const silentOutput = new Writable({ write(_chunk, _encoding, callback) {
177
+ callback();
178
+ } });
179
+ const S_STEP_ACTIVE = import_picocolors.default.green("◆");
180
+ const S_STEP_CANCEL = import_picocolors.default.red("■");
181
+ const S_STEP_SUBMIT = import_picocolors.default.green("◇");
182
+ const S_RADIO_ACTIVE = import_picocolors.default.green("●");
183
+ const S_RADIO_INACTIVE = import_picocolors.default.dim("○");
184
+ import_picocolors.default.green("✓");
185
+ const S_BULLET = import_picocolors.default.green("•");
186
+ const S_BAR = import_picocolors.default.dim("│");
187
+ const S_BAR_H = import_picocolors.default.dim("─");
188
+ const cancelSymbol = Symbol("cancel");
189
+ async function searchMultiselect(options) {
190
+ const { message, items, maxVisible = 8, initialSelected = [], required = false, lockedSection } = options;
191
+ return new Promise((resolve) => {
192
+ const rl = readline.createInterface({
193
+ input: process.stdin,
194
+ output: silentOutput,
195
+ terminal: false
196
+ });
197
+ if (process.stdin.isTTY) process.stdin.setRawMode(true);
198
+ readline.emitKeypressEvents(process.stdin, rl);
199
+ let query = "";
200
+ let cursor = 0;
201
+ const selected = new Set(initialSelected);
202
+ let lastRenderHeight = 0;
203
+ const lockedValues = lockedSection ? lockedSection.items.map((i) => i.value) : [];
204
+ const filter = (item, q) => {
205
+ if (!q) return true;
206
+ const lowerQ = q.toLowerCase();
207
+ return item.label.toLowerCase().includes(lowerQ) || String(item.value).toLowerCase().includes(lowerQ);
208
+ };
209
+ const getFiltered = () => {
210
+ return items.filter((item) => filter(item, query));
211
+ };
212
+ const clearRender = () => {
213
+ if (lastRenderHeight > 0) {
214
+ process.stdout.write(`\x1b[${lastRenderHeight}A`);
215
+ for (let i = 0; i < lastRenderHeight; i++) process.stdout.write("\x1B[2K\x1B[1B");
216
+ process.stdout.write(`\x1b[${lastRenderHeight}A`);
217
+ }
218
+ };
219
+ const render = (state = "active") => {
220
+ clearRender();
221
+ const lines = [];
222
+ const filtered = getFiltered();
223
+ const icon = state === "active" ? S_STEP_ACTIVE : state === "cancel" ? S_STEP_CANCEL : S_STEP_SUBMIT;
224
+ lines.push(`${icon} ${import_picocolors.default.bold(message)}`);
225
+ if (state === "active") {
226
+ if (lockedSection && lockedSection.items.length > 0) {
227
+ lines.push(`${S_BAR}`);
228
+ const lockedTitle = `${import_picocolors.default.bold(lockedSection.title)} ${import_picocolors.default.dim("── always included")}`;
229
+ lines.push(`${S_BAR} ${S_BAR_H}${S_BAR_H} ${lockedTitle} ${S_BAR_H.repeat(12)}`);
230
+ for (const item of lockedSection.items) lines.push(`${S_BAR} ${S_BULLET} ${import_picocolors.default.bold(item.label)}`);
231
+ lines.push(`${S_BAR}`);
232
+ lines.push(`${S_BAR} ${S_BAR_H}${S_BAR_H} ${import_picocolors.default.bold("Additional agents")} ${S_BAR_H.repeat(29)}`);
233
+ }
234
+ const searchLine = `${S_BAR} ${import_picocolors.default.dim("Search:")} ${query}${import_picocolors.default.inverse(" ")}`;
235
+ lines.push(searchLine);
236
+ lines.push(`${S_BAR} ${import_picocolors.default.dim("↑↓ move, space select, enter confirm")}`);
237
+ lines.push(`${S_BAR}`);
238
+ const visibleStart = Math.max(0, Math.min(cursor - Math.floor(maxVisible / 2), filtered.length - maxVisible));
239
+ const visibleEnd = Math.min(filtered.length, visibleStart + maxVisible);
240
+ const visibleItems = filtered.slice(visibleStart, visibleEnd);
241
+ if (filtered.length === 0) lines.push(`${S_BAR} ${import_picocolors.default.dim("No matches found")}`);
242
+ else {
243
+ for (let i = 0; i < visibleItems.length; i++) {
244
+ const item = visibleItems[i];
245
+ const actualIndex = visibleStart + i;
246
+ const isSelected = selected.has(item.value);
247
+ const isCursor = actualIndex === cursor;
248
+ const radio = isSelected ? S_RADIO_ACTIVE : S_RADIO_INACTIVE;
249
+ const label = isCursor ? import_picocolors.default.underline(item.label) : item.label;
250
+ const hint = item.hint ? import_picocolors.default.dim(` (${item.hint})`) : "";
251
+ const prefix = isCursor ? import_picocolors.default.cyan("❯") : " ";
252
+ lines.push(`${S_BAR} ${prefix} ${radio} ${label}${hint}`);
253
+ }
254
+ const hiddenBefore = visibleStart;
255
+ const hiddenAfter = filtered.length - visibleEnd;
256
+ if (hiddenBefore > 0 || hiddenAfter > 0) {
257
+ const parts = [];
258
+ if (hiddenBefore > 0) parts.push(`↑ ${hiddenBefore} more`);
259
+ if (hiddenAfter > 0) parts.push(`↓ ${hiddenAfter} more`);
260
+ lines.push(`${S_BAR} ${import_picocolors.default.dim(parts.join(" "))}`);
261
+ }
262
+ }
263
+ lines.push(`${S_BAR}`);
264
+ const allSelectedLabels = [...lockedSection ? lockedSection.items.map((i) => i.label) : [], ...items.filter((item) => selected.has(item.value)).map((item) => item.label)];
265
+ if (allSelectedLabels.length === 0) lines.push(`${S_BAR} ${import_picocolors.default.dim("Selected: (none)")}`);
266
+ else {
267
+ const summary = allSelectedLabels.length <= 3 ? allSelectedLabels.join(", ") : `${allSelectedLabels.slice(0, 3).join(", ")} +${allSelectedLabels.length - 3} more`;
268
+ lines.push(`${S_BAR} ${import_picocolors.default.green("Selected:")} ${summary}`);
269
+ }
270
+ lines.push(`${import_picocolors.default.dim("└")}`);
271
+ } else if (state === "submit") {
272
+ const allSelectedLabels = [...lockedSection ? lockedSection.items.map((i) => i.label) : [], ...items.filter((item) => selected.has(item.value)).map((item) => item.label)];
273
+ lines.push(`${S_BAR} ${import_picocolors.default.dim(allSelectedLabels.join(", "))}`);
274
+ } else if (state === "cancel") lines.push(`${S_BAR} ${import_picocolors.default.strikethrough(import_picocolors.default.dim("Cancelled"))}`);
275
+ process.stdout.write(lines.join("\n") + "\n");
276
+ lastRenderHeight = lines.length;
277
+ };
278
+ const cleanup = () => {
279
+ process.stdin.removeListener("keypress", keypressHandler);
280
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
281
+ rl.close();
282
+ };
283
+ const submit = () => {
284
+ if (required && selected.size === 0 && lockedValues.length === 0) return;
285
+ render("submit");
286
+ cleanup();
287
+ resolve([...lockedValues, ...Array.from(selected)]);
288
+ };
289
+ const cancel = () => {
290
+ render("cancel");
291
+ cleanup();
292
+ resolve(cancelSymbol);
293
+ };
294
+ const keypressHandler = (_str, key) => {
295
+ if (!key) return;
296
+ const filtered = getFiltered();
297
+ if (key.name === "return") {
298
+ submit();
299
+ return;
300
+ }
301
+ if (key.name === "escape" || key.ctrl && key.name === "c") {
302
+ cancel();
303
+ return;
304
+ }
305
+ if (key.name === "up") {
306
+ cursor = Math.max(0, cursor - 1);
307
+ render();
308
+ return;
309
+ }
310
+ if (key.name === "down") {
311
+ cursor = Math.min(filtered.length - 1, cursor + 1);
312
+ render();
313
+ return;
314
+ }
315
+ if (key.name === "space") {
316
+ const item = filtered[cursor];
317
+ if (item) if (selected.has(item.value)) selected.delete(item.value);
318
+ else selected.add(item.value);
319
+ render();
320
+ return;
321
+ }
322
+ if (key.name === "backspace") {
323
+ query = query.slice(0, -1);
324
+ cursor = 0;
325
+ render();
326
+ return;
327
+ }
328
+ if (key.sequence && !key.ctrl && !key.meta && key.sequence.length === 1) {
329
+ query += key.sequence;
330
+ cursor = 0;
331
+ render();
332
+ return;
333
+ }
334
+ };
335
+ process.stdin.on("keypress", keypressHandler);
336
+ render();
337
+ });
338
+ }
339
+ function parseDependencyRef(ref) {
340
+ if (!ref || !ref.includes("/")) return null;
341
+ const atIndex = ref.indexOf("@", ref.indexOf("/"));
342
+ if (atIndex === -1) return {
343
+ source: ref,
344
+ skillName: void 0
345
+ };
346
+ return {
347
+ source: ref.slice(0, atIndex),
348
+ skillName: ref.slice(atIndex + 1)
349
+ };
350
+ }
351
+ async function resolveDependencies(skill, installFn, warn, resolved) {
352
+ const result = {
353
+ resolved: resolved ?? /* @__PURE__ */ new Set(),
354
+ errors: [],
355
+ postInstallCommands: []
356
+ };
357
+ if (skill.dependsOn.length === 0) return result;
358
+ for (const depRef of skill.dependsOn) {
359
+ if (result.resolved.has(depRef)) {
360
+ warn(`Dependency cycle detected: ${skill.name} → ${depRef} (skipping)`);
361
+ continue;
362
+ }
363
+ const parsed = parseDependencyRef(depRef);
364
+ if (!parsed) {
365
+ result.errors.push({
366
+ ref: depRef,
367
+ error: `Invalid dependency reference: ${depRef}`
368
+ });
369
+ continue;
370
+ }
371
+ result.resolved.add(depRef);
372
+ try {
373
+ const installedSkills = await installFn(parsed.source, parsed.skillName);
374
+ for (const depSkill of installedSkills) {
375
+ if (depSkill.postInstall.length > 0) result.postInstallCommands.push(...depSkill.postInstall);
376
+ if (depSkill.dependsOn.length > 0) {
377
+ const subResult = await resolveDependencies(depSkill, installFn, warn, result.resolved);
378
+ for (const err of subResult.errors) result.errors.push(err);
379
+ result.postInstallCommands.push(...subResult.postInstallCommands);
380
+ }
381
+ }
382
+ } catch (err) {
383
+ result.errors.push({
384
+ ref: depRef,
385
+ error: err instanceof Error ? err.message : String(err)
386
+ });
387
+ }
388
+ }
389
+ return result;
390
+ }
391
+ function formatPostInstallCommands(commands) {
392
+ if (commands.length === 0) return "";
393
+ return commands.map((cmd) => ` $ ${cmd}`).join("\n");
394
+ }
395
+ async function executePostInstallCommands(commands, execFn) {
396
+ const result = {
397
+ succeeded: [],
398
+ failed: []
399
+ };
400
+ for (const command of commands) try {
401
+ execFn(command);
402
+ result.succeeded.push(command);
403
+ } catch (err) {
404
+ result.failed.push({
405
+ command,
406
+ error: err instanceof Error ? err.message : String(err)
407
+ });
408
+ }
409
+ return result;
410
+ }
411
+ const CLONE_TIMEOUT_MS = 6e4;
412
+ var GitCloneError = class extends Error {
413
+ url;
414
+ isTimeout;
415
+ isAuthError;
416
+ constructor(message, url, isTimeout = false, isAuthError = false) {
417
+ super(message);
418
+ this.name = "GitCloneError";
419
+ this.url = url;
420
+ this.isTimeout = isTimeout;
421
+ this.isAuthError = isAuthError;
422
+ }
423
+ };
424
+ async function cloneRepo(url, ref) {
425
+ const tempDir = await mkdtemp(join(tmpdir(), "skpm-"));
426
+ process.env.GIT_TERMINAL_PROMPT = "0";
427
+ const git = esm_default({ timeout: { block: CLONE_TIMEOUT_MS } });
428
+ const cloneOptions = ref ? [
429
+ "--depth",
430
+ "1",
431
+ "--branch",
432
+ ref
433
+ ] : ["--depth", "1"];
434
+ try {
435
+ await git.clone(url, tempDir, cloneOptions);
436
+ return tempDir;
437
+ } catch (error) {
438
+ await rm(tempDir, {
439
+ recursive: true,
440
+ force: true
441
+ }).catch(() => {});
442
+ const errorMessage = error instanceof Error ? error.message : String(error);
443
+ const isTimeout = errorMessage.includes("block timeout") || errorMessage.includes("timed out");
444
+ const isAuthError = errorMessage.includes("Authentication failed") || errorMessage.includes("could not read Username") || errorMessage.includes("Permission denied") || errorMessage.includes("Repository not found");
445
+ if (isTimeout) throw new GitCloneError("Clone timed out after 60s. This often happens with private repos that require authentication.\n Ensure you have access and your SSH keys or credentials are configured:\n - For SSH: ssh-add -l (to check loaded keys)\n - For HTTPS: gh auth status (if using GitHub CLI)", url, true, false);
446
+ if (isAuthError) throw new GitCloneError(`Authentication failed for ${url}.\n - For private repos, ensure you have access\n - For SSH: Check your keys with 'ssh -T git@github.com'\n - For HTTPS: Run 'gh auth login' or configure git credentials`, url, false, true);
447
+ throw new GitCloneError(`Failed to clone ${url}: ${errorMessage}`, url, false, false);
448
+ }
449
+ }
450
+ async function cleanupTempDir(dir) {
451
+ const normalizedDir = normalize(resolve(dir));
452
+ const normalizedTmpDir = normalize(resolve(tmpdir()));
453
+ if (!normalizedDir.startsWith(normalizedTmpDir + sep) && normalizedDir !== normalizedTmpDir) throw new Error("Attempted to clean up directory outside of temp directory");
454
+ await rm(dir, {
455
+ recursive: true,
456
+ force: true
457
+ });
458
+ }
459
+ var import_gray_matter = /* @__PURE__ */ __toESM(require_gray_matter(), 1);
460
+ function isContainedIn(targetPath, basePath) {
461
+ const normalizedBase = normalize(resolve(basePath));
462
+ const normalizedTarget = normalize(resolve(targetPath));
463
+ return normalizedTarget.startsWith(normalizedBase + sep) || normalizedTarget === normalizedBase;
464
+ }
465
+ function isValidRelativePath(path) {
466
+ return path.startsWith("./");
467
+ }
468
+ async function getPluginSkillPaths(basePath) {
469
+ const searchDirs = [];
470
+ const addPluginSkillPaths = (pluginBase, skills) => {
471
+ if (!isContainedIn(pluginBase, basePath)) return;
472
+ if (skills && skills.length > 0) for (const skillPath of skills) {
473
+ if (!isValidRelativePath(skillPath)) continue;
474
+ const skillDir = dirname(join(pluginBase, skillPath));
475
+ if (isContainedIn(skillDir, basePath)) searchDirs.push(skillDir);
476
+ }
477
+ searchDirs.push(join(pluginBase, "skills"));
478
+ };
479
+ try {
480
+ const content = await readFile(join(basePath, ".claude-plugin/marketplace.json"), "utf-8");
481
+ const manifest = JSON.parse(content);
482
+ const pluginRoot = manifest.metadata?.pluginRoot;
483
+ if (pluginRoot === void 0 || isValidRelativePath(pluginRoot)) for (const plugin of manifest.plugins ?? []) {
484
+ if (typeof plugin.source !== "string" && plugin.source !== void 0) continue;
485
+ if (plugin.source !== void 0 && !isValidRelativePath(plugin.source)) continue;
486
+ addPluginSkillPaths(join(basePath, pluginRoot ?? "", plugin.source ?? ""), plugin.skills);
487
+ }
488
+ } catch {}
489
+ try {
490
+ const content = await readFile(join(basePath, ".claude-plugin/plugin.json"), "utf-8");
491
+ addPluginSkillPaths(basePath, JSON.parse(content).skills);
492
+ } catch {}
493
+ return searchDirs;
494
+ }
495
+ async function getPluginGroupings(basePath) {
496
+ const groupings = /* @__PURE__ */ new Map();
497
+ try {
498
+ const content = await readFile(join(basePath, ".claude-plugin/marketplace.json"), "utf-8");
499
+ const manifest = JSON.parse(content);
500
+ const pluginRoot = manifest.metadata?.pluginRoot;
501
+ if (pluginRoot === void 0 || isValidRelativePath(pluginRoot)) for (const plugin of manifest.plugins ?? []) {
502
+ if (!plugin.name) continue;
503
+ if (typeof plugin.source !== "string" && plugin.source !== void 0) continue;
504
+ if (plugin.source !== void 0 && !isValidRelativePath(plugin.source)) continue;
505
+ const pluginBase = join(basePath, pluginRoot ?? "", plugin.source ?? "");
506
+ if (!isContainedIn(pluginBase, basePath)) continue;
507
+ if (plugin.skills && plugin.skills.length > 0) for (const skillPath of plugin.skills) {
508
+ if (!isValidRelativePath(skillPath)) continue;
509
+ const skillDir = join(pluginBase, skillPath);
510
+ if (isContainedIn(skillDir, basePath)) groupings.set(resolve(skillDir), plugin.name);
511
+ }
512
+ }
513
+ } catch {}
514
+ try {
515
+ const content = await readFile(join(basePath, ".claude-plugin/plugin.json"), "utf-8");
516
+ const manifest = JSON.parse(content);
517
+ if (manifest.name && manifest.skills && manifest.skills.length > 0) for (const skillPath of manifest.skills) {
518
+ if (!isValidRelativePath(skillPath)) continue;
519
+ const skillDir = join(basePath, skillPath);
520
+ if (isContainedIn(skillDir, basePath)) groupings.set(resolve(skillDir), manifest.name);
521
+ }
522
+ } catch {}
523
+ return groupings;
524
+ }
525
+ const SKIP_DIRS = [
526
+ "node_modules",
527
+ ".git",
528
+ "dist",
529
+ "build",
530
+ "__pycache__"
531
+ ];
532
+ function shouldInstallInternalSkills() {
533
+ const envValue = process.env.INSTALL_INTERNAL_SKILLS;
534
+ return envValue === "1" || envValue === "true";
535
+ }
536
+ async function hasSkillMd(dir) {
537
+ try {
538
+ return (await stat(join(dir, "SKILL.md"))).isFile();
539
+ } catch {
540
+ return false;
541
+ }
542
+ }
543
+ async function parseSkillMd(skillMdPath, options) {
544
+ try {
545
+ const content = await readFile(skillMdPath, "utf-8");
546
+ const { data } = (0, import_gray_matter.default)(content);
547
+ if (!data.name || !data.description) return null;
548
+ if (typeof data.name !== "string" || typeof data.description !== "string") return null;
549
+ if (data.metadata?.internal === true && !shouldInstallInternalSkills() && !options?.includeInternal) return null;
550
+ return {
551
+ name: data.name,
552
+ description: data.description,
553
+ path: dirname(skillMdPath),
554
+ rawContent: content,
555
+ metadata: data.metadata,
556
+ dependsOn: Array.isArray(data.dependsOn) ? data.dependsOn.filter((d) => typeof d === "string") : [],
557
+ postInstall: Array.isArray(data.postInstall) ? data.postInstall.filter((c) => typeof c === "string") : []
558
+ };
559
+ } catch {
560
+ return null;
561
+ }
562
+ }
563
+ async function findSkillDirs(dir, depth = 0, maxDepth = 5) {
564
+ if (depth > maxDepth) return [];
565
+ try {
566
+ const [hasSkill, entries] = await Promise.all([hasSkillMd(dir), readdir(dir, { withFileTypes: true }).catch(() => [])]);
567
+ const currentDir = hasSkill ? [dir] : [];
568
+ const subDirResults = await Promise.all(entries.filter((entry) => entry.isDirectory() && !SKIP_DIRS.includes(entry.name)).map((entry) => findSkillDirs(join(dir, entry.name), depth + 1, maxDepth)));
569
+ return [...currentDir, ...subDirResults.flat()];
570
+ } catch {
571
+ return [];
572
+ }
573
+ }
574
+ function isSubpathSafe(basePath, subpath) {
575
+ const normalizedBase = normalize(resolve(basePath));
576
+ const normalizedTarget = normalize(resolve(join(basePath, subpath)));
577
+ return normalizedTarget.startsWith(normalizedBase + sep) || normalizedTarget === normalizedBase;
578
+ }
579
+ async function discoverSkills(basePath, subpath, options) {
580
+ const skills = [];
581
+ const seenNames = /* @__PURE__ */ new Set();
582
+ if (subpath && !isSubpathSafe(basePath, subpath)) throw new Error(`Invalid subpath: "${subpath}" resolves outside the repository directory. Subpath must not contain ".." segments that escape the base path.`);
583
+ const searchPath = subpath ? join(basePath, subpath) : basePath;
584
+ const pluginGroupings = await getPluginGroupings(searchPath);
585
+ const enhanceSkill = (skill) => {
586
+ const resolvedPath = resolve(skill.path);
587
+ if (pluginGroupings.has(resolvedPath)) skill.pluginName = pluginGroupings.get(resolvedPath);
588
+ return skill;
589
+ };
590
+ if (await hasSkillMd(searchPath)) {
591
+ let skill = await parseSkillMd(join(searchPath, "SKILL.md"), options);
592
+ if (skill) {
593
+ skill = enhanceSkill(skill);
594
+ skills.push(skill);
595
+ seenNames.add(skill.name);
596
+ if (!options?.fullDepth) return skills;
597
+ }
598
+ }
599
+ const prioritySearchDirs = [
600
+ searchPath,
601
+ join(searchPath, "skills"),
602
+ join(searchPath, "skills/.curated"),
603
+ join(searchPath, "skills/.experimental"),
604
+ join(searchPath, "skills/.system"),
605
+ join(searchPath, ".agents/skills"),
606
+ join(searchPath, ".claude/skills"),
607
+ join(searchPath, ".cline/skills"),
608
+ join(searchPath, ".codebuddy/skills"),
609
+ join(searchPath, ".codex/skills"),
610
+ join(searchPath, ".commandcode/skills"),
611
+ join(searchPath, ".continue/skills"),
612
+ join(searchPath, ".github/skills"),
613
+ join(searchPath, ".goose/skills"),
614
+ join(searchPath, ".iflow/skills"),
615
+ join(searchPath, ".junie/skills"),
616
+ join(searchPath, ".kilocode/skills"),
617
+ join(searchPath, ".kiro/skills"),
618
+ join(searchPath, ".mux/skills"),
619
+ join(searchPath, ".neovate/skills"),
620
+ join(searchPath, ".opencode/skills"),
621
+ join(searchPath, ".openhands/skills"),
622
+ join(searchPath, ".pi/skills"),
623
+ join(searchPath, ".qoder/skills"),
624
+ join(searchPath, ".roo/skills"),
625
+ join(searchPath, ".trae/skills"),
626
+ join(searchPath, ".windsurf/skills"),
627
+ join(searchPath, ".zencoder/skills")
628
+ ];
629
+ prioritySearchDirs.push(...await getPluginSkillPaths(searchPath));
630
+ for (const dir of prioritySearchDirs) try {
631
+ const entries = await readdir(dir, { withFileTypes: true });
632
+ for (const entry of entries) if (entry.isDirectory()) {
633
+ const skillDir = join(dir, entry.name);
634
+ if (await hasSkillMd(skillDir)) {
635
+ let skill = await parseSkillMd(join(skillDir, "SKILL.md"), options);
636
+ if (skill && !seenNames.has(skill.name)) {
637
+ skill = enhanceSkill(skill);
638
+ skills.push(skill);
639
+ seenNames.add(skill.name);
640
+ }
641
+ }
642
+ }
643
+ } catch {}
644
+ if (skills.length === 0 || options?.fullDepth) {
645
+ const allSkillDirs = await findSkillDirs(searchPath);
646
+ for (const skillDir of allSkillDirs) {
647
+ let skill = await parseSkillMd(join(skillDir, "SKILL.md"), options);
648
+ if (skill && !seenNames.has(skill.name)) {
649
+ skill = enhanceSkill(skill);
650
+ skills.push(skill);
651
+ seenNames.add(skill.name);
652
+ }
653
+ }
654
+ }
655
+ return skills;
656
+ }
657
+ function getSkillDisplayName(skill) {
658
+ return skill.name || basename(skill.path);
659
+ }
660
+ function filterSkills(skills, inputNames) {
661
+ const normalizedInputs = inputNames.map((n) => n.toLowerCase());
662
+ return skills.filter((skill) => {
663
+ const name = skill.name.toLowerCase();
664
+ const displayName = getSkillDisplayName(skill).toLowerCase();
665
+ return normalizedInputs.some((input) => input === name || input === displayName);
666
+ });
667
+ }
668
+ const home = homedir();
669
+ const configHome = xdgConfig ?? join(home, ".config");
670
+ const codexHome = process.env.CODEX_HOME?.trim() || join(home, ".codex");
671
+ const claudeHome = process.env.CLAUDE_CONFIG_DIR?.trim() || join(home, ".claude");
672
+ function getOpenClawGlobalSkillsDir(homeDir = home, pathExists = existsSync) {
673
+ if (pathExists(join(homeDir, ".openclaw"))) return join(homeDir, ".openclaw/skills");
674
+ if (pathExists(join(homeDir, ".clawdbot"))) return join(homeDir, ".clawdbot/skills");
675
+ if (pathExists(join(homeDir, ".moltbot"))) return join(homeDir, ".moltbot/skills");
676
+ return join(homeDir, ".openclaw/skills");
677
+ }
678
+ const agents = {
679
+ amp: {
680
+ name: "amp",
681
+ displayName: "Amp",
682
+ skillsDir: ".agents/skills",
683
+ globalSkillsDir: join(configHome, "agents/skills"),
684
+ detectInstalled: async () => {
685
+ return existsSync(join(configHome, "amp"));
686
+ }
687
+ },
688
+ antigravity: {
689
+ name: "antigravity",
690
+ displayName: "Antigravity",
691
+ skillsDir: ".agents/skills",
692
+ globalSkillsDir: join(home, ".gemini/antigravity/skills"),
693
+ detectInstalled: async () => {
694
+ return existsSync(join(home, ".gemini/antigravity"));
695
+ }
696
+ },
697
+ augment: {
698
+ name: "augment",
699
+ displayName: "Augment",
700
+ skillsDir: ".augment/skills",
701
+ globalSkillsDir: join(home, ".augment/skills"),
702
+ detectInstalled: async () => {
703
+ return existsSync(join(home, ".augment"));
704
+ }
705
+ },
706
+ "claude-code": {
707
+ name: "claude-code",
708
+ displayName: "Claude Code",
709
+ skillsDir: ".claude/skills",
710
+ globalSkillsDir: join(claudeHome, "skills"),
711
+ detectInstalled: async () => {
712
+ return existsSync(claudeHome);
713
+ }
714
+ },
715
+ openclaw: {
716
+ name: "openclaw",
717
+ displayName: "OpenClaw",
718
+ skillsDir: "skills",
719
+ globalSkillsDir: getOpenClawGlobalSkillsDir(),
720
+ detectInstalled: async () => {
721
+ return existsSync(join(home, ".openclaw")) || existsSync(join(home, ".clawdbot")) || existsSync(join(home, ".moltbot"));
722
+ }
723
+ },
724
+ cline: {
725
+ name: "cline",
726
+ displayName: "Cline",
727
+ skillsDir: ".agents/skills",
728
+ globalSkillsDir: join(home, ".agents", "skills"),
729
+ detectInstalled: async () => {
730
+ return existsSync(join(home, ".cline"));
731
+ }
732
+ },
733
+ codebuddy: {
734
+ name: "codebuddy",
735
+ displayName: "CodeBuddy",
736
+ skillsDir: ".codebuddy/skills",
737
+ globalSkillsDir: join(home, ".codebuddy/skills"),
738
+ detectInstalled: async () => {
739
+ return existsSync(join(process.cwd(), ".codebuddy")) || existsSync(join(home, ".codebuddy"));
740
+ }
741
+ },
742
+ codex: {
743
+ name: "codex",
744
+ displayName: "Codex",
745
+ skillsDir: ".agents/skills",
746
+ globalSkillsDir: join(codexHome, "skills"),
747
+ detectInstalled: async () => {
748
+ return existsSync(codexHome) || existsSync("/etc/codex");
749
+ }
750
+ },
751
+ "command-code": {
752
+ name: "command-code",
753
+ displayName: "Command Code",
754
+ skillsDir: ".commandcode/skills",
755
+ globalSkillsDir: join(home, ".commandcode/skills"),
756
+ detectInstalled: async () => {
757
+ return existsSync(join(home, ".commandcode"));
758
+ }
759
+ },
760
+ continue: {
761
+ name: "continue",
762
+ displayName: "Continue",
763
+ skillsDir: ".continue/skills",
764
+ globalSkillsDir: join(home, ".continue/skills"),
765
+ detectInstalled: async () => {
766
+ return existsSync(join(process.cwd(), ".continue")) || existsSync(join(home, ".continue"));
767
+ }
768
+ },
769
+ cortex: {
770
+ name: "cortex",
771
+ displayName: "Cortex Code",
772
+ skillsDir: ".cortex/skills",
773
+ globalSkillsDir: join(home, ".snowflake/cortex/skills"),
774
+ detectInstalled: async () => {
775
+ return existsSync(join(home, ".snowflake/cortex"));
776
+ }
777
+ },
778
+ crush: {
779
+ name: "crush",
780
+ displayName: "Crush",
781
+ skillsDir: ".crush/skills",
782
+ globalSkillsDir: join(home, ".config/crush/skills"),
783
+ detectInstalled: async () => {
784
+ return existsSync(join(home, ".config/crush"));
785
+ }
786
+ },
787
+ cursor: {
788
+ name: "cursor",
789
+ displayName: "Cursor",
790
+ skillsDir: ".agents/skills",
791
+ globalSkillsDir: join(home, ".cursor/skills"),
792
+ detectInstalled: async () => {
793
+ return existsSync(join(home, ".cursor"));
794
+ }
795
+ },
796
+ deepagents: {
797
+ name: "deepagents",
798
+ displayName: "Deep Agents",
799
+ skillsDir: ".agents/skills",
800
+ globalSkillsDir: join(home, ".deepagents/agent/skills"),
801
+ detectInstalled: async () => {
802
+ return existsSync(join(home, ".deepagents"));
803
+ }
804
+ },
805
+ droid: {
806
+ name: "droid",
807
+ displayName: "Droid",
808
+ skillsDir: ".factory/skills",
809
+ globalSkillsDir: join(home, ".factory/skills"),
810
+ detectInstalled: async () => {
811
+ return existsSync(join(home, ".factory"));
812
+ }
813
+ },
814
+ firebender: {
815
+ name: "firebender",
816
+ displayName: "Firebender",
817
+ skillsDir: ".agents/skills",
818
+ globalSkillsDir: join(home, ".firebender/skills"),
819
+ detectInstalled: async () => {
820
+ return existsSync(join(home, ".firebender"));
821
+ }
822
+ },
823
+ "gemini-cli": {
824
+ name: "gemini-cli",
825
+ displayName: "Gemini CLI",
826
+ skillsDir: ".agents/skills",
827
+ globalSkillsDir: join(home, ".gemini/skills"),
828
+ detectInstalled: async () => {
829
+ return existsSync(join(home, ".gemini"));
830
+ }
831
+ },
832
+ "github-copilot": {
833
+ name: "github-copilot",
834
+ displayName: "GitHub Copilot",
835
+ skillsDir: ".agents/skills",
836
+ globalSkillsDir: join(home, ".copilot/skills"),
837
+ detectInstalled: async () => {
838
+ return existsSync(join(home, ".copilot"));
839
+ }
840
+ },
841
+ goose: {
842
+ name: "goose",
843
+ displayName: "Goose",
844
+ skillsDir: ".goose/skills",
845
+ globalSkillsDir: join(configHome, "goose/skills"),
846
+ detectInstalled: async () => {
847
+ return existsSync(join(configHome, "goose"));
848
+ }
849
+ },
850
+ junie: {
851
+ name: "junie",
852
+ displayName: "Junie",
853
+ skillsDir: ".junie/skills",
854
+ globalSkillsDir: join(home, ".junie/skills"),
855
+ detectInstalled: async () => {
856
+ return existsSync(join(home, ".junie"));
857
+ }
858
+ },
859
+ "iflow-cli": {
860
+ name: "iflow-cli",
861
+ displayName: "iFlow CLI",
862
+ skillsDir: ".iflow/skills",
863
+ globalSkillsDir: join(home, ".iflow/skills"),
864
+ detectInstalled: async () => {
865
+ return existsSync(join(home, ".iflow"));
866
+ }
867
+ },
868
+ kilo: {
869
+ name: "kilo",
870
+ displayName: "Kilo Code",
871
+ skillsDir: ".kilocode/skills",
872
+ globalSkillsDir: join(home, ".kilocode/skills"),
873
+ detectInstalled: async () => {
874
+ return existsSync(join(home, ".kilocode"));
875
+ }
876
+ },
877
+ "kimi-cli": {
878
+ name: "kimi-cli",
879
+ displayName: "Kimi Code CLI",
880
+ skillsDir: ".agents/skills",
881
+ globalSkillsDir: join(home, ".config/agents/skills"),
882
+ detectInstalled: async () => {
883
+ return existsSync(join(home, ".kimi"));
884
+ }
885
+ },
886
+ "kiro-cli": {
887
+ name: "kiro-cli",
888
+ displayName: "Kiro CLI",
889
+ skillsDir: ".kiro/skills",
890
+ globalSkillsDir: join(home, ".kiro/skills"),
891
+ detectInstalled: async () => {
892
+ return existsSync(join(home, ".kiro"));
893
+ }
894
+ },
895
+ kode: {
896
+ name: "kode",
897
+ displayName: "Kode",
898
+ skillsDir: ".kode/skills",
899
+ globalSkillsDir: join(home, ".kode/skills"),
900
+ detectInstalled: async () => {
901
+ return existsSync(join(home, ".kode"));
902
+ }
903
+ },
904
+ mcpjam: {
905
+ name: "mcpjam",
906
+ displayName: "MCPJam",
907
+ skillsDir: ".mcpjam/skills",
908
+ globalSkillsDir: join(home, ".mcpjam/skills"),
909
+ detectInstalled: async () => {
910
+ return existsSync(join(home, ".mcpjam"));
911
+ }
912
+ },
913
+ "mistral-vibe": {
914
+ name: "mistral-vibe",
915
+ displayName: "Mistral Vibe",
916
+ skillsDir: ".vibe/skills",
917
+ globalSkillsDir: join(home, ".vibe/skills"),
918
+ detectInstalled: async () => {
919
+ return existsSync(join(home, ".vibe"));
920
+ }
921
+ },
922
+ mux: {
923
+ name: "mux",
924
+ displayName: "Mux",
925
+ skillsDir: ".mux/skills",
926
+ globalSkillsDir: join(home, ".mux/skills"),
927
+ detectInstalled: async () => {
928
+ return existsSync(join(home, ".mux"));
929
+ }
930
+ },
931
+ opencode: {
932
+ name: "opencode",
933
+ displayName: "OpenCode",
934
+ skillsDir: ".agents/skills",
935
+ globalSkillsDir: join(configHome, "opencode/skills"),
936
+ detectInstalled: async () => {
937
+ return existsSync(join(configHome, "opencode"));
938
+ }
939
+ },
940
+ openhands: {
941
+ name: "openhands",
942
+ displayName: "OpenHands",
943
+ skillsDir: ".openhands/skills",
944
+ globalSkillsDir: join(home, ".openhands/skills"),
945
+ detectInstalled: async () => {
946
+ return existsSync(join(home, ".openhands"));
947
+ }
948
+ },
949
+ pi: {
950
+ name: "pi",
951
+ displayName: "Pi",
952
+ skillsDir: ".pi/skills",
953
+ globalSkillsDir: join(home, ".pi/agent/skills"),
954
+ detectInstalled: async () => {
955
+ return existsSync(join(home, ".pi/agent"));
956
+ }
957
+ },
958
+ qoder: {
959
+ name: "qoder",
960
+ displayName: "Qoder",
961
+ skillsDir: ".qoder/skills",
962
+ globalSkillsDir: join(home, ".qoder/skills"),
963
+ detectInstalled: async () => {
964
+ return existsSync(join(home, ".qoder"));
965
+ }
966
+ },
967
+ "qwen-code": {
968
+ name: "qwen-code",
969
+ displayName: "Qwen Code",
970
+ skillsDir: ".qwen/skills",
971
+ globalSkillsDir: join(home, ".qwen/skills"),
972
+ detectInstalled: async () => {
973
+ return existsSync(join(home, ".qwen"));
974
+ }
975
+ },
976
+ replit: {
977
+ name: "replit",
978
+ displayName: "Replit",
979
+ skillsDir: ".agents/skills",
980
+ globalSkillsDir: join(configHome, "agents/skills"),
981
+ showInUniversalList: false,
982
+ detectInstalled: async () => {
983
+ return existsSync(join(process.cwd(), ".replit"));
984
+ }
985
+ },
986
+ roo: {
987
+ name: "roo",
988
+ displayName: "Roo Code",
989
+ skillsDir: ".roo/skills",
990
+ globalSkillsDir: join(home, ".roo/skills"),
991
+ detectInstalled: async () => {
992
+ return existsSync(join(home, ".roo"));
993
+ }
994
+ },
995
+ trae: {
996
+ name: "trae",
997
+ displayName: "Trae",
998
+ skillsDir: ".trae/skills",
999
+ globalSkillsDir: join(home, ".trae/skills"),
1000
+ detectInstalled: async () => {
1001
+ return existsSync(join(home, ".trae"));
1002
+ }
1003
+ },
1004
+ "trae-cn": {
1005
+ name: "trae-cn",
1006
+ displayName: "Trae CN",
1007
+ skillsDir: ".trae/skills",
1008
+ globalSkillsDir: join(home, ".trae-cn/skills"),
1009
+ detectInstalled: async () => {
1010
+ return existsSync(join(home, ".trae-cn"));
1011
+ }
1012
+ },
1013
+ warp: {
1014
+ name: "warp",
1015
+ displayName: "Warp",
1016
+ skillsDir: ".agents/skills",
1017
+ globalSkillsDir: join(home, ".agents/skills"),
1018
+ detectInstalled: async () => {
1019
+ return existsSync(join(home, ".warp"));
1020
+ }
1021
+ },
1022
+ windsurf: {
1023
+ name: "windsurf",
1024
+ displayName: "Windsurf",
1025
+ skillsDir: ".windsurf/skills",
1026
+ globalSkillsDir: join(home, ".codeium/windsurf/skills"),
1027
+ detectInstalled: async () => {
1028
+ return existsSync(join(home, ".codeium/windsurf"));
1029
+ }
1030
+ },
1031
+ zencoder: {
1032
+ name: "zencoder",
1033
+ displayName: "Zencoder",
1034
+ skillsDir: ".zencoder/skills",
1035
+ globalSkillsDir: join(home, ".zencoder/skills"),
1036
+ detectInstalled: async () => {
1037
+ return existsSync(join(home, ".zencoder"));
1038
+ }
1039
+ },
1040
+ neovate: {
1041
+ name: "neovate",
1042
+ displayName: "Neovate",
1043
+ skillsDir: ".neovate/skills",
1044
+ globalSkillsDir: join(home, ".neovate/skills"),
1045
+ detectInstalled: async () => {
1046
+ return existsSync(join(home, ".neovate"));
1047
+ }
1048
+ },
1049
+ pochi: {
1050
+ name: "pochi",
1051
+ displayName: "Pochi",
1052
+ skillsDir: ".pochi/skills",
1053
+ globalSkillsDir: join(home, ".pochi/skills"),
1054
+ detectInstalled: async () => {
1055
+ return existsSync(join(home, ".pochi"));
1056
+ }
1057
+ },
1058
+ adal: {
1059
+ name: "adal",
1060
+ displayName: "AdaL",
1061
+ skillsDir: ".adal/skills",
1062
+ globalSkillsDir: join(home, ".adal/skills"),
1063
+ detectInstalled: async () => {
1064
+ return existsSync(join(home, ".adal"));
1065
+ }
1066
+ },
1067
+ universal: {
1068
+ name: "universal",
1069
+ displayName: "Universal",
1070
+ skillsDir: ".agents/skills",
1071
+ globalSkillsDir: join(configHome, "agents/skills"),
1072
+ showInUniversalList: false,
1073
+ detectInstalled: async () => false
1074
+ }
1075
+ };
1076
+ async function detectInstalledAgents() {
1077
+ return (await Promise.all(Object.entries(agents).map(async ([type, config]) => ({
1078
+ type,
1079
+ installed: await config.detectInstalled()
1080
+ })))).filter((r) => r.installed).map((r) => r.type);
1081
+ }
1082
+ function getUniversalAgents() {
1083
+ return Object.entries(agents).filter(([_, config]) => config.skillsDir === ".agents/skills" && config.showInUniversalList !== false).map(([type]) => type);
1084
+ }
1085
+ function getNonUniversalAgents() {
1086
+ return Object.entries(agents).filter(([_, config]) => config.skillsDir !== ".agents/skills").map(([type]) => type);
1087
+ }
1088
+ function isUniversalAgent(type) {
1089
+ return agents[type].skillsDir === ".agents/skills";
1090
+ }
1091
+ const AGENTS_DIR$2 = ".agents";
1092
+ const SKILLS_SUBDIR = "skills";
1093
+ function sanitizeName(name) {
1094
+ return name.toLowerCase().replace(/[^a-z0-9._]+/g, "-").replace(/^[.\-]+|[.\-]+$/g, "").substring(0, 255) || "unnamed-skill";
1095
+ }
1096
+ function isPathSafe(basePath, targetPath) {
1097
+ const normalizedBase = normalize(resolve(basePath));
1098
+ const normalizedTarget = normalize(resolve(targetPath));
1099
+ return normalizedTarget.startsWith(normalizedBase + sep) || normalizedTarget === normalizedBase;
1100
+ }
1101
+ function getCanonicalSkillsDir(global, cwd) {
1102
+ return join(global ? homedir() : cwd || process.cwd(), AGENTS_DIR$2, SKILLS_SUBDIR);
1103
+ }
1104
+ function getAgentBaseDir(agentType, global, cwd) {
1105
+ if (isUniversalAgent(agentType)) return getCanonicalSkillsDir(global, cwd);
1106
+ const agent = agents[agentType];
1107
+ const baseDir = global ? homedir() : cwd || process.cwd();
1108
+ if (global) {
1109
+ if (agent.globalSkillsDir === void 0) return join(baseDir, agent.skillsDir);
1110
+ return agent.globalSkillsDir;
1111
+ }
1112
+ return join(baseDir, agent.skillsDir);
1113
+ }
1114
+ function resolveSymlinkTarget(linkPath, linkTarget) {
1115
+ return resolve(dirname(linkPath), linkTarget);
1116
+ }
1117
+ async function cleanAndCreateDirectory(path) {
1118
+ try {
1119
+ await rm(path, {
1120
+ recursive: true,
1121
+ force: true
1122
+ });
1123
+ } catch {}
1124
+ await mkdir(path, { recursive: true });
1125
+ }
1126
+ async function resolveParentSymlinks(path) {
1127
+ const resolved = resolve(path);
1128
+ const dir = dirname(resolved);
1129
+ const base = basename(resolved);
1130
+ try {
1131
+ return join(await realpath(dir), base);
1132
+ } catch {
1133
+ return resolved;
1134
+ }
1135
+ }
1136
+ async function createSymlink(target, linkPath) {
1137
+ try {
1138
+ const resolvedTarget = resolve(target);
1139
+ const resolvedLinkPath = resolve(linkPath);
1140
+ const [realTarget, realLinkPath] = await Promise.all([realpath(resolvedTarget).catch(() => resolvedTarget), realpath(resolvedLinkPath).catch(() => resolvedLinkPath)]);
1141
+ if (realTarget === realLinkPath) return true;
1142
+ if (await resolveParentSymlinks(target) === await resolveParentSymlinks(linkPath)) return true;
1143
+ try {
1144
+ if ((await lstat(linkPath)).isSymbolicLink()) {
1145
+ if (resolveSymlinkTarget(linkPath, await readlink(linkPath)) === resolvedTarget) return true;
1146
+ await rm(linkPath);
1147
+ } else await rm(linkPath, { recursive: true });
1148
+ } catch (err) {
1149
+ if (err && typeof err === "object" && "code" in err && err.code === "ELOOP") try {
1150
+ await rm(linkPath, { force: true });
1151
+ } catch {}
1152
+ }
1153
+ const linkDir = dirname(linkPath);
1154
+ await mkdir(linkDir, { recursive: true });
1155
+ await symlink(relative(await resolveParentSymlinks(linkDir), target), linkPath, platform() === "win32" ? "junction" : void 0);
1156
+ return true;
1157
+ } catch {
1158
+ return false;
1159
+ }
1160
+ }
1161
+ async function installSkillForAgent(skill, agentType, options = {}) {
1162
+ const agent = agents[agentType];
1163
+ const isGlobal = options.global ?? false;
1164
+ const cwd = options.cwd || process.cwd();
1165
+ if (isGlobal && agent.globalSkillsDir === void 0) return {
1166
+ success: false,
1167
+ path: "",
1168
+ mode: options.mode ?? "symlink",
1169
+ error: `${agent.displayName} does not support global skill installation`
1170
+ };
1171
+ const skillName = sanitizeName(skill.name || basename(skill.path));
1172
+ const canonicalBase = getCanonicalSkillsDir(isGlobal, cwd);
1173
+ const canonicalDir = join(canonicalBase, skillName);
1174
+ const agentBase = getAgentBaseDir(agentType, isGlobal, cwd);
1175
+ const agentDir = join(agentBase, skillName);
1176
+ const installMode = options.mode ?? "symlink";
1177
+ if (!isPathSafe(canonicalBase, canonicalDir)) return {
1178
+ success: false,
1179
+ path: agentDir,
1180
+ mode: installMode,
1181
+ error: "Invalid skill name: potential path traversal detected"
1182
+ };
1183
+ if (!isPathSafe(agentBase, agentDir)) return {
1184
+ success: false,
1185
+ path: agentDir,
1186
+ mode: installMode,
1187
+ error: "Invalid skill name: potential path traversal detected"
1188
+ };
1189
+ try {
1190
+ if (installMode === "copy") {
1191
+ await cleanAndCreateDirectory(agentDir);
1192
+ await copyDirectory(skill.path, agentDir);
1193
+ return {
1194
+ success: true,
1195
+ path: agentDir,
1196
+ mode: "copy"
1197
+ };
1198
+ }
1199
+ await cleanAndCreateDirectory(canonicalDir);
1200
+ await copyDirectory(skill.path, canonicalDir);
1201
+ if (isGlobal && isUniversalAgent(agentType)) return {
1202
+ success: true,
1203
+ path: canonicalDir,
1204
+ canonicalPath: canonicalDir,
1205
+ mode: "symlink"
1206
+ };
1207
+ if (!await createSymlink(canonicalDir, agentDir)) {
1208
+ await cleanAndCreateDirectory(agentDir);
1209
+ await copyDirectory(skill.path, agentDir);
1210
+ return {
1211
+ success: true,
1212
+ path: agentDir,
1213
+ canonicalPath: canonicalDir,
1214
+ mode: "symlink",
1215
+ symlinkFailed: true
1216
+ };
1217
+ }
1218
+ return {
1219
+ success: true,
1220
+ path: agentDir,
1221
+ canonicalPath: canonicalDir,
1222
+ mode: "symlink"
1223
+ };
1224
+ } catch (error) {
1225
+ return {
1226
+ success: false,
1227
+ path: agentDir,
1228
+ mode: installMode,
1229
+ error: error instanceof Error ? error.message : "Unknown error"
1230
+ };
1231
+ }
1232
+ }
1233
+ const EXCLUDE_FILES = new Set(["metadata.json"]);
1234
+ const EXCLUDE_DIRS = new Set([
1235
+ ".git",
1236
+ "__pycache__",
1237
+ "__pypackages__"
1238
+ ]);
1239
+ const isExcluded = (name, isDirectory = false) => {
1240
+ if (EXCLUDE_FILES.has(name)) return true;
1241
+ if (name.startsWith(".")) return true;
1242
+ if (isDirectory && EXCLUDE_DIRS.has(name)) return true;
1243
+ return false;
1244
+ };
1245
+ async function copyDirectory(src, dest) {
1246
+ await mkdir(dest, { recursive: true });
1247
+ const entries = await readdir(src, { withFileTypes: true });
1248
+ await Promise.all(entries.filter((entry) => !isExcluded(entry.name, entry.isDirectory())).map(async (entry) => {
1249
+ const srcPath = join(src, entry.name);
1250
+ const destPath = join(dest, entry.name);
1251
+ if (entry.isDirectory()) await copyDirectory(srcPath, destPath);
1252
+ else try {
1253
+ await cp(srcPath, destPath, {
1254
+ dereference: true,
1255
+ recursive: true
1256
+ });
1257
+ } catch (err) {
1258
+ if (err instanceof Error && "code" in err && err.code === "ENOENT" && entry.isSymbolicLink()) console.warn(`Skipping broken symlink: ${srcPath}`);
1259
+ else throw err;
1260
+ }
1261
+ }));
1262
+ }
1263
+ async function isSkillInstalled(skillName, agentType, options = {}) {
1264
+ const agent = agents[agentType];
1265
+ const sanitized = sanitizeName(skillName);
1266
+ if (options.global && agent.globalSkillsDir === void 0) return false;
1267
+ const targetBase = options.global ? agent.globalSkillsDir : join(options.cwd || process.cwd(), agent.skillsDir);
1268
+ const skillDir = join(targetBase, sanitized);
1269
+ if (!isPathSafe(targetBase, skillDir)) return false;
1270
+ try {
1271
+ await access(skillDir);
1272
+ return true;
1273
+ } catch {
1274
+ return false;
1275
+ }
1276
+ }
1277
+ function getInstallPath(skillName, agentType, options = {}) {
1278
+ agents[agentType];
1279
+ options.cwd || process.cwd();
1280
+ const sanitized = sanitizeName(skillName);
1281
+ const targetBase = getAgentBaseDir(agentType, options.global ?? false, options.cwd);
1282
+ const installPath = join(targetBase, sanitized);
1283
+ if (!isPathSafe(targetBase, installPath)) throw new Error("Invalid skill name: potential path traversal detected");
1284
+ return installPath;
1285
+ }
1286
+ function getCanonicalPath(skillName, options = {}) {
1287
+ const sanitized = sanitizeName(skillName);
1288
+ const canonicalBase = getCanonicalSkillsDir(options.global ?? false, options.cwd);
1289
+ const canonicalPath = join(canonicalBase, sanitized);
1290
+ if (!isPathSafe(canonicalBase, canonicalPath)) throw new Error("Invalid skill name: potential path traversal detected");
1291
+ return canonicalPath;
1292
+ }
1293
+ async function installWellKnownSkillForAgent(skill, agentType, options = {}) {
1294
+ const agent = agents[agentType];
1295
+ const isGlobal = options.global ?? false;
1296
+ const cwd = options.cwd || process.cwd();
1297
+ const installMode = options.mode ?? "symlink";
1298
+ if (isGlobal && agent.globalSkillsDir === void 0) return {
1299
+ success: false,
1300
+ path: "",
1301
+ mode: installMode,
1302
+ error: `${agent.displayName} does not support global skill installation`
1303
+ };
1304
+ const skillName = sanitizeName(skill.installName);
1305
+ const canonicalBase = getCanonicalSkillsDir(isGlobal, cwd);
1306
+ const canonicalDir = join(canonicalBase, skillName);
1307
+ const agentBase = getAgentBaseDir(agentType, isGlobal, cwd);
1308
+ const agentDir = join(agentBase, skillName);
1309
+ if (!isPathSafe(canonicalBase, canonicalDir)) return {
1310
+ success: false,
1311
+ path: agentDir,
1312
+ mode: installMode,
1313
+ error: "Invalid skill name: potential path traversal detected"
1314
+ };
1315
+ if (!isPathSafe(agentBase, agentDir)) return {
1316
+ success: false,
1317
+ path: agentDir,
1318
+ mode: installMode,
1319
+ error: "Invalid skill name: potential path traversal detected"
1320
+ };
1321
+ async function writeSkillFiles(targetDir) {
1322
+ for (const [filePath, content] of skill.files) {
1323
+ const fullPath = join(targetDir, filePath);
1324
+ if (!isPathSafe(targetDir, fullPath)) continue;
1325
+ const parentDir = dirname(fullPath);
1326
+ if (parentDir !== targetDir) await mkdir(parentDir, { recursive: true });
1327
+ await writeFile(fullPath, content, "utf-8");
1328
+ }
1329
+ }
1330
+ try {
1331
+ if (installMode === "copy") {
1332
+ await cleanAndCreateDirectory(agentDir);
1333
+ await writeSkillFiles(agentDir);
1334
+ return {
1335
+ success: true,
1336
+ path: agentDir,
1337
+ mode: "copy"
1338
+ };
1339
+ }
1340
+ await cleanAndCreateDirectory(canonicalDir);
1341
+ await writeSkillFiles(canonicalDir);
1342
+ if (isGlobal && isUniversalAgent(agentType)) return {
1343
+ success: true,
1344
+ path: canonicalDir,
1345
+ canonicalPath: canonicalDir,
1346
+ mode: "symlink"
1347
+ };
1348
+ if (!await createSymlink(canonicalDir, agentDir)) {
1349
+ await cleanAndCreateDirectory(agentDir);
1350
+ await writeSkillFiles(agentDir);
1351
+ return {
1352
+ success: true,
1353
+ path: agentDir,
1354
+ canonicalPath: canonicalDir,
1355
+ mode: "symlink",
1356
+ symlinkFailed: true
1357
+ };
1358
+ }
1359
+ return {
1360
+ success: true,
1361
+ path: agentDir,
1362
+ canonicalPath: canonicalDir,
1363
+ mode: "symlink"
1364
+ };
1365
+ } catch (error) {
1366
+ return {
1367
+ success: false,
1368
+ path: agentDir,
1369
+ mode: installMode,
1370
+ error: error instanceof Error ? error.message : "Unknown error"
1371
+ };
1372
+ }
1373
+ }
1374
+ async function listInstalledSkills(options = {}) {
1375
+ const cwd = options.cwd || process.cwd();
1376
+ const skillsMap = /* @__PURE__ */ new Map();
1377
+ const scopes = [];
1378
+ const detectedAgents = await detectInstalledAgents();
1379
+ const agentFilter = options.agentFilter;
1380
+ const agentsToCheck = agentFilter ? detectedAgents.filter((a) => agentFilter.includes(a)) : detectedAgents;
1381
+ const scopeTypes = [];
1382
+ if (options.global === void 0) scopeTypes.push({ global: false }, { global: true });
1383
+ else scopeTypes.push({ global: options.global });
1384
+ for (const { global: isGlobal } of scopeTypes) {
1385
+ scopes.push({
1386
+ global: isGlobal,
1387
+ path: getCanonicalSkillsDir(isGlobal, cwd)
1388
+ });
1389
+ for (const agentType of agentsToCheck) {
1390
+ const agent = agents[agentType];
1391
+ if (isGlobal && agent.globalSkillsDir === void 0) continue;
1392
+ const agentDir = isGlobal ? agent.globalSkillsDir : join(cwd, agent.skillsDir);
1393
+ if (!scopes.some((s) => s.path === agentDir && s.global === isGlobal)) scopes.push({
1394
+ global: isGlobal,
1395
+ path: agentDir,
1396
+ agentType
1397
+ });
1398
+ }
1399
+ const allAgentTypes = Object.keys(agents);
1400
+ for (const agentType of allAgentTypes) {
1401
+ if (agentsToCheck.includes(agentType)) continue;
1402
+ const agent = agents[agentType];
1403
+ if (isGlobal && agent.globalSkillsDir === void 0) continue;
1404
+ const agentDir = isGlobal ? agent.globalSkillsDir : join(cwd, agent.skillsDir);
1405
+ if (scopes.some((s) => s.path === agentDir && s.global === isGlobal)) continue;
1406
+ if (existsSync(agentDir)) scopes.push({
1407
+ global: isGlobal,
1408
+ path: agentDir,
1409
+ agentType
1410
+ });
1411
+ }
1412
+ }
1413
+ for (const scope of scopes) try {
1414
+ const entries = await readdir(scope.path, { withFileTypes: true });
1415
+ for (const entry of entries) {
1416
+ if (!entry.isDirectory()) continue;
1417
+ const skillDir = join(scope.path, entry.name);
1418
+ const skillMdPath = join(skillDir, "SKILL.md");
1419
+ try {
1420
+ await stat(skillMdPath);
1421
+ } catch {
1422
+ continue;
1423
+ }
1424
+ const skill = await parseSkillMd(skillMdPath);
1425
+ if (!skill) continue;
1426
+ const scopeKey = scope.global ? "global" : "project";
1427
+ const skillKey = `${scopeKey}:${skill.name}`;
1428
+ if (scope.agentType) {
1429
+ if (skillsMap.has(skillKey)) {
1430
+ const existing = skillsMap.get(skillKey);
1431
+ if (!existing.agents.includes(scope.agentType)) existing.agents.push(scope.agentType);
1432
+ } else skillsMap.set(skillKey, {
1433
+ name: skill.name,
1434
+ description: skill.description,
1435
+ path: skillDir,
1436
+ canonicalPath: skillDir,
1437
+ scope: scopeKey,
1438
+ agents: [scope.agentType]
1439
+ });
1440
+ continue;
1441
+ }
1442
+ const sanitizedSkillName = sanitizeName(skill.name);
1443
+ const installedAgents = [];
1444
+ for (const agentType of agentsToCheck) {
1445
+ const agent = agents[agentType];
1446
+ if (scope.global && agent.globalSkillsDir === void 0) continue;
1447
+ const agentBase = scope.global ? agent.globalSkillsDir : join(cwd, agent.skillsDir);
1448
+ let found = false;
1449
+ const possibleNames = Array.from(new Set([
1450
+ entry.name,
1451
+ sanitizedSkillName,
1452
+ skill.name.toLowerCase().replace(/\s+/g, "-").replace(/[\/\\:\0]/g, "")
1453
+ ]));
1454
+ for (const possibleName of possibleNames) {
1455
+ const agentSkillDir = join(agentBase, possibleName);
1456
+ if (!isPathSafe(agentBase, agentSkillDir)) continue;
1457
+ try {
1458
+ await access(agentSkillDir);
1459
+ found = true;
1460
+ break;
1461
+ } catch {}
1462
+ }
1463
+ if (!found) try {
1464
+ const agentEntries = await readdir(agentBase, { withFileTypes: true });
1465
+ for (const agentEntry of agentEntries) {
1466
+ if (!agentEntry.isDirectory()) continue;
1467
+ const candidateDir = join(agentBase, agentEntry.name);
1468
+ if (!isPathSafe(agentBase, candidateDir)) continue;
1469
+ try {
1470
+ const candidateSkillMd = join(candidateDir, "SKILL.md");
1471
+ await stat(candidateSkillMd);
1472
+ const candidateSkill = await parseSkillMd(candidateSkillMd);
1473
+ if (candidateSkill && candidateSkill.name === skill.name) {
1474
+ found = true;
1475
+ break;
1476
+ }
1477
+ } catch {}
1478
+ }
1479
+ } catch {}
1480
+ if (found) installedAgents.push(agentType);
1481
+ }
1482
+ if (skillsMap.has(skillKey)) {
1483
+ const existing = skillsMap.get(skillKey);
1484
+ for (const agent of installedAgents) if (!existing.agents.includes(agent)) existing.agents.push(agent);
1485
+ } else skillsMap.set(skillKey, {
1486
+ name: skill.name,
1487
+ description: skill.description,
1488
+ path: skillDir,
1489
+ canonicalPath: skillDir,
1490
+ scope: scopeKey,
1491
+ agents: installedAgents
1492
+ });
1493
+ }
1494
+ } catch {}
1495
+ return Array.from(skillsMap.values());
1496
+ }
1497
+ const TELEMETRY_URL = "https://skpm.sh/t";
1498
+ const AUDIT_URL = "https://skpm.sh/audit";
1499
+ let cliVersion = null;
1500
+ function isCI() {
1501
+ return !!(process.env.CI || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI || process.env.CIRCLECI || process.env.TRAVIS || process.env.BUILDKITE || process.env.JENKINS_URL || process.env.TEAMCITY_VERSION);
1502
+ }
1503
+ function isEnabled() {
1504
+ return !process.env.DISABLE_TELEMETRY && !process.env.DO_NOT_TRACK;
1505
+ }
1506
+ function setVersion(version) {
1507
+ cliVersion = version;
1508
+ }
1509
+ async function fetchAuditData(source, skillSlugs, timeoutMs = 3e3) {
1510
+ if (skillSlugs.length === 0) return null;
1511
+ try {
1512
+ const params = new URLSearchParams({
1513
+ source,
1514
+ skills: skillSlugs.join(",")
1515
+ });
1516
+ const controller = new AbortController();
1517
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
1518
+ const response = await fetch(`${AUDIT_URL}?${params.toString()}`, { signal: controller.signal });
1519
+ clearTimeout(timeout);
1520
+ if (!response.ok) return null;
1521
+ return await response.json();
1522
+ } catch {
1523
+ return null;
1524
+ }
1525
+ }
1526
+ function track(data) {
1527
+ if (!isEnabled()) return;
1528
+ try {
1529
+ const params = new URLSearchParams();
1530
+ if (cliVersion) params.set("v", cliVersion);
1531
+ if (isCI()) params.set("ci", "1");
1532
+ for (const [key, value] of Object.entries(data)) if (value !== void 0 && value !== null) params.set(key, String(value));
1533
+ fetch(`${TELEMETRY_URL}?${params.toString()}`).catch(() => {});
1534
+ } catch {}
1535
+ }
1536
+ var ProviderRegistryImpl = class {
1537
+ providers = [];
1538
+ register(provider) {
1539
+ if (this.providers.some((p) => p.id === provider.id)) throw new Error(`Provider with id "${provider.id}" already registered`);
1540
+ this.providers.push(provider);
1541
+ }
1542
+ findProvider(url) {
1543
+ for (const provider of this.providers) if (provider.match(url).matches) return provider;
1544
+ return null;
1545
+ }
1546
+ getProviders() {
1547
+ return [...this.providers];
1548
+ }
1549
+ };
1550
+ new ProviderRegistryImpl();
1551
+ var WellKnownProvider = class {
1552
+ id = "well-known";
1553
+ displayName = "Well-Known Skills";
1554
+ WELL_KNOWN_PATHS = [".well-known/agent-skills", ".well-known/skills"];
1555
+ INDEX_FILE = "index.json";
1556
+ match(url) {
1557
+ if (!url.startsWith("http://") && !url.startsWith("https://")) return { matches: false };
1558
+ try {
1559
+ const parsed = new URL(url);
1560
+ if ([
1561
+ "github.com",
1562
+ "gitlab.com",
1563
+ "huggingface.co"
1564
+ ].includes(parsed.hostname)) return { matches: false };
1565
+ return {
1566
+ matches: true,
1567
+ sourceIdentifier: `wellknown/${parsed.hostname}`
1568
+ };
1569
+ } catch {
1570
+ return { matches: false };
1571
+ }
1572
+ }
1573
+ async fetchIndex(baseUrl) {
1574
+ try {
1575
+ const parsed = new URL(baseUrl);
1576
+ const basePath = parsed.pathname.replace(/\/$/, "");
1577
+ const urlsToTry = [];
1578
+ for (const wellKnownPath of this.WELL_KNOWN_PATHS) {
1579
+ urlsToTry.push({
1580
+ indexUrl: `${parsed.protocol}//${parsed.host}${basePath}/${wellKnownPath}/${this.INDEX_FILE}`,
1581
+ baseUrl: `${parsed.protocol}//${parsed.host}${basePath}`,
1582
+ wellKnownPath
1583
+ });
1584
+ if (basePath && basePath !== "") urlsToTry.push({
1585
+ indexUrl: `${parsed.protocol}//${parsed.host}/${wellKnownPath}/${this.INDEX_FILE}`,
1586
+ baseUrl: `${parsed.protocol}//${parsed.host}`,
1587
+ wellKnownPath
1588
+ });
1589
+ }
1590
+ for (const { indexUrl, baseUrl: resolvedBase, wellKnownPath } of urlsToTry) try {
1591
+ const response = await fetch(indexUrl);
1592
+ if (!response.ok) continue;
1593
+ const index = await response.json();
1594
+ if (!index.skills || !Array.isArray(index.skills)) continue;
1595
+ let allValid = true;
1596
+ for (const entry of index.skills) if (!this.isValidSkillEntry(entry)) {
1597
+ allValid = false;
1598
+ break;
1599
+ }
1600
+ if (allValid) return {
1601
+ index,
1602
+ resolvedBaseUrl: resolvedBase,
1603
+ resolvedWellKnownPath: wellKnownPath
1604
+ };
1605
+ } catch {
1606
+ continue;
1607
+ }
1608
+ return null;
1609
+ } catch {
1610
+ return null;
1611
+ }
1612
+ }
1613
+ isValidSkillEntry(entry) {
1614
+ if (!entry || typeof entry !== "object") return false;
1615
+ const e = entry;
1616
+ if (typeof e.name !== "string" || !e.name) return false;
1617
+ if (typeof e.description !== "string" || !e.description) return false;
1618
+ if (!Array.isArray(e.files) || e.files.length === 0) return false;
1619
+ if (!/^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/.test(e.name) && e.name.length > 1) {
1620
+ if (e.name.length === 1 && !/^[a-z0-9]$/.test(e.name)) return false;
1621
+ }
1622
+ for (const file of e.files) {
1623
+ if (typeof file !== "string") return false;
1624
+ if (file.startsWith("/") || file.startsWith("\\") || file.includes("..")) return false;
1625
+ }
1626
+ if (!e.files.some((f) => typeof f === "string" && f.toLowerCase() === "skill.md")) return false;
1627
+ return true;
1628
+ }
1629
+ async fetchSkill(url) {
1630
+ try {
1631
+ const parsed = new URL(url);
1632
+ const result = await this.fetchIndex(url);
1633
+ if (!result) return null;
1634
+ const { index, resolvedBaseUrl, resolvedWellKnownPath } = result;
1635
+ let skillName = null;
1636
+ const pathMatch = parsed.pathname.match(/\/.well-known\/(?:agent-skills|skills)\/([^/]+)\/?$/);
1637
+ if (pathMatch && pathMatch[1] && pathMatch[1] !== "index.json") skillName = pathMatch[1];
1638
+ else if (index.skills.length === 1) skillName = index.skills[0].name;
1639
+ if (!skillName) return null;
1640
+ const skillEntry = index.skills.find((s) => s.name === skillName);
1641
+ if (!skillEntry) return null;
1642
+ return this.fetchSkillByEntry(resolvedBaseUrl, skillEntry, resolvedWellKnownPath);
1643
+ } catch {
1644
+ return null;
1645
+ }
1646
+ }
1647
+ async fetchSkillByEntry(baseUrl, entry, wellKnownPath) {
1648
+ try {
1649
+ const resolvedPath = wellKnownPath ?? this.WELL_KNOWN_PATHS[0];
1650
+ const skillBaseUrl = `${baseUrl.replace(/\/$/, "")}/${resolvedPath}/${entry.name}`;
1651
+ const skillMdUrl = `${skillBaseUrl}/SKILL.md`;
1652
+ const response = await fetch(skillMdUrl);
1653
+ if (!response.ok) return null;
1654
+ const content = await response.text();
1655
+ const { data } = (0, import_gray_matter.default)(content);
1656
+ if (!data.name || !data.description) return null;
1657
+ const files = /* @__PURE__ */ new Map();
1658
+ files.set("SKILL.md", content);
1659
+ const filePromises = entry.files.filter((f) => f.toLowerCase() !== "skill.md").map(async (filePath) => {
1660
+ try {
1661
+ const fileUrl = `${skillBaseUrl}/${filePath}`;
1662
+ const fileResponse = await fetch(fileUrl);
1663
+ if (fileResponse.ok) return {
1664
+ path: filePath,
1665
+ content: await fileResponse.text()
1666
+ };
1667
+ } catch {}
1668
+ return null;
1669
+ });
1670
+ const fileResults = await Promise.all(filePromises);
1671
+ for (const result of fileResults) if (result) files.set(result.path, result.content);
1672
+ return {
1673
+ name: data.name,
1674
+ description: data.description,
1675
+ content,
1676
+ installName: entry.name,
1677
+ sourceUrl: skillMdUrl,
1678
+ metadata: data.metadata,
1679
+ files,
1680
+ indexEntry: entry
1681
+ };
1682
+ } catch {
1683
+ return null;
1684
+ }
1685
+ }
1686
+ async fetchAllSkills(url) {
1687
+ try {
1688
+ const result = await this.fetchIndex(url);
1689
+ if (!result) return [];
1690
+ const { index, resolvedBaseUrl, resolvedWellKnownPath } = result;
1691
+ const skillPromises = index.skills.map((entry) => this.fetchSkillByEntry(resolvedBaseUrl, entry, resolvedWellKnownPath));
1692
+ return (await Promise.all(skillPromises)).filter((s) => s !== null);
1693
+ } catch {
1694
+ return [];
1695
+ }
1696
+ }
1697
+ toRawUrl(url) {
1698
+ try {
1699
+ const parsed = new URL(url);
1700
+ if (url.toLowerCase().endsWith("/skill.md")) return url;
1701
+ const primaryPath = this.WELL_KNOWN_PATHS[0];
1702
+ const pathMatch = parsed.pathname.match(/\/.well-known\/(?:agent-skills|skills)\/([^/]+)\/?$/);
1703
+ if (pathMatch && pathMatch[1]) {
1704
+ const basePath = parsed.pathname.replace(/\/.well-known\/(?:agent-skills|skills)\/.*$/, "");
1705
+ return `${parsed.protocol}//${parsed.host}${basePath}/${primaryPath}/${pathMatch[1]}/SKILL.md`;
1706
+ }
1707
+ const basePath = parsed.pathname.replace(/\/$/, "");
1708
+ return `${parsed.protocol}//${parsed.host}${basePath}/${primaryPath}/${this.INDEX_FILE}`;
1709
+ } catch {
1710
+ return url;
1711
+ }
1712
+ }
1713
+ getSourceIdentifier(url) {
1714
+ try {
1715
+ return new URL(url).hostname.replace(/^www\./, "");
1716
+ } catch {
1717
+ return "unknown";
1718
+ }
1719
+ }
1720
+ async hasSkillsIndex(url) {
1721
+ return await this.fetchIndex(url) !== null;
1722
+ }
1723
+ };
1724
+ const wellKnownProvider = new WellKnownProvider();
1725
+ const AGENTS_DIR$1 = ".agents";
1726
+ const LOCK_FILE$1 = ".skill-lock.json";
1727
+ const CURRENT_VERSION$1 = 3;
1728
+ function getSkillLockPath$1() {
1729
+ const xdgStateHome = process.env.XDG_STATE_HOME;
1730
+ if (xdgStateHome) return join(xdgStateHome, "skills", LOCK_FILE$1);
1731
+ return join(homedir(), AGENTS_DIR$1, LOCK_FILE$1);
1732
+ }
1733
+ async function readSkillLock$1() {
1734
+ const lockPath = getSkillLockPath$1();
1735
+ try {
1736
+ const content = await readFile(lockPath, "utf-8");
1737
+ const parsed = JSON.parse(content);
1738
+ if (typeof parsed.version !== "number" || !parsed.skills) return createEmptyLockFile();
1739
+ if (parsed.version < CURRENT_VERSION$1) return createEmptyLockFile();
1740
+ return parsed;
1741
+ } catch (error) {
1742
+ return createEmptyLockFile();
1743
+ }
1744
+ }
1745
+ async function writeSkillLock(lock) {
1746
+ const lockPath = getSkillLockPath$1();
1747
+ await mkdir(dirname(lockPath), { recursive: true });
1748
+ await writeFile(lockPath, JSON.stringify(lock, null, 2), "utf-8");
1749
+ }
1750
+ function getGitHubToken() {
1751
+ if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN;
1752
+ if (process.env.GH_TOKEN) return process.env.GH_TOKEN;
1753
+ try {
1754
+ const token = execSync("gh auth token", {
1755
+ encoding: "utf-8",
1756
+ stdio: [
1757
+ "pipe",
1758
+ "pipe",
1759
+ "pipe"
1760
+ ]
1761
+ }).trim();
1762
+ if (token) return token;
1763
+ } catch {}
1764
+ return null;
1765
+ }
1766
+ async function fetchSkillFolderHash(ownerRepo, skillPath, token) {
1767
+ let folderPath = skillPath.replace(/\\/g, "/");
1768
+ if (folderPath.endsWith("/SKILL.md")) folderPath = folderPath.slice(0, -9);
1769
+ else if (folderPath.endsWith("SKILL.md")) folderPath = folderPath.slice(0, -8);
1770
+ if (folderPath.endsWith("/")) folderPath = folderPath.slice(0, -1);
1771
+ for (const branch of ["main", "master"]) try {
1772
+ const url = `https://api.github.com/repos/${ownerRepo}/git/trees/${branch}?recursive=1`;
1773
+ const headers = {
1774
+ Accept: "application/vnd.github.v3+json",
1775
+ "User-Agent": "skpm-cli"
1776
+ };
1777
+ if (token) headers["Authorization"] = `Bearer ${token}`;
1778
+ const response = await fetch(url, { headers });
1779
+ if (!response.ok) continue;
1780
+ const data = await response.json();
1781
+ if (!folderPath) return data.sha;
1782
+ const folderEntry = data.tree.find((entry) => entry.type === "tree" && entry.path === folderPath);
1783
+ if (folderEntry) return folderEntry.sha;
1784
+ } catch {
1785
+ continue;
1786
+ }
1787
+ return null;
1788
+ }
1789
+ async function addSkillToLock(skillName, entry) {
1790
+ const lock = await readSkillLock$1();
1791
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1792
+ const existingEntry = lock.skills[skillName];
1793
+ lock.skills[skillName] = {
1794
+ ...entry,
1795
+ installedAt: existingEntry?.installedAt ?? now,
1796
+ updatedAt: now
1797
+ };
1798
+ await writeSkillLock(lock);
1799
+ }
1800
+ async function removeSkillFromLock(skillName) {
1801
+ const lock = await readSkillLock$1();
1802
+ if (!(skillName in lock.skills)) return false;
1803
+ delete lock.skills[skillName];
1804
+ await writeSkillLock(lock);
1805
+ return true;
1806
+ }
1807
+ async function getSkillFromLock(skillName) {
1808
+ return (await readSkillLock$1()).skills[skillName] ?? null;
1809
+ }
1810
+ async function getAllLockedSkills() {
1811
+ return (await readSkillLock$1()).skills;
1812
+ }
1813
+ function createEmptyLockFile() {
1814
+ return {
1815
+ version: CURRENT_VERSION$1,
1816
+ skills: {},
1817
+ dismissed: {}
1818
+ };
1819
+ }
1820
+ async function isPromptDismissed(promptKey) {
1821
+ return (await readSkillLock$1()).dismissed?.[promptKey] === true;
1822
+ }
1823
+ async function dismissPrompt(promptKey) {
1824
+ const lock = await readSkillLock$1();
1825
+ if (!lock.dismissed) lock.dismissed = {};
1826
+ lock.dismissed[promptKey] = true;
1827
+ await writeSkillLock(lock);
1828
+ }
1829
+ async function getLastSelectedAgents() {
1830
+ return (await readSkillLock$1()).lastSelectedAgents;
1831
+ }
1832
+ async function saveSelectedAgents(agents) {
1833
+ const lock = await readSkillLock$1();
1834
+ lock.lastSelectedAgents = agents;
1835
+ await writeSkillLock(lock);
1836
+ }
1837
+ const LOCAL_LOCK_FILE = "skills-lock.json";
1838
+ const CURRENT_VERSION = 1;
1839
+ function getLocalLockPath(cwd) {
1840
+ return join(cwd || process.cwd(), LOCAL_LOCK_FILE);
1841
+ }
1842
+ async function readLocalLock(cwd) {
1843
+ const lockPath = getLocalLockPath(cwd);
1844
+ try {
1845
+ const content = await readFile(lockPath, "utf-8");
1846
+ const parsed = JSON.parse(content);
1847
+ if (typeof parsed.version !== "number" || !parsed.skills) return createEmptyLocalLock();
1848
+ if (parsed.version < CURRENT_VERSION) return createEmptyLocalLock();
1849
+ return parsed;
1850
+ } catch {
1851
+ return createEmptyLocalLock();
1852
+ }
1853
+ }
1854
+ async function writeLocalLock(lock, cwd) {
1855
+ const lockPath = getLocalLockPath(cwd);
1856
+ const sortedSkills = {};
1857
+ for (const key of Object.keys(lock.skills).sort()) sortedSkills[key] = lock.skills[key];
1858
+ const sorted = {
1859
+ version: lock.version,
1860
+ skills: sortedSkills
1861
+ };
1862
+ await writeFile(lockPath, JSON.stringify(sorted, null, 2) + "\n", "utf-8");
1863
+ }
1864
+ async function computeSkillFolderHash(skillDir) {
1865
+ const files = [];
1866
+ await collectFiles(skillDir, skillDir, files);
1867
+ files.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
1868
+ const hash = createHash("sha256");
1869
+ for (const file of files) {
1870
+ hash.update(file.relativePath);
1871
+ hash.update(file.content);
1872
+ }
1873
+ return hash.digest("hex");
1874
+ }
1875
+ async function collectFiles(baseDir, currentDir, results) {
1876
+ const entries = await readdir(currentDir, { withFileTypes: true });
1877
+ await Promise.all(entries.map(async (entry) => {
1878
+ const fullPath = join(currentDir, entry.name);
1879
+ if (entry.isDirectory()) {
1880
+ if (entry.name === ".git" || entry.name === "node_modules") return;
1881
+ await collectFiles(baseDir, fullPath, results);
1882
+ } else if (entry.isFile()) {
1883
+ const content = await readFile(fullPath);
1884
+ const relativePath = relative(baseDir, fullPath).split("\\").join("/");
1885
+ results.push({
1886
+ relativePath,
1887
+ content
1888
+ });
1889
+ }
1890
+ }));
1891
+ }
1892
+ async function addSkillToLocalLock(skillName, entry, cwd) {
1893
+ const lock = await readLocalLock(cwd);
1894
+ lock.skills[skillName] = entry;
1895
+ await writeLocalLock(lock, cwd);
1896
+ }
1897
+ function createEmptyLocalLock() {
1898
+ return {
1899
+ version: CURRENT_VERSION,
1900
+ skills: {}
1901
+ };
1902
+ }
1903
+ var version$1 = "1.4.6";
1904
+ const isCancelled$1 = (value) => typeof value === "symbol";
1905
+ async function isSourcePrivate(source) {
1906
+ const ownerRepo = parseOwnerRepo(source);
1907
+ if (!ownerRepo) return false;
1908
+ return isRepoPrivate(ownerRepo.owner, ownerRepo.repo);
1909
+ }
1910
+ function initTelemetry(version) {
1911
+ setVersion(version);
1912
+ }
1913
+ function riskLabel(risk) {
1914
+ switch (risk) {
1915
+ case "critical": return import_picocolors.default.red(import_picocolors.default.bold("Critical Risk"));
1916
+ case "high": return import_picocolors.default.red("High Risk");
1917
+ case "medium": return import_picocolors.default.yellow("Med Risk");
1918
+ case "low": return import_picocolors.default.green("Low Risk");
1919
+ case "safe": return import_picocolors.default.green("Safe");
1920
+ default: return import_picocolors.default.dim("--");
1921
+ }
1922
+ }
1923
+ function socketLabel(audit) {
1924
+ if (!audit) return import_picocolors.default.dim("--");
1925
+ const count = audit.alerts ?? 0;
1926
+ return count > 0 ? import_picocolors.default.red(`${count} alert${count !== 1 ? "s" : ""}`) : import_picocolors.default.green("0 alerts");
1927
+ }
1928
+ function padEnd(str, width) {
1929
+ const visible = str.replace(/\x1b\[[0-9;]*m/g, "");
1930
+ const pad = Math.max(0, width - visible.length);
1931
+ return str + " ".repeat(pad);
1932
+ }
1933
+ function buildSecurityLines(auditData, skills, source) {
1934
+ if (!auditData) return [];
1935
+ if (!skills.some((s) => {
1936
+ const data = auditData[s.slug];
1937
+ return data && Object.keys(data).length > 0;
1938
+ })) return [];
1939
+ const nameWidth = Math.min(Math.max(...skills.map((s) => s.displayName.length)), 36);
1940
+ const lines = [];
1941
+ const header = padEnd("", nameWidth + 2) + padEnd(import_picocolors.default.dim("Gen"), 18) + padEnd(import_picocolors.default.dim("Socket"), 18) + import_picocolors.default.dim("Snyk");
1942
+ lines.push(header);
1943
+ for (const skill of skills) {
1944
+ const data = auditData[skill.slug];
1945
+ const name = skill.displayName.length > nameWidth ? skill.displayName.slice(0, nameWidth - 1) + "…" : skill.displayName;
1946
+ const ath = data?.ath ? riskLabel(data.ath.risk) : import_picocolors.default.dim("--");
1947
+ const socket = data?.socket ? socketLabel(data.socket) : import_picocolors.default.dim("--");
1948
+ const snyk = data?.snyk ? riskLabel(data.snyk.risk) : import_picocolors.default.dim("--");
1949
+ lines.push(padEnd(import_picocolors.default.cyan(name), nameWidth + 2) + padEnd(ath, 18) + padEnd(socket, 18) + snyk);
1950
+ }
1951
+ lines.push("");
1952
+ lines.push(`${import_picocolors.default.dim("Details:")} ${import_picocolors.default.dim(`https://skpm.sh/${source}`)}`);
1953
+ return lines;
1954
+ }
1955
+ function shortenPath$2(fullPath, cwd) {
1956
+ const home = homedir();
1957
+ if (fullPath === home || fullPath.startsWith(home + sep)) return "~" + fullPath.slice(home.length);
1958
+ if (fullPath === cwd || fullPath.startsWith(cwd + sep)) return "." + fullPath.slice(cwd.length);
1959
+ return fullPath;
1960
+ }
1961
+ function formatList$1(items, maxShow = 5) {
1962
+ if (items.length <= maxShow) return items.join(", ");
1963
+ const shown = items.slice(0, maxShow);
1964
+ const remaining = items.length - maxShow;
1965
+ return `${shown.join(", ")} +${remaining} more`;
1966
+ }
1967
+ function splitAgentsByType(agentTypes) {
1968
+ const universal = [];
1969
+ const symlinked = [];
1970
+ for (const a of agentTypes) if (isUniversalAgent(a)) universal.push(agents[a].displayName);
1971
+ else symlinked.push(agents[a].displayName);
1972
+ return {
1973
+ universal,
1974
+ symlinked
1975
+ };
1976
+ }
1977
+ function buildAgentSummaryLines(targetAgents, installMode) {
1978
+ const lines = [];
1979
+ const { universal, symlinked } = splitAgentsByType(targetAgents);
1980
+ if (installMode === "symlink") {
1981
+ if (universal.length > 0) lines.push(` ${import_picocolors.default.green("universal:")} ${formatList$1(universal)}`);
1982
+ if (symlinked.length > 0) lines.push(` ${import_picocolors.default.dim("symlink →")} ${formatList$1(symlinked)}`);
1983
+ } else {
1984
+ const allNames = targetAgents.map((a) => agents[a].displayName);
1985
+ lines.push(` ${import_picocolors.default.dim("copy →")} ${formatList$1(allNames)}`);
1986
+ }
1987
+ return lines;
1988
+ }
1989
+ function ensureUniversalAgents(targetAgents) {
1990
+ const universalAgents = getUniversalAgents();
1991
+ const result = [...targetAgents];
1992
+ for (const ua of universalAgents) if (!result.includes(ua)) result.push(ua);
1993
+ return result;
1994
+ }
1995
+ function buildResultLines(results, targetAgents) {
1996
+ const lines = [];
1997
+ const { universal, symlinked: symlinkAgents } = splitAgentsByType(targetAgents);
1998
+ const successfulSymlinks = results.filter((r) => !r.symlinkFailed && !universal.includes(r.agent)).map((r) => r.agent);
1999
+ const failedSymlinks = results.filter((r) => r.symlinkFailed).map((r) => r.agent);
2000
+ if (universal.length > 0) lines.push(` ${import_picocolors.default.green("universal:")} ${formatList$1(universal)}`);
2001
+ if (successfulSymlinks.length > 0) lines.push(` ${import_picocolors.default.dim("symlinked:")} ${formatList$1(successfulSymlinks)}`);
2002
+ if (failedSymlinks.length > 0) lines.push(` ${import_picocolors.default.yellow("copied:")} ${formatList$1(failedSymlinks)}`);
2003
+ return lines;
2004
+ }
2005
+ function multiselect(opts) {
2006
+ return fe({
2007
+ ...opts,
2008
+ options: opts.options,
2009
+ message: `${opts.message} ${import_picocolors.default.dim("(space to toggle)")}`
2010
+ });
2011
+ }
2012
+ async function promptForAgents(message, choices) {
2013
+ let lastSelected;
2014
+ try {
2015
+ lastSelected = await getLastSelectedAgents();
2016
+ } catch {}
2017
+ const validAgents = choices.map((c) => c.value);
2018
+ const defaultValues = [
2019
+ "claude-code",
2020
+ "opencode",
2021
+ "codex"
2022
+ ].filter((a) => validAgents.includes(a));
2023
+ let initialValues = [];
2024
+ if (lastSelected && lastSelected.length > 0) initialValues = lastSelected.filter((a) => validAgents.includes(a));
2025
+ if (initialValues.length === 0) initialValues = defaultValues;
2026
+ const selected = await searchMultiselect({
2027
+ message,
2028
+ items: choices,
2029
+ initialSelected: initialValues,
2030
+ required: true
2031
+ });
2032
+ if (!isCancelled$1(selected)) try {
2033
+ await saveSelectedAgents(selected);
2034
+ } catch {}
2035
+ return selected;
2036
+ }
2037
+ async function selectAgentsInteractive(options) {
2038
+ const supportsGlobalFilter = (a) => !options.global || agents[a].globalSkillsDir;
2039
+ const universalAgents = getUniversalAgents().filter(supportsGlobalFilter);
2040
+ const otherAgents = getNonUniversalAgents().filter(supportsGlobalFilter);
2041
+ const universalSection = {
2042
+ title: "Universal (.agents/skills)",
2043
+ items: universalAgents.map((a) => ({
2044
+ value: a,
2045
+ label: agents[a].displayName
2046
+ }))
2047
+ };
2048
+ const otherChoices = otherAgents.map((a) => ({
2049
+ value: a,
2050
+ label: agents[a].displayName,
2051
+ hint: options.global ? agents[a].globalSkillsDir : agents[a].skillsDir
2052
+ }));
2053
+ let lastSelected;
2054
+ try {
2055
+ lastSelected = await getLastSelectedAgents();
2056
+ } catch {}
2057
+ const selected = await searchMultiselect({
2058
+ message: "Which agents do you want to install to?",
2059
+ items: otherChoices,
2060
+ initialSelected: lastSelected ? lastSelected.filter((a) => otherAgents.includes(a) && !universalAgents.includes(a)) : [],
2061
+ lockedSection: universalSection
2062
+ });
2063
+ if (!isCancelled$1(selected)) try {
2064
+ await saveSelectedAgents(selected);
2065
+ } catch {}
2066
+ return selected;
2067
+ }
2068
+ setVersion(version$1);
2069
+ async function handleWellKnownSkills(source, url, options, spinner) {
2070
+ spinner.start("Discovering skills from well-known endpoint...");
2071
+ const skills = await wellKnownProvider.fetchAllSkills(url);
2072
+ if (skills.length === 0) {
2073
+ spinner.stop(import_picocolors.default.red("No skills found"));
2074
+ Se(import_picocolors.default.red("No skills found at this URL. Make sure the server has a /.well-known/agent-skills/index.json or /.well-known/skills/index.json file."));
2075
+ process.exit(1);
2076
+ }
2077
+ spinner.stop(`Found ${import_picocolors.default.green(skills.length)} skill${skills.length > 1 ? "s" : ""}`);
2078
+ for (const skill of skills) {
2079
+ M.info(`Skill: ${import_picocolors.default.cyan(skill.installName)}`);
2080
+ M.message(import_picocolors.default.dim(skill.description));
2081
+ if (skill.files.size > 1) M.message(import_picocolors.default.dim(` Files: ${Array.from(skill.files.keys()).join(", ")}`));
2082
+ }
2083
+ if (options.list) {
2084
+ console.log();
2085
+ M.step(import_picocolors.default.bold("Available Skills"));
2086
+ for (const skill of skills) {
2087
+ M.message(` ${import_picocolors.default.cyan(skill.installName)}`);
2088
+ M.message(` ${import_picocolors.default.dim(skill.description)}`);
2089
+ if (skill.files.size > 1) M.message(` ${import_picocolors.default.dim(`Files: ${skill.files.size}`)}`);
2090
+ }
2091
+ console.log();
2092
+ Se("Run without --list to install");
2093
+ process.exit(0);
2094
+ }
2095
+ let selectedSkills;
2096
+ if (options.skill?.includes("*")) {
2097
+ selectedSkills = skills;
2098
+ M.info(`Installing all ${skills.length} skills`);
2099
+ } else if (options.skill && options.skill.length > 0) {
2100
+ selectedSkills = skills.filter((s) => options.skill.some((name) => s.installName.toLowerCase() === name.toLowerCase() || s.name.toLowerCase() === name.toLowerCase()));
2101
+ if (selectedSkills.length === 0) {
2102
+ M.error(`No matching skills found for: ${options.skill.join(", ")}`);
2103
+ M.info("Available skills:");
2104
+ for (const s of skills) M.message(` - ${s.installName}`);
2105
+ process.exit(1);
2106
+ }
2107
+ } else if (skills.length === 1) {
2108
+ selectedSkills = skills;
2109
+ const firstSkill = skills[0];
2110
+ M.info(`Skill: ${import_picocolors.default.cyan(firstSkill.installName)}`);
2111
+ } else if (options.yes) {
2112
+ selectedSkills = skills;
2113
+ M.info(`Installing all ${skills.length} skills`);
2114
+ } else {
2115
+ const selected = await multiselect({
2116
+ message: "Select skills to install",
2117
+ options: skills.map((s) => ({
2118
+ value: s,
2119
+ label: s.installName,
2120
+ hint: s.description.length > 60 ? s.description.slice(0, 57) + "..." : s.description
2121
+ })),
2122
+ required: true
2123
+ });
2124
+ if (pD(selected)) {
2125
+ xe("Installation cancelled");
2126
+ process.exit(0);
2127
+ }
2128
+ selectedSkills = selected;
2129
+ }
2130
+ let targetAgents;
2131
+ const validAgents = Object.keys(agents);
2132
+ if (options.agent?.includes("*")) {
2133
+ targetAgents = validAgents;
2134
+ M.info(`Installing to all ${targetAgents.length} agents`);
2135
+ } else if (options.agent && options.agent.length > 0) {
2136
+ const invalidAgents = options.agent.filter((a) => !validAgents.includes(a));
2137
+ if (invalidAgents.length > 0) {
2138
+ M.error(`Invalid agents: ${invalidAgents.join(", ")}`);
2139
+ M.info(`Valid agents: ${validAgents.join(", ")}`);
2140
+ process.exit(1);
2141
+ }
2142
+ targetAgents = options.agent;
2143
+ } else {
2144
+ spinner.start("Loading agents...");
2145
+ const installedAgents = await detectInstalledAgents();
2146
+ const totalAgents = Object.keys(agents).length;
2147
+ spinner.stop(`${totalAgents} agents`);
2148
+ if (installedAgents.length === 0) if (options.yes) {
2149
+ targetAgents = validAgents;
2150
+ M.info("Installing to all agents");
2151
+ } else {
2152
+ M.info("Select agents to install skills to");
2153
+ const selected = await promptForAgents("Which agents do you want to install to?", Object.entries(agents).map(([key, config]) => ({
2154
+ value: key,
2155
+ label: config.displayName
2156
+ })));
2157
+ if (pD(selected)) {
2158
+ xe("Installation cancelled");
2159
+ process.exit(0);
2160
+ }
2161
+ targetAgents = selected;
2162
+ }
2163
+ else if (installedAgents.length === 1 || options.yes) {
2164
+ targetAgents = ensureUniversalAgents(installedAgents);
2165
+ if (installedAgents.length === 1) {
2166
+ const firstAgent = installedAgents[0];
2167
+ M.info(`Installing to: ${import_picocolors.default.cyan(agents[firstAgent].displayName)}`);
2168
+ } else M.info(`Installing to: ${installedAgents.map((a) => import_picocolors.default.cyan(agents[a].displayName)).join(", ")}`);
2169
+ } else {
2170
+ const selected = await selectAgentsInteractive({ global: options.global });
2171
+ if (pD(selected)) {
2172
+ xe("Installation cancelled");
2173
+ process.exit(0);
2174
+ }
2175
+ targetAgents = selected;
2176
+ }
2177
+ }
2178
+ let installGlobally = options.global ?? false;
2179
+ const supportsGlobal = targetAgents.some((a) => agents[a].globalSkillsDir !== void 0);
2180
+ if (options.global === void 0 && !options.yes && supportsGlobal) {
2181
+ const scope = await ve({
2182
+ message: "Installation scope",
2183
+ options: [{
2184
+ value: false,
2185
+ label: "Project",
2186
+ hint: "Install in current directory (committed with your project)"
2187
+ }, {
2188
+ value: true,
2189
+ label: "Global",
2190
+ hint: "Install in home directory (available across all projects)"
2191
+ }]
2192
+ });
2193
+ if (pD(scope)) {
2194
+ xe("Installation cancelled");
2195
+ process.exit(0);
2196
+ }
2197
+ installGlobally = scope;
2198
+ }
2199
+ let installMode = options.copy ? "copy" : "symlink";
2200
+ const uniqueDirs = new Set(targetAgents.map((a) => agents[a].skillsDir));
2201
+ if (!options.copy && !options.yes && uniqueDirs.size > 1) {
2202
+ const modeChoice = await ve({
2203
+ message: "Installation method",
2204
+ options: [{
2205
+ value: "symlink",
2206
+ label: "Symlink (Recommended)",
2207
+ hint: "Single source of truth, easy updates"
2208
+ }, {
2209
+ value: "copy",
2210
+ label: "Copy to all agents",
2211
+ hint: "Independent copies for each agent"
2212
+ }]
2213
+ });
2214
+ if (pD(modeChoice)) {
2215
+ xe("Installation cancelled");
2216
+ process.exit(0);
2217
+ }
2218
+ installMode = modeChoice;
2219
+ } else if (uniqueDirs.size <= 1) installMode = "copy";
2220
+ const cwd = process.cwd();
2221
+ const summaryLines = [];
2222
+ targetAgents.map((a) => agents[a].displayName);
2223
+ const overwriteChecks = await Promise.all(selectedSkills.flatMap((skill) => targetAgents.map(async (agent) => ({
2224
+ skillName: skill.installName,
2225
+ agent,
2226
+ installed: await isSkillInstalled(skill.installName, agent, { global: installGlobally })
2227
+ }))));
2228
+ const overwriteStatus = /* @__PURE__ */ new Map();
2229
+ for (const { skillName, agent, installed } of overwriteChecks) {
2230
+ if (!overwriteStatus.has(skillName)) overwriteStatus.set(skillName, /* @__PURE__ */ new Map());
2231
+ overwriteStatus.get(skillName).set(agent, installed);
2232
+ }
2233
+ for (const skill of selectedSkills) {
2234
+ if (summaryLines.length > 0) summaryLines.push("");
2235
+ const shortCanonical = shortenPath$2(getCanonicalPath(skill.installName, { global: installGlobally }), cwd);
2236
+ summaryLines.push(`${import_picocolors.default.cyan(shortCanonical)}`);
2237
+ summaryLines.push(...buildAgentSummaryLines(targetAgents, installMode));
2238
+ if (skill.files.size > 1) summaryLines.push(` ${import_picocolors.default.dim("files:")} ${skill.files.size}`);
2239
+ const skillOverwrites = overwriteStatus.get(skill.installName);
2240
+ const overwriteAgents = targetAgents.filter((a) => skillOverwrites?.get(a)).map((a) => agents[a].displayName);
2241
+ if (overwriteAgents.length > 0) summaryLines.push(` ${import_picocolors.default.yellow("overwrites:")} ${formatList$1(overwriteAgents)}`);
2242
+ }
2243
+ console.log();
2244
+ Me(summaryLines.join("\n"), "Installation Summary");
2245
+ if (!options.yes) {
2246
+ const confirmed = await ye({ message: "Proceed with installation?" });
2247
+ if (pD(confirmed) || !confirmed) {
2248
+ xe("Installation cancelled");
2249
+ process.exit(0);
2250
+ }
2251
+ }
2252
+ spinner.start("Installing skills...");
2253
+ const results = [];
2254
+ for (const skill of selectedSkills) for (const agent of targetAgents) {
2255
+ const result = await installWellKnownSkillForAgent(skill, agent, {
2256
+ global: installGlobally,
2257
+ mode: installMode
2258
+ });
2259
+ results.push({
2260
+ skill: skill.installName,
2261
+ agent: agents[agent].displayName,
2262
+ ...result
2263
+ });
2264
+ }
2265
+ spinner.stop("Installation complete");
2266
+ console.log();
2267
+ const successful = results.filter((r) => r.success);
2268
+ const failed = results.filter((r) => !r.success);
2269
+ const sourceIdentifier = wellKnownProvider.getSourceIdentifier(url);
2270
+ const skillFiles = {};
2271
+ for (const skill of selectedSkills) skillFiles[skill.installName] = skill.sourceUrl;
2272
+ if (await isSourcePrivate(sourceIdentifier) !== true) track({
2273
+ event: "install",
2274
+ source: sourceIdentifier,
2275
+ skills: selectedSkills.map((s) => s.installName).join(","),
2276
+ agents: targetAgents.join(","),
2277
+ ...installGlobally && { global: "1" },
2278
+ skillFiles: JSON.stringify(skillFiles),
2279
+ sourceType: "well-known"
2280
+ });
2281
+ if (successful.length > 0 && installGlobally) {
2282
+ const successfulSkillNames = new Set(successful.map((r) => r.skill));
2283
+ for (const skill of selectedSkills) if (successfulSkillNames.has(skill.installName)) try {
2284
+ await addSkillToLock(skill.installName, {
2285
+ source: sourceIdentifier,
2286
+ sourceType: "well-known",
2287
+ sourceUrl: skill.sourceUrl,
2288
+ skillFolderHash: ""
2289
+ });
2290
+ } catch {}
2291
+ }
2292
+ if (successful.length > 0 && !installGlobally) {
2293
+ const successfulSkillNames = new Set(successful.map((r) => r.skill));
2294
+ for (const skill of selectedSkills) if (successfulSkillNames.has(skill.installName)) try {
2295
+ const matchingResult = successful.find((r) => r.skill === skill.installName);
2296
+ const installDir = matchingResult?.canonicalPath || matchingResult?.path;
2297
+ if (installDir) {
2298
+ const computedHash = await computeSkillFolderHash(installDir);
2299
+ await addSkillToLocalLock(skill.installName, {
2300
+ source: sourceIdentifier,
2301
+ sourceType: "well-known",
2302
+ computedHash
2303
+ }, cwd);
2304
+ }
2305
+ } catch {}
2306
+ }
2307
+ if (successful.length > 0) {
2308
+ const bySkill = /* @__PURE__ */ new Map();
2309
+ for (const r of successful) {
2310
+ const skillResults = bySkill.get(r.skill) || [];
2311
+ skillResults.push(r);
2312
+ bySkill.set(r.skill, skillResults);
2313
+ }
2314
+ const skillCount = bySkill.size;
2315
+ const symlinkFailures = successful.filter((r) => r.mode === "symlink" && r.symlinkFailed);
2316
+ const copiedAgents = symlinkFailures.map((r) => r.agent);
2317
+ const resultLines = [];
2318
+ for (const [skillName, skillResults] of bySkill) {
2319
+ const firstResult = skillResults[0];
2320
+ if (firstResult.mode === "copy") {
2321
+ resultLines.push(`${import_picocolors.default.green("✓")} ${skillName} ${import_picocolors.default.dim("(copied)")}`);
2322
+ for (const r of skillResults) {
2323
+ const shortPath = shortenPath$2(r.path, cwd);
2324
+ resultLines.push(` ${import_picocolors.default.dim("→")} ${shortPath}`);
2325
+ }
2326
+ } else {
2327
+ if (firstResult.canonicalPath) {
2328
+ const shortPath = shortenPath$2(firstResult.canonicalPath, cwd);
2329
+ resultLines.push(`${import_picocolors.default.green("✓")} ${shortPath}`);
2330
+ } else resultLines.push(`${import_picocolors.default.green("✓")} ${skillName}`);
2331
+ resultLines.push(...buildResultLines(skillResults, targetAgents));
2332
+ }
2333
+ }
2334
+ const title = import_picocolors.default.green(`Installed ${skillCount} skill${skillCount !== 1 ? "s" : ""}`);
2335
+ Me(resultLines.join("\n"), title);
2336
+ if (symlinkFailures.length > 0) {
2337
+ M.warn(import_picocolors.default.yellow(`Symlinks failed for: ${formatList$1(copiedAgents)}`));
2338
+ M.message(import_picocolors.default.dim(" Files were copied instead. On Windows, enable Developer Mode for symlink support."));
2339
+ }
2340
+ }
2341
+ if (failed.length > 0) {
2342
+ console.log();
2343
+ M.error(import_picocolors.default.red(`Failed to install ${failed.length}`));
2344
+ for (const r of failed) M.message(` ${import_picocolors.default.red("✗")} ${r.skill} → ${r.agent}: ${import_picocolors.default.dim(r.error)}`);
2345
+ }
2346
+ console.log();
2347
+ Se(import_picocolors.default.green("Done!") + import_picocolors.default.dim(" Review skills before use; they run with full agent permissions."));
2348
+ await promptForFindSkills(options, targetAgents);
2349
+ }
2350
+ async function runAdd(args, options = {}) {
2351
+ const source = args[0];
2352
+ let installTipShown = false;
2353
+ const showInstallTip = () => {
2354
+ if (installTipShown) return;
2355
+ M.message(import_picocolors.default.dim("Tip: use the --yes (-y) and --global (-g) flags to install without prompts."));
2356
+ installTipShown = true;
2357
+ };
2358
+ if (!source) {
2359
+ console.log();
2360
+ console.log(import_picocolors.default.bgRed(import_picocolors.default.white(import_picocolors.default.bold(" ERROR "))) + " " + import_picocolors.default.red("Missing required argument: source"));
2361
+ console.log();
2362
+ console.log(import_picocolors.default.dim(" Usage:"));
2363
+ console.log(` ${import_picocolors.default.cyan("npx skpm-cli add")} ${import_picocolors.default.yellow("<source>")} ${import_picocolors.default.dim("[options]")}`);
2364
+ console.log();
2365
+ console.log(import_picocolors.default.dim(" Example:"));
2366
+ console.log(` ${import_picocolors.default.cyan("npx skpm-cli add")} ${import_picocolors.default.yellow("vercel-labs/agent-skills")}`);
2367
+ console.log();
2368
+ process.exit(1);
2369
+ }
2370
+ if (options.all) {
2371
+ options.skill = ["*"];
2372
+ options.agent = ["*"];
2373
+ options.yes = true;
2374
+ }
2375
+ console.log();
2376
+ Ie(import_picocolors.default.bgCyan(import_picocolors.default.black(" skills ")));
2377
+ if (!process.stdin.isTTY) showInstallTip();
2378
+ let tempDir = null;
2379
+ try {
2380
+ const spinner = Y();
2381
+ spinner.start("Parsing source...");
2382
+ const parsed = parseSource(source);
2383
+ spinner.stop(`Source: ${parsed.type === "local" ? parsed.localPath : parsed.url}${parsed.ref ? ` @ ${import_picocolors.default.yellow(parsed.ref)}` : ""}${parsed.subpath ? ` (${parsed.subpath})` : ""}${parsed.skillFilter ? ` ${import_picocolors.default.dim("@")}${import_picocolors.default.cyan(parsed.skillFilter)}` : ""}`);
2384
+ if (parsed.type === "well-known") {
2385
+ await handleWellKnownSkills(source, parsed.url, options, spinner);
2386
+ return;
2387
+ }
2388
+ let skillsDir;
2389
+ if (parsed.type === "local") {
2390
+ spinner.start("Validating local path...");
2391
+ if (!existsSync(parsed.localPath)) {
2392
+ spinner.stop(import_picocolors.default.red("Path not found"));
2393
+ Se(import_picocolors.default.red(`Local path does not exist: ${parsed.localPath}`));
2394
+ process.exit(1);
2395
+ }
2396
+ skillsDir = parsed.localPath;
2397
+ spinner.stop("Local path validated");
2398
+ } else {
2399
+ spinner.start("Cloning repository...");
2400
+ tempDir = await cloneRepo(parsed.url, parsed.ref);
2401
+ skillsDir = tempDir;
2402
+ spinner.stop("Repository cloned");
2403
+ }
2404
+ if (parsed.skillFilter) {
2405
+ options.skill = options.skill || [];
2406
+ if (!options.skill.includes(parsed.skillFilter)) options.skill.push(parsed.skillFilter);
2407
+ }
2408
+ const includeInternal = !!(options.skill && options.skill.length > 0);
2409
+ spinner.start("Discovering skills...");
2410
+ const skills = await discoverSkills(skillsDir, parsed.subpath, {
2411
+ includeInternal,
2412
+ fullDepth: options.fullDepth
2413
+ });
2414
+ if (skills.length === 0) {
2415
+ spinner.stop(import_picocolors.default.red("No skills found"));
2416
+ Se(import_picocolors.default.red("No valid skills found. Skills require a SKILL.md with name and description."));
2417
+ await cleanup(tempDir);
2418
+ process.exit(1);
2419
+ }
2420
+ spinner.stop(`Found ${import_picocolors.default.green(skills.length)} skill${skills.length > 1 ? "s" : ""}`);
2421
+ if (options.list) {
2422
+ console.log();
2423
+ M.step(import_picocolors.default.bold("Available Skills"));
2424
+ const groupedSkills = {};
2425
+ const ungroupedSkills = [];
2426
+ for (const skill of skills) if (skill.pluginName) {
2427
+ const group = skill.pluginName;
2428
+ if (!groupedSkills[group]) groupedSkills[group] = [];
2429
+ groupedSkills[group].push(skill);
2430
+ } else ungroupedSkills.push(skill);
2431
+ const sortedGroups = Object.keys(groupedSkills).sort();
2432
+ for (const group of sortedGroups) {
2433
+ const title = group.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
2434
+ console.log(import_picocolors.default.bold(title));
2435
+ for (const skill of groupedSkills[group]) {
2436
+ M.message(` ${import_picocolors.default.cyan(getSkillDisplayName(skill))}`);
2437
+ M.message(` ${import_picocolors.default.dim(skill.description)}`);
2438
+ }
2439
+ console.log();
2440
+ }
2441
+ if (ungroupedSkills.length > 0) {
2442
+ if (sortedGroups.length > 0) console.log(import_picocolors.default.bold("General"));
2443
+ for (const skill of ungroupedSkills) {
2444
+ M.message(` ${import_picocolors.default.cyan(getSkillDisplayName(skill))}`);
2445
+ M.message(` ${import_picocolors.default.dim(skill.description)}`);
2446
+ }
2447
+ }
2448
+ console.log();
2449
+ Se("Use --skill <name> to install specific skills");
2450
+ await cleanup(tempDir);
2451
+ process.exit(0);
2452
+ }
2453
+ let selectedSkills;
2454
+ if (options.skill?.includes("*")) {
2455
+ selectedSkills = skills;
2456
+ M.info(`Installing all ${skills.length} skills`);
2457
+ } else if (options.skill && options.skill.length > 0) {
2458
+ selectedSkills = filterSkills(skills, options.skill);
2459
+ if (selectedSkills.length === 0) {
2460
+ M.error(`No matching skills found for: ${options.skill.join(", ")}`);
2461
+ M.info("Available skills:");
2462
+ for (const s of skills) M.message(` - ${getSkillDisplayName(s)}`);
2463
+ await cleanup(tempDir);
2464
+ process.exit(1);
2465
+ }
2466
+ M.info(`Selected ${selectedSkills.length} skill${selectedSkills.length !== 1 ? "s" : ""}: ${selectedSkills.map((s) => import_picocolors.default.cyan(getSkillDisplayName(s))).join(", ")}`);
2467
+ } else if (skills.length === 1) {
2468
+ selectedSkills = skills;
2469
+ const firstSkill = skills[0];
2470
+ M.info(`Skill: ${import_picocolors.default.cyan(getSkillDisplayName(firstSkill))}`);
2471
+ M.message(import_picocolors.default.dim(firstSkill.description));
2472
+ } else if (options.yes) {
2473
+ selectedSkills = skills;
2474
+ M.info(`Installing all ${skills.length} skills`);
2475
+ } else {
2476
+ const sortedSkills = [...skills].sort((a, b) => {
2477
+ if (a.pluginName && !b.pluginName) return -1;
2478
+ if (!a.pluginName && b.pluginName) return 1;
2479
+ if (a.pluginName && b.pluginName && a.pluginName !== b.pluginName) return a.pluginName.localeCompare(b.pluginName);
2480
+ return getSkillDisplayName(a).localeCompare(getSkillDisplayName(b));
2481
+ });
2482
+ const hasGroups = sortedSkills.some((s) => s.pluginName);
2483
+ let selected;
2484
+ if (hasGroups) {
2485
+ const kebabToTitle = (s) => s.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
2486
+ const grouped = {};
2487
+ for (const s of sortedSkills) {
2488
+ const groupName = s.pluginName ? kebabToTitle(s.pluginName) : "Other";
2489
+ if (!grouped[groupName]) grouped[groupName] = [];
2490
+ grouped[groupName].push({
2491
+ value: s,
2492
+ label: getSkillDisplayName(s),
2493
+ hint: s.description.length > 60 ? s.description.slice(0, 57) + "..." : s.description
2494
+ });
2495
+ }
2496
+ selected = await be({
2497
+ message: `Select skills to install ${import_picocolors.default.dim("(space to toggle)")}`,
2498
+ options: grouped,
2499
+ required: true
2500
+ });
2501
+ } else selected = await multiselect({
2502
+ message: "Select skills to install",
2503
+ options: sortedSkills.map((s) => ({
2504
+ value: s,
2505
+ label: getSkillDisplayName(s),
2506
+ hint: s.description.length > 60 ? s.description.slice(0, 57) + "..." : s.description
2507
+ })),
2508
+ required: true
2509
+ });
2510
+ if (pD(selected)) {
2511
+ xe("Installation cancelled");
2512
+ await cleanup(tempDir);
2513
+ process.exit(0);
2514
+ }
2515
+ selectedSkills = selected;
2516
+ }
2517
+ const ownerRepoForAudit = getOwnerRepo(parsed);
2518
+ const auditPromise = ownerRepoForAudit ? fetchAuditData(ownerRepoForAudit, selectedSkills.map((s) => getSkillDisplayName(s))) : Promise.resolve(null);
2519
+ let targetAgents;
2520
+ const validAgents = Object.keys(agents);
2521
+ if (options.agent?.includes("*")) {
2522
+ targetAgents = validAgents;
2523
+ M.info(`Installing to all ${targetAgents.length} agents`);
2524
+ } else if (options.agent && options.agent.length > 0) {
2525
+ const invalidAgents = options.agent.filter((a) => !validAgents.includes(a));
2526
+ if (invalidAgents.length > 0) {
2527
+ M.error(`Invalid agents: ${invalidAgents.join(", ")}`);
2528
+ M.info(`Valid agents: ${validAgents.join(", ")}`);
2529
+ await cleanup(tempDir);
2530
+ process.exit(1);
2531
+ }
2532
+ targetAgents = options.agent;
2533
+ } else {
2534
+ spinner.start("Loading agents...");
2535
+ const installedAgents = await detectInstalledAgents();
2536
+ const totalAgents = Object.keys(agents).length;
2537
+ spinner.stop(`${totalAgents} agents`);
2538
+ if (installedAgents.length === 0) if (options.yes) {
2539
+ targetAgents = validAgents;
2540
+ M.info("Installing to all agents");
2541
+ } else {
2542
+ M.info("Select agents to install skills to");
2543
+ const selected = await promptForAgents("Which agents do you want to install to?", Object.entries(agents).map(([key, config]) => ({
2544
+ value: key,
2545
+ label: config.displayName
2546
+ })));
2547
+ if (pD(selected)) {
2548
+ xe("Installation cancelled");
2549
+ await cleanup(tempDir);
2550
+ process.exit(0);
2551
+ }
2552
+ targetAgents = selected;
2553
+ }
2554
+ else if (installedAgents.length === 1 || options.yes) {
2555
+ targetAgents = ensureUniversalAgents(installedAgents);
2556
+ if (installedAgents.length === 1) {
2557
+ const firstAgent = installedAgents[0];
2558
+ M.info(`Installing to: ${import_picocolors.default.cyan(agents[firstAgent].displayName)}`);
2559
+ } else M.info(`Installing to: ${installedAgents.map((a) => import_picocolors.default.cyan(agents[a].displayName)).join(", ")}`);
2560
+ } else {
2561
+ const selected = await selectAgentsInteractive({ global: options.global });
2562
+ if (pD(selected)) {
2563
+ xe("Installation cancelled");
2564
+ await cleanup(tempDir);
2565
+ process.exit(0);
2566
+ }
2567
+ targetAgents = selected;
2568
+ }
2569
+ }
2570
+ let installGlobally = options.global ?? false;
2571
+ const supportsGlobal = targetAgents.some((a) => agents[a].globalSkillsDir !== void 0);
2572
+ if (options.global === void 0 && !options.yes && supportsGlobal) {
2573
+ const scope = await ve({
2574
+ message: "Installation scope",
2575
+ options: [{
2576
+ value: false,
2577
+ label: "Project",
2578
+ hint: "Install in current directory (committed with your project)"
2579
+ }, {
2580
+ value: true,
2581
+ label: "Global",
2582
+ hint: "Install in home directory (available across all projects)"
2583
+ }]
2584
+ });
2585
+ if (pD(scope)) {
2586
+ xe("Installation cancelled");
2587
+ await cleanup(tempDir);
2588
+ process.exit(0);
2589
+ }
2590
+ installGlobally = scope;
2591
+ }
2592
+ let installMode = options.copy ? "copy" : "symlink";
2593
+ const uniqueDirs = new Set(targetAgents.map((a) => agents[a].skillsDir));
2594
+ if (!options.copy && !options.yes && uniqueDirs.size > 1) {
2595
+ const modeChoice = await ve({
2596
+ message: "Installation method",
2597
+ options: [{
2598
+ value: "symlink",
2599
+ label: "Symlink (Recommended)",
2600
+ hint: "Single source of truth, easy updates"
2601
+ }, {
2602
+ value: "copy",
2603
+ label: "Copy to all agents",
2604
+ hint: "Independent copies for each agent"
2605
+ }]
2606
+ });
2607
+ if (pD(modeChoice)) {
2608
+ xe("Installation cancelled");
2609
+ await cleanup(tempDir);
2610
+ process.exit(0);
2611
+ }
2612
+ installMode = modeChoice;
2613
+ } else if (uniqueDirs.size <= 1) installMode = "copy";
2614
+ const cwd = process.cwd();
2615
+ const summaryLines = [];
2616
+ targetAgents.map((a) => agents[a].displayName);
2617
+ const overwriteChecks = await Promise.all(selectedSkills.flatMap((skill) => targetAgents.map(async (agent) => ({
2618
+ skillName: skill.name,
2619
+ agent,
2620
+ installed: await isSkillInstalled(skill.name, agent, { global: installGlobally })
2621
+ }))));
2622
+ const overwriteStatus = /* @__PURE__ */ new Map();
2623
+ for (const { skillName, agent, installed } of overwriteChecks) {
2624
+ if (!overwriteStatus.has(skillName)) overwriteStatus.set(skillName, /* @__PURE__ */ new Map());
2625
+ overwriteStatus.get(skillName).set(agent, installed);
2626
+ }
2627
+ const groupedSummary = {};
2628
+ const ungroupedSummary = [];
2629
+ for (const skill of selectedSkills) if (skill.pluginName) {
2630
+ const group = skill.pluginName;
2631
+ if (!groupedSummary[group]) groupedSummary[group] = [];
2632
+ groupedSummary[group].push(skill);
2633
+ } else ungroupedSummary.push(skill);
2634
+ const printSkillSummary = (skills) => {
2635
+ for (const skill of skills) {
2636
+ if (summaryLines.length > 0) summaryLines.push("");
2637
+ const shortCanonical = shortenPath$2(getCanonicalPath(skill.name, { global: installGlobally }), cwd);
2638
+ summaryLines.push(`${import_picocolors.default.cyan(shortCanonical)}`);
2639
+ summaryLines.push(...buildAgentSummaryLines(targetAgents, installMode));
2640
+ const skillOverwrites = overwriteStatus.get(skill.name);
2641
+ const overwriteAgents = targetAgents.filter((a) => skillOverwrites?.get(a)).map((a) => agents[a].displayName);
2642
+ if (overwriteAgents.length > 0) summaryLines.push(` ${import_picocolors.default.yellow("overwrites:")} ${formatList$1(overwriteAgents)}`);
2643
+ }
2644
+ };
2645
+ const sortedGroups = Object.keys(groupedSummary).sort();
2646
+ for (const group of sortedGroups) {
2647
+ const title = group.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
2648
+ summaryLines.push("");
2649
+ summaryLines.push(import_picocolors.default.bold(title));
2650
+ printSkillSummary(groupedSummary[group]);
2651
+ }
2652
+ if (ungroupedSummary.length > 0) {
2653
+ if (sortedGroups.length > 0) {
2654
+ summaryLines.push("");
2655
+ summaryLines.push(import_picocolors.default.bold("General"));
2656
+ }
2657
+ printSkillSummary(ungroupedSummary);
2658
+ }
2659
+ console.log();
2660
+ Me(summaryLines.join("\n"), "Installation Summary");
2661
+ try {
2662
+ const auditData = await auditPromise;
2663
+ if (auditData && ownerRepoForAudit) {
2664
+ const securityLines = buildSecurityLines(auditData, selectedSkills.map((s) => ({
2665
+ slug: getSkillDisplayName(s),
2666
+ displayName: getSkillDisplayName(s)
2667
+ })), ownerRepoForAudit);
2668
+ if (securityLines.length > 0) Me(securityLines.join("\n"), "Security Risk Assessments");
2669
+ }
2670
+ } catch {}
2671
+ if (!options.yes) {
2672
+ const confirmed = await ye({ message: "Proceed with installation?" });
2673
+ if (pD(confirmed) || !confirmed) {
2674
+ xe("Installation cancelled");
2675
+ await cleanup(tempDir);
2676
+ process.exit(0);
2677
+ }
2678
+ }
2679
+ spinner.start("Installing skills...");
2680
+ const results = [];
2681
+ for (const skill of selectedSkills) for (const agent of targetAgents) {
2682
+ const result = await installSkillForAgent(skill, agent, {
2683
+ global: installGlobally,
2684
+ mode: installMode
2685
+ });
2686
+ results.push({
2687
+ skill: getSkillDisplayName(skill),
2688
+ agent: agents[agent].displayName,
2689
+ pluginName: skill.pluginName,
2690
+ ...result
2691
+ });
2692
+ }
2693
+ spinner.stop("Installation complete");
2694
+ console.log();
2695
+ const successful = results.filter((r) => r.success);
2696
+ const failed = results.filter((r) => !r.success);
2697
+ const skillFiles = {};
2698
+ for (const skill of selectedSkills) {
2699
+ let relativePath;
2700
+ if (tempDir && skill.path === tempDir) relativePath = "SKILL.md";
2701
+ else if (tempDir && skill.path.startsWith(tempDir + sep)) relativePath = skill.path.slice(tempDir.length + 1).split(sep).join("/") + "/SKILL.md";
2702
+ else continue;
2703
+ skillFiles[skill.name] = relativePath;
2704
+ }
2705
+ const normalizedSource = getOwnerRepo(parsed);
2706
+ const lockSource = parsed.url.startsWith("git@") ? parsed.url : normalizedSource;
2707
+ if (normalizedSource) {
2708
+ const ownerRepo = parseOwnerRepo(normalizedSource);
2709
+ if (ownerRepo) {
2710
+ if (await isRepoPrivate(ownerRepo.owner, ownerRepo.repo) === false) track({
2711
+ event: "install",
2712
+ source: normalizedSource,
2713
+ skills: selectedSkills.map((s) => s.name).join(","),
2714
+ agents: targetAgents.join(","),
2715
+ ...installGlobally && { global: "1" },
2716
+ skillFiles: JSON.stringify(skillFiles)
2717
+ });
2718
+ } else track({
2719
+ event: "install",
2720
+ source: normalizedSource,
2721
+ skills: selectedSkills.map((s) => s.name).join(","),
2722
+ agents: targetAgents.join(","),
2723
+ ...installGlobally && { global: "1" },
2724
+ skillFiles: JSON.stringify(skillFiles)
2725
+ });
2726
+ }
2727
+ if (successful.length > 0 && installGlobally && normalizedSource) {
2728
+ const successfulSkillNames = new Set(successful.map((r) => r.skill));
2729
+ for (const skill of selectedSkills) {
2730
+ const skillDisplayName = getSkillDisplayName(skill);
2731
+ if (successfulSkillNames.has(skillDisplayName)) try {
2732
+ let skillFolderHash = "";
2733
+ const skillPathValue = skillFiles[skill.name];
2734
+ if (parsed.type === "github" && skillPathValue) {
2735
+ const hash = await fetchSkillFolderHash(normalizedSource, skillPathValue, getGitHubToken());
2736
+ if (hash) skillFolderHash = hash;
2737
+ }
2738
+ await addSkillToLock(skill.name, {
2739
+ source: lockSource || normalizedSource,
2740
+ sourceType: parsed.type,
2741
+ sourceUrl: parsed.url,
2742
+ skillPath: skillPathValue,
2743
+ skillFolderHash,
2744
+ pluginName: skill.pluginName
2745
+ });
2746
+ } catch {}
2747
+ }
2748
+ }
2749
+ if (successful.length > 0 && !installGlobally) {
2750
+ const successfulSkillNames = new Set(successful.map((r) => r.skill));
2751
+ for (const skill of selectedSkills) {
2752
+ const skillDisplayName = getSkillDisplayName(skill);
2753
+ if (successfulSkillNames.has(skillDisplayName)) try {
2754
+ const computedHash = await computeSkillFolderHash(skill.path);
2755
+ await addSkillToLocalLock(skill.name, {
2756
+ source: lockSource || parsed.url,
2757
+ sourceType: parsed.type,
2758
+ computedHash
2759
+ }, cwd);
2760
+ } catch {}
2761
+ }
2762
+ }
2763
+ if (successful.length > 0) {
2764
+ const bySkill = /* @__PURE__ */ new Map();
2765
+ const groupedResults = {};
2766
+ const ungroupedResults = [];
2767
+ for (const r of successful) {
2768
+ const skillResults = bySkill.get(r.skill) || [];
2769
+ skillResults.push(r);
2770
+ bySkill.set(r.skill, skillResults);
2771
+ if (skillResults.length === 1) if (r.pluginName) {
2772
+ const group = r.pluginName;
2773
+ if (!groupedResults[group]) groupedResults[group] = [];
2774
+ groupedResults[group].push(r);
2775
+ } else ungroupedResults.push(r);
2776
+ }
2777
+ const skillCount = bySkill.size;
2778
+ const symlinkFailures = successful.filter((r) => r.mode === "symlink" && r.symlinkFailed);
2779
+ const copiedAgents = symlinkFailures.map((r) => r.agent);
2780
+ const resultLines = [];
2781
+ const printSkillResults = (entries) => {
2782
+ for (const entry of entries) {
2783
+ const skillResults = bySkill.get(entry.skill) || [];
2784
+ const firstResult = skillResults[0];
2785
+ if (firstResult.mode === "copy") {
2786
+ resultLines.push(`${import_picocolors.default.green("✓")} ${entry.skill} ${import_picocolors.default.dim("(copied)")}`);
2787
+ for (const r of skillResults) {
2788
+ const shortPath = shortenPath$2(r.path, cwd);
2789
+ resultLines.push(` ${import_picocolors.default.dim("→")} ${shortPath}`);
2790
+ }
2791
+ } else {
2792
+ if (firstResult.canonicalPath) {
2793
+ const shortPath = shortenPath$2(firstResult.canonicalPath, cwd);
2794
+ resultLines.push(`${import_picocolors.default.green("✓")} ${shortPath}`);
2795
+ } else resultLines.push(`${import_picocolors.default.green("✓")} ${entry.skill}`);
2796
+ resultLines.push(...buildResultLines(skillResults, targetAgents));
2797
+ }
2798
+ }
2799
+ };
2800
+ const sortedResultGroups = Object.keys(groupedResults).sort();
2801
+ for (const group of sortedResultGroups) {
2802
+ const title = group.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
2803
+ resultLines.push("");
2804
+ resultLines.push(import_picocolors.default.bold(title));
2805
+ printSkillResults(groupedResults[group]);
2806
+ }
2807
+ if (ungroupedResults.length > 0) {
2808
+ if (sortedResultGroups.length > 0) {
2809
+ resultLines.push("");
2810
+ resultLines.push(import_picocolors.default.bold("General"));
2811
+ }
2812
+ printSkillResults(ungroupedResults);
2813
+ }
2814
+ const title = import_picocolors.default.green(`Installed ${skillCount} skill${skillCount !== 1 ? "s" : ""}`);
2815
+ Me(resultLines.join("\n"), title);
2816
+ if (symlinkFailures.length > 0) {
2817
+ M.warn(import_picocolors.default.yellow(`Symlinks failed for: ${formatList$1(copiedAgents)}`));
2818
+ M.message(import_picocolors.default.dim(" Files were copied instead. On Windows, enable Developer Mode for symlink support."));
2819
+ }
2820
+ }
2821
+ if (failed.length > 0) {
2822
+ console.log();
2823
+ M.error(import_picocolors.default.red(`Failed to install ${failed.length}`));
2824
+ for (const r of failed) M.message(` ${import_picocolors.default.red("✗")} ${r.skill} → ${r.agent}: ${import_picocolors.default.dim(r.error)}`);
2825
+ }
2826
+ const allPostInstallCommands = [];
2827
+ for (const skill of selectedSkills) {
2828
+ if (skill.postInstall.length > 0) allPostInstallCommands.push(...skill.postInstall);
2829
+ if (skill.dependsOn.length > 0) {
2830
+ M.info(import_picocolors.default.dim(`Resolving dependencies for ${skill.name}...`));
2831
+ const depResult = await resolveDependencies(skill, async (source, skillName) => {
2832
+ const depSource = skillName ? `${source}@${skillName}` : source;
2833
+ M.step(import_picocolors.default.dim(` Installing dependency: ${depSource}`));
2834
+ await runAdd([depSource], {
2835
+ ...options,
2836
+ yes: true,
2837
+ skill: skillName ? [skillName] : void 0
2838
+ });
2839
+ return [];
2840
+ }, (warning) => M.warn(import_picocolors.default.yellow(warning)));
2841
+ allPostInstallCommands.push(...depResult.postInstallCommands);
2842
+ if (depResult.errors.length > 0) for (const err of depResult.errors) M.warn(import_picocolors.default.yellow(`Dependency ${err.ref}: ${err.error}`));
2843
+ }
2844
+ }
2845
+ if (allPostInstallCommands.length > 0) {
2846
+ console.log();
2847
+ M.info("Post-install commands required:");
2848
+ console.log(formatPostInstallCommands(allPostInstallCommands));
2849
+ console.log();
2850
+ let shouldRun = options.trustScripts === true;
2851
+ if (!shouldRun && !options.yes) shouldRun = await ye({ message: "Run these post-install commands?" }) === true;
2852
+ if (shouldRun) {
2853
+ const postResult = await executePostInstallCommands(allPostInstallCommands, (cmd) => {
2854
+ execSync(cmd, { stdio: "inherit" });
2855
+ });
2856
+ if (postResult.failed.length > 0) for (const f of postResult.failed) M.warn(import_picocolors.default.yellow(`Post-install command failed: ${f.command}`));
2857
+ } else M.info(import_picocolors.default.dim("Post-install commands skipped."));
2858
+ }
2859
+ console.log();
2860
+ Se(import_picocolors.default.green("Done!") + import_picocolors.default.dim(" Review skills before use; they run with full agent permissions."));
2861
+ await promptForFindSkills(options, targetAgents);
2862
+ } catch (error) {
2863
+ if (error instanceof GitCloneError) {
2864
+ M.error(import_picocolors.default.red("Failed to clone repository"));
2865
+ for (const line of error.message.split("\n")) M.message(import_picocolors.default.dim(line));
2866
+ } else M.error(error instanceof Error ? error.message : "Unknown error occurred");
2867
+ showInstallTip();
2868
+ Se(import_picocolors.default.red("Installation failed"));
2869
+ process.exit(1);
2870
+ } finally {
2871
+ await cleanup(tempDir);
2872
+ }
2873
+ }
2874
+ async function cleanup(tempDir) {
2875
+ if (tempDir) try {
2876
+ await cleanupTempDir(tempDir);
2877
+ } catch {}
2878
+ }
2879
+ async function promptForFindSkills(options, targetAgents) {
2880
+ if (!process.stdin.isTTY) return;
2881
+ if (options?.yes) return;
2882
+ try {
2883
+ if (await isPromptDismissed("findSkillsPrompt")) return;
2884
+ if (await isSkillInstalled("find-skills", "claude-code", { global: true })) {
2885
+ await dismissPrompt("findSkillsPrompt");
2886
+ return;
2887
+ }
2888
+ console.log();
2889
+ M.message(import_picocolors.default.dim("One-time prompt - you won't be asked again if you dismiss."));
2890
+ const install = await ye({ message: `Install the ${import_picocolors.default.cyan("find-skills")} skill? It helps your agent discover and suggest skills.` });
2891
+ if (pD(install)) {
2892
+ await dismissPrompt("findSkillsPrompt");
2893
+ return;
2894
+ }
2895
+ if (install) {
2896
+ await dismissPrompt("findSkillsPrompt");
2897
+ const findSkillsAgents = targetAgents?.filter((a) => a !== "replit");
2898
+ if (!findSkillsAgents || findSkillsAgents.length === 0) return;
2899
+ console.log();
2900
+ M.step("Installing find-skills skill...");
2901
+ try {
2902
+ await runAdd(["vercel-labs/skills"], {
2903
+ skill: ["find-skills"],
2904
+ global: true,
2905
+ yes: true,
2906
+ agent: findSkillsAgents
2907
+ });
2908
+ } catch {
2909
+ M.warn("Failed to install find-skills. You can try again with:");
2910
+ M.message(import_picocolors.default.dim(" npx skpm-cli add vercel-labs/skills@find-skills -g -y --all"));
2911
+ }
2912
+ } else {
2913
+ await dismissPrompt("findSkillsPrompt");
2914
+ M.message(import_picocolors.default.dim("You can install it later with: npx skpm-cli add vercel-labs/skills@find-skills"));
2915
+ }
2916
+ } catch {}
2917
+ }
2918
+ function parseAddOptions(args) {
2919
+ const options = {};
2920
+ const source = [];
2921
+ for (let i = 0; i < args.length; i++) {
2922
+ const arg = args[i];
2923
+ if (arg === "-g" || arg === "--global") options.global = true;
2924
+ else if (arg === "-y" || arg === "--yes") options.yes = true;
2925
+ else if (arg === "-l" || arg === "--list") options.list = true;
2926
+ else if (arg === "--all") options.all = true;
2927
+ else if (arg === "-a" || arg === "--agent") {
2928
+ options.agent = options.agent || [];
2929
+ i++;
2930
+ let nextArg = args[i];
2931
+ while (i < args.length && nextArg && !nextArg.startsWith("-")) {
2932
+ options.agent.push(nextArg);
2933
+ i++;
2934
+ nextArg = args[i];
2935
+ }
2936
+ i--;
2937
+ } else if (arg === "-s" || arg === "--skill") {
2938
+ options.skill = options.skill || [];
2939
+ i++;
2940
+ let nextArg = args[i];
2941
+ while (i < args.length && nextArg && !nextArg.startsWith("-")) {
2942
+ options.skill.push(nextArg);
2943
+ i++;
2944
+ nextArg = args[i];
2945
+ }
2946
+ i--;
2947
+ } else if (arg === "--full-depth") options.fullDepth = true;
2948
+ else if (arg === "--copy") options.copy = true;
2949
+ else if (arg === "--trust-scripts") options.trustScripts = true;
2950
+ else if (arg && !arg.startsWith("-")) source.push(arg);
2951
+ }
2952
+ return {
2953
+ source,
2954
+ options
2955
+ };
2956
+ }
2957
+ const RESET$2 = "\x1B[0m";
2958
+ const BOLD$2 = "\x1B[1m";
2959
+ const DIM$2 = "\x1B[38;5;102m";
2960
+ const TEXT$1 = "\x1B[38;5;145m";
2961
+ const CYAN$1 = "\x1B[36m";
2962
+ const SEARCH_API_BASE = process.env.SKPM_API_URL || "https://skpm.sh";
2963
+ function formatInstalls(count) {
2964
+ if (!count || count <= 0) return "";
2965
+ if (count >= 1e6) return `${(count / 1e6).toFixed(1).replace(/\.0$/, "")}M installs`;
2966
+ if (count >= 1e3) return `${(count / 1e3).toFixed(1).replace(/\.0$/, "")}K installs`;
2967
+ return `${count} install${count === 1 ? "" : "s"}`;
2968
+ }
2969
+ async function searchSkillsAPI(query) {
2970
+ try {
2971
+ const url = `${SEARCH_API_BASE}/api/search?q=${encodeURIComponent(query)}&limit=10`;
2972
+ const res = await fetch(url);
2973
+ if (!res.ok) return [];
2974
+ return (await res.json()).skills.map((skill) => ({
2975
+ name: skill.name,
2976
+ slug: skill.id,
2977
+ source: skill.source || "",
2978
+ installs: skill.installs
2979
+ })).sort((a, b) => (b.installs || 0) - (a.installs || 0));
2980
+ } catch {
2981
+ return [];
2982
+ }
2983
+ }
2984
+ const HIDE_CURSOR = "\x1B[?25l";
2985
+ const SHOW_CURSOR = "\x1B[?25h";
2986
+ const CLEAR_DOWN = "\x1B[J";
2987
+ const MOVE_UP = (n) => `\x1b[${n}A`;
2988
+ const MOVE_TO_COL = (n) => `\x1b[${n}G`;
2989
+ async function runSearchPrompt(initialQuery = "") {
2990
+ let results = [];
2991
+ let selectedIndex = 0;
2992
+ let query = initialQuery;
2993
+ let loading = false;
2994
+ let debounceTimer = null;
2995
+ let lastRenderedLines = 0;
2996
+ if (process.stdin.isTTY) process.stdin.setRawMode(true);
2997
+ readline.emitKeypressEvents(process.stdin);
2998
+ process.stdin.resume();
2999
+ process.stdout.write(HIDE_CURSOR);
3000
+ function render() {
3001
+ if (lastRenderedLines > 0) process.stdout.write(MOVE_UP(lastRenderedLines) + MOVE_TO_COL(1));
3002
+ process.stdout.write(CLEAR_DOWN);
3003
+ const lines = [];
3004
+ const cursor = `${BOLD$2}_${RESET$2}`;
3005
+ lines.push(`${TEXT$1}Search skills:${RESET$2} ${query}${cursor}`);
3006
+ lines.push("");
3007
+ if (!query || query.length < 2) lines.push(`${DIM$2}Start typing to search (min 2 chars)${RESET$2}`);
3008
+ else if (results.length === 0 && loading) lines.push(`${DIM$2}Searching...${RESET$2}`);
3009
+ else if (results.length === 0) lines.push(`${DIM$2}No skills found${RESET$2}`);
3010
+ else {
3011
+ const visible = results.slice(0, 8);
3012
+ for (let i = 0; i < visible.length; i++) {
3013
+ const skill = visible[i];
3014
+ const isSelected = i === selectedIndex;
3015
+ const arrow = isSelected ? `${BOLD$2}>${RESET$2}` : " ";
3016
+ const name = isSelected ? `${BOLD$2}${skill.name}${RESET$2}` : `${TEXT$1}${skill.name}${RESET$2}`;
3017
+ const source = skill.source ? ` ${DIM$2}${skill.source}${RESET$2}` : "";
3018
+ const installs = formatInstalls(skill.installs);
3019
+ const installsBadge = installs ? ` ${CYAN$1}${installs}${RESET$2}` : "";
3020
+ const loadingIndicator = loading && i === 0 ? ` ${DIM$2}...${RESET$2}` : "";
3021
+ lines.push(` ${arrow} ${name}${source}${installsBadge}${loadingIndicator}`);
3022
+ }
3023
+ }
3024
+ lines.push("");
3025
+ lines.push(`${DIM$2}up/down navigate | enter select | esc cancel${RESET$2}`);
3026
+ for (const line of lines) process.stdout.write(line + "\n");
3027
+ lastRenderedLines = lines.length;
3028
+ }
3029
+ function triggerSearch(q) {
3030
+ if (debounceTimer) {
3031
+ clearTimeout(debounceTimer);
3032
+ debounceTimer = null;
3033
+ }
3034
+ loading = false;
3035
+ if (!q || q.length < 2) {
3036
+ results = [];
3037
+ selectedIndex = 0;
3038
+ render();
3039
+ return;
3040
+ }
3041
+ loading = true;
3042
+ render();
3043
+ const debounceMs = Math.max(150, 350 - q.length * 50);
3044
+ debounceTimer = setTimeout(async () => {
3045
+ try {
3046
+ results = await searchSkillsAPI(q);
3047
+ selectedIndex = 0;
3048
+ } catch {
3049
+ results = [];
3050
+ } finally {
3051
+ loading = false;
3052
+ debounceTimer = null;
3053
+ render();
3054
+ }
3055
+ }, debounceMs);
3056
+ }
3057
+ if (initialQuery) triggerSearch(initialQuery);
3058
+ render();
3059
+ return new Promise((resolve) => {
3060
+ function cleanup() {
3061
+ process.stdin.removeListener("keypress", handleKeypress);
3062
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
3063
+ process.stdout.write(SHOW_CURSOR);
3064
+ process.stdin.pause();
3065
+ }
3066
+ function handleKeypress(_ch, key) {
3067
+ if (!key) return;
3068
+ if (key.name === "escape" || key.ctrl && key.name === "c") {
3069
+ cleanup();
3070
+ resolve(null);
3071
+ return;
3072
+ }
3073
+ if (key.name === "return") {
3074
+ cleanup();
3075
+ resolve(results[selectedIndex] || null);
3076
+ return;
3077
+ }
3078
+ if (key.name === "up") {
3079
+ selectedIndex = Math.max(0, selectedIndex - 1);
3080
+ render();
3081
+ return;
3082
+ }
3083
+ if (key.name === "down") {
3084
+ selectedIndex = Math.min(Math.max(0, results.length - 1), selectedIndex + 1);
3085
+ render();
3086
+ return;
3087
+ }
3088
+ if (key.name === "backspace") {
3089
+ if (query.length > 0) {
3090
+ query = query.slice(0, -1);
3091
+ triggerSearch(query);
3092
+ }
3093
+ return;
3094
+ }
3095
+ if (key.sequence && !key.ctrl && !key.meta && key.sequence.length === 1) {
3096
+ const char = key.sequence;
3097
+ if (char >= " " && char <= "~") {
3098
+ query += char;
3099
+ triggerSearch(query);
3100
+ }
3101
+ }
3102
+ }
3103
+ process.stdin.on("keypress", handleKeypress);
3104
+ });
3105
+ }
3106
+ function getOwnerRepoFromString(pkg) {
3107
+ const atIndex = pkg.lastIndexOf("@");
3108
+ const match = (atIndex > 0 ? pkg.slice(0, atIndex) : pkg).match(/^([^/]+)\/([^/]+)$/);
3109
+ if (match) return {
3110
+ owner: match[1],
3111
+ repo: match[2]
3112
+ };
3113
+ return null;
3114
+ }
3115
+ async function isRepoPublic(owner, repo) {
3116
+ return await isRepoPrivate(owner, repo) === false;
3117
+ }
3118
+ async function runFind(args) {
3119
+ const query = args.join(" ");
3120
+ const isNonInteractive = !process.stdin.isTTY;
3121
+ const agentTip = `${DIM$2}Tip: if running in a coding agent, follow these steps:${RESET$2}
3122
+ ${DIM$2} 1) npx skpm-cli find [query]${RESET$2}
3123
+ ${DIM$2} 2) npx skpm-cli add <owner/repo@skill>${RESET$2}`;
3124
+ if (query) {
3125
+ const results = await searchSkillsAPI(query);
3126
+ track({
3127
+ event: "find",
3128
+ query,
3129
+ resultCount: String(results.length)
3130
+ });
3131
+ if (results.length === 0) {
3132
+ console.log(`${DIM$2}No skills found for "${query}"${RESET$2}`);
3133
+ return;
3134
+ }
3135
+ console.log(`${DIM$2}Install with${RESET$2} npx skpm-cli add <owner/repo@skill>`);
3136
+ console.log();
3137
+ for (const skill of results.slice(0, 6)) {
3138
+ const pkg = skill.source || skill.slug;
3139
+ const installs = formatInstalls(skill.installs);
3140
+ console.log(`${TEXT$1}${pkg}@${skill.name}${RESET$2}${installs ? ` ${CYAN$1}${installs}${RESET$2}` : ""}`);
3141
+ console.log(`${DIM$2}└ https://skpm.sh/${skill.slug}${RESET$2}`);
3142
+ console.log();
3143
+ }
3144
+ return;
3145
+ }
3146
+ if (isNonInteractive) {
3147
+ console.log(agentTip);
3148
+ console.log();
3149
+ }
3150
+ const selected = await runSearchPrompt();
3151
+ track({
3152
+ event: "find",
3153
+ query: "",
3154
+ resultCount: selected ? "1" : "0",
3155
+ interactive: "1"
3156
+ });
3157
+ if (!selected) {
3158
+ console.log(`${DIM$2}Search cancelled${RESET$2}`);
3159
+ console.log();
3160
+ return;
3161
+ }
3162
+ const pkg = selected.source || selected.slug;
3163
+ const skillName = selected.name;
3164
+ console.log();
3165
+ console.log(`${TEXT$1}Installing ${BOLD$2}${skillName}${RESET$2} from ${DIM$2}${pkg}${RESET$2}...`);
3166
+ console.log();
3167
+ const { source, options } = parseAddOptions([
3168
+ pkg,
3169
+ "--skill",
3170
+ skillName
3171
+ ]);
3172
+ await runAdd(source, options);
3173
+ console.log();
3174
+ const info = getOwnerRepoFromString(pkg);
3175
+ if (info && await isRepoPublic(info.owner, info.repo)) console.log(`${DIM$2}View the skill at${RESET$2} ${TEXT$1}https://skpm.sh/${selected.slug}${RESET$2}`);
3176
+ else console.log(`${DIM$2}Discover more skills at${RESET$2} ${TEXT$1}https://skpm.sh${RESET$2}`);
3177
+ console.log();
3178
+ }
3179
+ const isCancelled = (value) => typeof value === "symbol";
3180
+ function shortenPath$1(fullPath, cwd) {
3181
+ const home = homedir();
3182
+ if (fullPath === home || fullPath.startsWith(home + sep)) return "~" + fullPath.slice(home.length);
3183
+ if (fullPath === cwd || fullPath.startsWith(cwd + sep)) return "." + fullPath.slice(cwd.length);
3184
+ return fullPath;
3185
+ }
3186
+ async function discoverNodeModuleSkills(cwd) {
3187
+ const nodeModulesDir = join(cwd, "node_modules");
3188
+ const skills = [];
3189
+ let topNames;
3190
+ try {
3191
+ topNames = await readdir(nodeModulesDir);
3192
+ } catch {
3193
+ return skills;
3194
+ }
3195
+ const processPackageDir = async (pkgDir, packageName) => {
3196
+ const rootSkill = await parseSkillMd(join(pkgDir, "SKILL.md"));
3197
+ if (rootSkill) {
3198
+ skills.push({
3199
+ ...rootSkill,
3200
+ packageName
3201
+ });
3202
+ return;
3203
+ }
3204
+ const searchDirs = [
3205
+ pkgDir,
3206
+ join(pkgDir, "skills"),
3207
+ join(pkgDir, ".agents", "skills")
3208
+ ];
3209
+ for (const searchDir of searchDirs) try {
3210
+ const entries = await readdir(searchDir);
3211
+ for (const name of entries) {
3212
+ const skillDir = join(searchDir, name);
3213
+ try {
3214
+ if (!(await stat(skillDir)).isDirectory()) continue;
3215
+ } catch {
3216
+ continue;
3217
+ }
3218
+ const skill = await parseSkillMd(join(skillDir, "SKILL.md"));
3219
+ if (skill) skills.push({
3220
+ ...skill,
3221
+ packageName
3222
+ });
3223
+ }
3224
+ } catch {}
3225
+ };
3226
+ await Promise.all(topNames.map(async (name) => {
3227
+ if (name.startsWith(".")) return;
3228
+ const fullPath = join(nodeModulesDir, name);
3229
+ try {
3230
+ if (!(await stat(fullPath)).isDirectory()) return;
3231
+ } catch {
3232
+ return;
3233
+ }
3234
+ if (name.startsWith("@")) try {
3235
+ const scopeNames = await readdir(fullPath);
3236
+ await Promise.all(scopeNames.map(async (scopedName) => {
3237
+ const scopedPath = join(fullPath, scopedName);
3238
+ try {
3239
+ if (!(await stat(scopedPath)).isDirectory()) return;
3240
+ } catch {
3241
+ return;
3242
+ }
3243
+ await processPackageDir(scopedPath, `${name}/${scopedName}`);
3244
+ }));
3245
+ } catch {}
3246
+ else await processPackageDir(fullPath, name);
3247
+ }));
3248
+ return skills;
3249
+ }
3250
+ async function runSync(args, options = {}) {
3251
+ const cwd = process.cwd();
3252
+ console.log();
3253
+ Ie(import_picocolors.default.bgCyan(import_picocolors.default.black(" skpm experimental_sync")));
3254
+ const spinner = Y();
3255
+ spinner.start("Scanning node_modules for skills...");
3256
+ const discoveredSkills = await discoverNodeModuleSkills(cwd);
3257
+ if (discoveredSkills.length === 0) {
3258
+ spinner.stop(import_picocolors.default.yellow("No skills found"));
3259
+ Se(import_picocolors.default.dim("No SKILL.md files found in node_modules."));
3260
+ return;
3261
+ }
3262
+ spinner.stop(`Found ${import_picocolors.default.green(String(discoveredSkills.length))} skill${discoveredSkills.length > 1 ? "s" : ""} in node_modules`);
3263
+ for (const skill of discoveredSkills) {
3264
+ M.info(`${import_picocolors.default.cyan(skill.name)} ${import_picocolors.default.dim(`from ${skill.packageName}`)}`);
3265
+ if (skill.description) M.message(import_picocolors.default.dim(` ${skill.description}`));
3266
+ }
3267
+ const localLock = await readLocalLock(cwd);
3268
+ const toInstall = [];
3269
+ const upToDate = [];
3270
+ if (options.force) {
3271
+ toInstall.push(...discoveredSkills);
3272
+ M.info(import_picocolors.default.dim("Force mode: reinstalling all skills"));
3273
+ } else {
3274
+ for (const skill of discoveredSkills) {
3275
+ const existingEntry = localLock.skills[skill.name];
3276
+ if (existingEntry) {
3277
+ if (await computeSkillFolderHash(skill.path) === existingEntry.computedHash) {
3278
+ upToDate.push(skill.name);
3279
+ continue;
3280
+ }
3281
+ }
3282
+ toInstall.push(skill);
3283
+ }
3284
+ if (upToDate.length > 0) M.info(import_picocolors.default.dim(`${upToDate.length} skill${upToDate.length !== 1 ? "s" : ""} already up to date`));
3285
+ if (toInstall.length === 0) {
3286
+ console.log();
3287
+ Se(import_picocolors.default.green("All skills are up to date."));
3288
+ return;
3289
+ }
3290
+ }
3291
+ M.info(`${toInstall.length} skill${toInstall.length !== 1 ? "s" : ""} to install/update`);
3292
+ let targetAgents;
3293
+ const validAgents = Object.keys(agents);
3294
+ const universalAgents = getUniversalAgents();
3295
+ if (options.agent?.includes("*")) {
3296
+ targetAgents = validAgents;
3297
+ M.info(`Installing to all ${targetAgents.length} agents`);
3298
+ } else if (options.agent && options.agent.length > 0) {
3299
+ const invalidAgents = options.agent.filter((a) => !validAgents.includes(a));
3300
+ if (invalidAgents.length > 0) {
3301
+ M.error(`Invalid agents: ${invalidAgents.join(", ")}`);
3302
+ M.info(`Valid agents: ${validAgents.join(", ")}`);
3303
+ process.exit(1);
3304
+ }
3305
+ targetAgents = options.agent;
3306
+ } else {
3307
+ spinner.start("Loading agents...");
3308
+ const installedAgents = await detectInstalledAgents();
3309
+ const totalAgents = Object.keys(agents).length;
3310
+ spinner.stop(`${totalAgents} agents`);
3311
+ if (installedAgents.length === 0) if (options.yes) {
3312
+ targetAgents = universalAgents;
3313
+ M.info("Installing to universal agents");
3314
+ } else {
3315
+ const selected = await searchMultiselect({
3316
+ message: "Which agents do you want to install to?",
3317
+ items: getNonUniversalAgents().map((a) => ({
3318
+ value: a,
3319
+ label: agents[a].displayName,
3320
+ hint: agents[a].skillsDir
3321
+ })),
3322
+ initialSelected: [],
3323
+ lockedSection: {
3324
+ title: "Universal (.agents/skills)",
3325
+ items: universalAgents.map((a) => ({
3326
+ value: a,
3327
+ label: agents[a].displayName
3328
+ }))
3329
+ }
3330
+ });
3331
+ if (isCancelled(selected)) {
3332
+ xe("Sync cancelled");
3333
+ process.exit(0);
3334
+ }
3335
+ targetAgents = selected;
3336
+ }
3337
+ else if (installedAgents.length === 1 || options.yes) {
3338
+ targetAgents = [...installedAgents];
3339
+ for (const ua of universalAgents) if (!targetAgents.includes(ua)) targetAgents.push(ua);
3340
+ } else {
3341
+ const selected = await searchMultiselect({
3342
+ message: "Which agents do you want to install to?",
3343
+ items: getNonUniversalAgents().filter((a) => installedAgents.includes(a)).map((a) => ({
3344
+ value: a,
3345
+ label: agents[a].displayName,
3346
+ hint: agents[a].skillsDir
3347
+ })),
3348
+ initialSelected: installedAgents.filter((a) => !universalAgents.includes(a)),
3349
+ lockedSection: {
3350
+ title: "Universal (.agents/skills)",
3351
+ items: universalAgents.map((a) => ({
3352
+ value: a,
3353
+ label: agents[a].displayName
3354
+ }))
3355
+ }
3356
+ });
3357
+ if (isCancelled(selected)) {
3358
+ xe("Sync cancelled");
3359
+ process.exit(0);
3360
+ }
3361
+ targetAgents = selected;
3362
+ }
3363
+ }
3364
+ const summaryLines = [];
3365
+ for (const skill of toInstall) {
3366
+ const shortCanonical = shortenPath$1(getCanonicalPath(skill.name, { global: false }), cwd);
3367
+ summaryLines.push(`${import_picocolors.default.cyan(skill.name)} ${import_picocolors.default.dim(`← ${skill.packageName}`)}`);
3368
+ summaryLines.push(` ${import_picocolors.default.dim(shortCanonical)}`);
3369
+ }
3370
+ console.log();
3371
+ Me(summaryLines.join("\n"), "Sync Summary");
3372
+ if (!options.yes) {
3373
+ const confirmed = await ye({ message: "Proceed with sync?" });
3374
+ if (pD(confirmed) || !confirmed) {
3375
+ xe("Sync cancelled");
3376
+ process.exit(0);
3377
+ }
3378
+ }
3379
+ spinner.start("Syncing skills...");
3380
+ const results = [];
3381
+ for (const skill of toInstall) for (const agent of targetAgents) {
3382
+ const result = await installSkillForAgent(skill, agent, {
3383
+ global: false,
3384
+ cwd,
3385
+ mode: "symlink"
3386
+ });
3387
+ results.push({
3388
+ skill: skill.name,
3389
+ packageName: skill.packageName,
3390
+ agent: agents[agent].displayName,
3391
+ success: result.success,
3392
+ path: result.path,
3393
+ canonicalPath: result.canonicalPath,
3394
+ error: result.error
3395
+ });
3396
+ }
3397
+ spinner.stop("Sync complete");
3398
+ const successful = results.filter((r) => r.success);
3399
+ const failed = results.filter((r) => !r.success);
3400
+ const successfulSkillNames = new Set(successful.map((r) => r.skill));
3401
+ for (const skill of toInstall) if (successfulSkillNames.has(skill.name)) try {
3402
+ const computedHash = await computeSkillFolderHash(skill.path);
3403
+ await addSkillToLocalLock(skill.name, {
3404
+ source: skill.packageName,
3405
+ sourceType: "node_modules",
3406
+ computedHash
3407
+ }, cwd);
3408
+ } catch {}
3409
+ console.log();
3410
+ if (successful.length > 0) {
3411
+ const bySkill = /* @__PURE__ */ new Map();
3412
+ for (const r of successful) {
3413
+ const skillResults = bySkill.get(r.skill) || [];
3414
+ skillResults.push(r);
3415
+ bySkill.set(r.skill, skillResults);
3416
+ }
3417
+ const resultLines = [];
3418
+ for (const [skillName, skillResults] of bySkill) {
3419
+ const firstResult = skillResults[0];
3420
+ const pkg = toInstall.find((s) => s.name === skillName)?.packageName;
3421
+ if (firstResult.canonicalPath) {
3422
+ const shortPath = shortenPath$1(firstResult.canonicalPath, cwd);
3423
+ resultLines.push(`${import_picocolors.default.green("✓")} ${skillName} ${import_picocolors.default.dim(`← ${pkg}`)}`);
3424
+ resultLines.push(` ${import_picocolors.default.dim(shortPath)}`);
3425
+ } else resultLines.push(`${import_picocolors.default.green("✓")} ${skillName} ${import_picocolors.default.dim(`← ${pkg}`)}`);
3426
+ }
3427
+ const skillCount = bySkill.size;
3428
+ const title = import_picocolors.default.green(`Synced ${skillCount} skill${skillCount !== 1 ? "s" : ""}`);
3429
+ Me(resultLines.join("\n"), title);
3430
+ }
3431
+ if (failed.length > 0) {
3432
+ console.log();
3433
+ M.error(import_picocolors.default.red(`Failed to install ${failed.length}`));
3434
+ for (const r of failed) M.message(` ${import_picocolors.default.red("✗")} ${r.skill} → ${r.agent}: ${import_picocolors.default.dim(r.error)}`);
3435
+ }
3436
+ track({
3437
+ event: "experimental_sync",
3438
+ skillCount: String(toInstall.length),
3439
+ successCount: String(successfulSkillNames.size),
3440
+ agents: targetAgents.join(",")
3441
+ });
3442
+ console.log();
3443
+ Se(import_picocolors.default.green("Done!") + import_picocolors.default.dim(" Review skills before use; they run with full agent permissions."));
3444
+ }
3445
+ function parseSyncOptions(args) {
3446
+ const options = {};
3447
+ for (let i = 0; i < args.length; i++) {
3448
+ const arg = args[i];
3449
+ if (arg === "-y" || arg === "--yes") options.yes = true;
3450
+ else if (arg === "-f" || arg === "--force") options.force = true;
3451
+ else if (arg === "-a" || arg === "--agent") {
3452
+ options.agent = options.agent || [];
3453
+ i++;
3454
+ let nextArg = args[i];
3455
+ while (i < args.length && nextArg && !nextArg.startsWith("-")) {
3456
+ options.agent.push(nextArg);
3457
+ i++;
3458
+ nextArg = args[i];
3459
+ }
3460
+ i--;
3461
+ }
3462
+ }
3463
+ return { options };
3464
+ }
3465
+ async function runInstallFromLock(args) {
3466
+ const lock = await readLocalLock(process.cwd());
3467
+ const skillEntries = Object.entries(lock.skills);
3468
+ if (skillEntries.length === 0) {
3469
+ M.warn("No project skills found in skills-lock.json");
3470
+ M.info(`Add project-level skills with ${import_picocolors.default.cyan("npx skpm-cli add <package>")} (without ${import_picocolors.default.cyan("-g")})`);
3471
+ return;
3472
+ }
3473
+ const universalAgentNames = getUniversalAgents();
3474
+ const nodeModuleSkills = [];
3475
+ const bySource = /* @__PURE__ */ new Map();
3476
+ for (const [skillName, entry] of skillEntries) {
3477
+ if (entry.sourceType === "node_modules") {
3478
+ nodeModuleSkills.push(skillName);
3479
+ continue;
3480
+ }
3481
+ const existing = bySource.get(entry.source);
3482
+ if (existing) existing.skills.push(skillName);
3483
+ else bySource.set(entry.source, {
3484
+ sourceType: entry.sourceType,
3485
+ skills: [skillName]
3486
+ });
3487
+ }
3488
+ const remoteCount = skillEntries.length - nodeModuleSkills.length;
3489
+ if (remoteCount > 0) M.info(`Restoring ${import_picocolors.default.cyan(String(remoteCount))} skill${remoteCount !== 1 ? "s" : ""} from skills-lock.json into ${import_picocolors.default.dim(".agents/skills/")}`);
3490
+ for (const [source, { skills }] of bySource) try {
3491
+ await runAdd([source], {
3492
+ skill: skills,
3493
+ agent: universalAgentNames,
3494
+ yes: true
3495
+ });
3496
+ } catch (error) {
3497
+ M.error(`Failed to install from ${import_picocolors.default.cyan(source)}: ${error instanceof Error ? error.message : "Unknown error"}`);
3498
+ }
3499
+ if (nodeModuleSkills.length > 0) {
3500
+ M.info(`${import_picocolors.default.cyan(String(nodeModuleSkills.length))} skill${nodeModuleSkills.length !== 1 ? "s" : ""} from node_modules`);
3501
+ try {
3502
+ const { options: syncOptions } = parseSyncOptions(args);
3503
+ await runSync(args, {
3504
+ ...syncOptions,
3505
+ yes: true,
3506
+ agent: universalAgentNames
3507
+ });
3508
+ } catch (error) {
3509
+ M.error(`Failed to sync node_modules skills: ${error instanceof Error ? error.message : "Unknown error"}`);
3510
+ }
3511
+ }
3512
+ }
3513
+ const RESET$1 = "\x1B[0m";
3514
+ const BOLD$1 = "\x1B[1m";
3515
+ const DIM$1 = "\x1B[38;5;102m";
3516
+ const CYAN = "\x1B[36m";
3517
+ const YELLOW = "\x1B[33m";
3518
+ function shortenPath(fullPath, cwd) {
3519
+ const home = homedir();
3520
+ if (fullPath.startsWith(home)) return fullPath.replace(home, "~");
3521
+ if (fullPath.startsWith(cwd)) return "." + fullPath.slice(cwd.length);
3522
+ return fullPath;
3523
+ }
3524
+ function formatList(items, maxShow = 5) {
3525
+ if (items.length <= maxShow) return items.join(", ");
3526
+ const shown = items.slice(0, maxShow);
3527
+ const remaining = items.length - maxShow;
3528
+ return `${shown.join(", ")} +${remaining} more`;
3529
+ }
3530
+ function parseListOptions(args) {
3531
+ const options = {};
3532
+ for (let i = 0; i < args.length; i++) {
3533
+ const arg = args[i];
3534
+ if (arg === "-g" || arg === "--global") options.global = true;
3535
+ else if (arg === "--json") options.json = true;
3536
+ else if (arg === "-a" || arg === "--agent") {
3537
+ options.agent = options.agent || [];
3538
+ while (i + 1 < args.length && !args[i + 1].startsWith("-")) options.agent.push(args[++i]);
3539
+ }
3540
+ }
3541
+ return options;
3542
+ }
3543
+ async function runList(args) {
3544
+ const options = parseListOptions(args);
3545
+ const scope = options.global === true ? true : false;
3546
+ let agentFilter;
3547
+ if (options.agent && options.agent.length > 0) {
3548
+ const validAgents = Object.keys(agents);
3549
+ const invalidAgents = options.agent.filter((a) => !validAgents.includes(a));
3550
+ if (invalidAgents.length > 0) {
3551
+ console.log(`${YELLOW}Invalid agents: ${invalidAgents.join(", ")}${RESET$1}`);
3552
+ console.log(`${DIM$1}Valid agents: ${validAgents.join(", ")}${RESET$1}`);
3553
+ process.exit(1);
3554
+ }
3555
+ agentFilter = options.agent;
3556
+ }
3557
+ const installedSkills = await listInstalledSkills({
3558
+ global: scope,
3559
+ agentFilter
3560
+ });
3561
+ if (options.json) {
3562
+ const jsonOutput = installedSkills.map((skill) => ({
3563
+ name: skill.name,
3564
+ path: skill.canonicalPath,
3565
+ scope: skill.scope,
3566
+ agents: skill.agents.map((a) => agents[a].displayName)
3567
+ }));
3568
+ console.log(JSON.stringify(jsonOutput, null, 2));
3569
+ return;
3570
+ }
3571
+ const lockedSkills = await getAllLockedSkills();
3572
+ const cwd = process.cwd();
3573
+ const scopeLabel = scope ? "Global" : "Project";
3574
+ if (installedSkills.length === 0) {
3575
+ if (options.json) {
3576
+ console.log("[]");
3577
+ return;
3578
+ }
3579
+ console.log(`${DIM$1}No ${scopeLabel.toLowerCase()} skills found.${RESET$1}`);
3580
+ if (scope) console.log(`${DIM$1}Try listing project skills without -g${RESET$1}`);
3581
+ else console.log(`${DIM$1}Try listing global skills with -g${RESET$1}`);
3582
+ return;
3583
+ }
3584
+ function printSkill(skill, indent = false) {
3585
+ const prefix = indent ? " " : "";
3586
+ const shortPath = shortenPath(skill.canonicalPath, cwd);
3587
+ const agentNames = skill.agents.map((a) => agents[a].displayName);
3588
+ const agentInfo = skill.agents.length > 0 ? formatList(agentNames) : `${YELLOW}not linked${RESET$1}`;
3589
+ console.log(`${prefix}${CYAN}${skill.name}${RESET$1} ${DIM$1}${shortPath}${RESET$1}`);
3590
+ console.log(`${prefix} ${DIM$1}Agents:${RESET$1} ${agentInfo}`);
3591
+ }
3592
+ console.log(`${BOLD$1}${scopeLabel} Skills${RESET$1}`);
3593
+ console.log();
3594
+ const groupedSkills = {};
3595
+ const ungroupedSkills = [];
3596
+ for (const skill of installedSkills) {
3597
+ const lockEntry = lockedSkills[skill.name];
3598
+ if (lockEntry?.pluginName) {
3599
+ const group = lockEntry.pluginName;
3600
+ if (!groupedSkills[group]) groupedSkills[group] = [];
3601
+ groupedSkills[group].push(skill);
3602
+ } else ungroupedSkills.push(skill);
3603
+ }
3604
+ if (Object.keys(groupedSkills).length > 0) {
3605
+ const sortedGroups = Object.keys(groupedSkills).sort();
3606
+ for (const group of sortedGroups) {
3607
+ const title = group.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
3608
+ console.log(`${BOLD$1}${title}${RESET$1}`);
3609
+ const skills = groupedSkills[group];
3610
+ if (skills) for (const skill of skills) printSkill(skill, true);
3611
+ console.log();
3612
+ }
3613
+ if (ungroupedSkills.length > 0) {
3614
+ console.log(`${BOLD$1}General${RESET$1}`);
3615
+ for (const skill of ungroupedSkills) printSkill(skill, true);
3616
+ console.log();
3617
+ }
3618
+ } else {
3619
+ for (const skill of installedSkills) printSkill(skill);
3620
+ console.log();
3621
+ }
3622
+ }
3623
+ async function removeCommand(skillNames, options) {
3624
+ const isGlobal = options.global ?? false;
3625
+ const cwd = process.cwd();
3626
+ const spinner = Y();
3627
+ spinner.start("Scanning for installed skills...");
3628
+ const skillNamesSet = /* @__PURE__ */ new Set();
3629
+ const scanDir = async (dir) => {
3630
+ try {
3631
+ const entries = await readdir(dir, { withFileTypes: true });
3632
+ for (const entry of entries) if (entry.isDirectory()) skillNamesSet.add(entry.name);
3633
+ } catch (err) {
3634
+ if (err instanceof Error && err.code !== "ENOENT") M.warn(`Could not scan directory ${dir}: ${err.message}`);
3635
+ }
3636
+ };
3637
+ if (isGlobal) {
3638
+ await scanDir(getCanonicalSkillsDir(true, cwd));
3639
+ for (const agent of Object.values(agents)) if (agent.globalSkillsDir !== void 0) await scanDir(agent.globalSkillsDir);
3640
+ } else {
3641
+ await scanDir(getCanonicalSkillsDir(false, cwd));
3642
+ for (const agent of Object.values(agents)) await scanDir(join(cwd, agent.skillsDir));
3643
+ }
3644
+ const installedSkills = Array.from(skillNamesSet).sort();
3645
+ spinner.stop(`Found ${installedSkills.length} unique installed skill(s)`);
3646
+ if (installedSkills.length === 0) {
3647
+ Se(import_picocolors.default.yellow("No skills found to remove."));
3648
+ return;
3649
+ }
3650
+ if (options.agent && options.agent.length > 0) {
3651
+ const validAgents = Object.keys(agents);
3652
+ const invalidAgents = options.agent.filter((a) => !validAgents.includes(a));
3653
+ if (invalidAgents.length > 0) {
3654
+ M.error(`Invalid agents: ${invalidAgents.join(", ")}`);
3655
+ M.info(`Valid agents: ${validAgents.join(", ")}`);
3656
+ process.exit(1);
3657
+ }
3658
+ }
3659
+ let selectedSkills = [];
3660
+ if (options.all) selectedSkills = installedSkills;
3661
+ else if (skillNames.length > 0) {
3662
+ selectedSkills = installedSkills.filter((s) => skillNames.some((name) => name.toLowerCase() === s.toLowerCase()));
3663
+ if (selectedSkills.length === 0) {
3664
+ M.error(`No matching skills found for: ${skillNames.join(", ")}`);
3665
+ return;
3666
+ }
3667
+ } else {
3668
+ const choices = installedSkills.map((s) => ({
3669
+ value: s,
3670
+ label: s
3671
+ }));
3672
+ const selected = await fe({
3673
+ message: `Select skills to remove ${import_picocolors.default.dim("(space to toggle)")}`,
3674
+ options: choices,
3675
+ required: true
3676
+ });
3677
+ if (pD(selected)) {
3678
+ xe("Removal cancelled");
3679
+ process.exit(0);
3680
+ }
3681
+ selectedSkills = selected;
3682
+ }
3683
+ let targetAgents;
3684
+ if (options.agent && options.agent.length > 0) targetAgents = options.agent;
3685
+ else {
3686
+ targetAgents = Object.keys(agents);
3687
+ spinner.stop(`Targeting ${targetAgents.length} potential agent(s)`);
3688
+ }
3689
+ if (!options.yes) {
3690
+ console.log();
3691
+ M.info("Skills to remove:");
3692
+ for (const skill of selectedSkills) M.message(` ${import_picocolors.default.red("•")} ${skill}`);
3693
+ console.log();
3694
+ const confirmed = await ye({ message: `Are you sure you want to uninstall ${selectedSkills.length} skill(s)?` });
3695
+ if (pD(confirmed) || !confirmed) {
3696
+ xe("Removal cancelled");
3697
+ process.exit(0);
3698
+ }
3699
+ }
3700
+ spinner.start("Removing skills...");
3701
+ const results = [];
3702
+ for (const skillName of selectedSkills) try {
3703
+ const canonicalPath = getCanonicalPath(skillName, {
3704
+ global: isGlobal,
3705
+ cwd
3706
+ });
3707
+ for (const agentKey of targetAgents) {
3708
+ const agent = agents[agentKey];
3709
+ const skillPath = getInstallPath(skillName, agentKey, {
3710
+ global: isGlobal,
3711
+ cwd
3712
+ });
3713
+ const pathsToCleanup = new Set([skillPath]);
3714
+ const sanitizedName = sanitizeName(skillName);
3715
+ if (isGlobal && agent.globalSkillsDir) pathsToCleanup.add(join(agent.globalSkillsDir, sanitizedName));
3716
+ else pathsToCleanup.add(join(cwd, agent.skillsDir, sanitizedName));
3717
+ for (const pathToCleanup of pathsToCleanup) {
3718
+ if (pathToCleanup === canonicalPath) continue;
3719
+ try {
3720
+ if (await lstat(pathToCleanup).catch(() => null)) await rm(pathToCleanup, {
3721
+ recursive: true,
3722
+ force: true
3723
+ });
3724
+ } catch (err) {
3725
+ M.warn(`Could not remove skill from ${agent.displayName}: ${err instanceof Error ? err.message : String(err)}`);
3726
+ }
3727
+ }
3728
+ }
3729
+ const remainingAgents = (await detectInstalledAgents()).filter((a) => !targetAgents.includes(a));
3730
+ let isStillUsed = false;
3731
+ for (const agentKey of remainingAgents) if (await lstat(getInstallPath(skillName, agentKey, {
3732
+ global: isGlobal,
3733
+ cwd
3734
+ })).catch(() => null)) {
3735
+ isStillUsed = true;
3736
+ break;
3737
+ }
3738
+ if (!isStillUsed) await rm(canonicalPath, {
3739
+ recursive: true,
3740
+ force: true
3741
+ });
3742
+ const lockEntry = isGlobal ? await getSkillFromLock(skillName) : null;
3743
+ const effectiveSource = lockEntry?.source || "local";
3744
+ const effectiveSourceType = lockEntry?.sourceType || "local";
3745
+ if (isGlobal) await removeSkillFromLock(skillName);
3746
+ results.push({
3747
+ skill: skillName,
3748
+ success: true,
3749
+ source: effectiveSource,
3750
+ sourceType: effectiveSourceType
3751
+ });
3752
+ } catch (err) {
3753
+ results.push({
3754
+ skill: skillName,
3755
+ success: false,
3756
+ error: err instanceof Error ? err.message : String(err)
3757
+ });
3758
+ }
3759
+ spinner.stop("Removal process complete");
3760
+ const successful = results.filter((r) => r.success);
3761
+ const failed = results.filter((r) => !r.success);
3762
+ if (successful.length > 0) {
3763
+ const bySource = /* @__PURE__ */ new Map();
3764
+ for (const r of successful) {
3765
+ const source = r.source || "local";
3766
+ const existing = bySource.get(source) || { skills: [] };
3767
+ existing.skills.push(r.skill);
3768
+ existing.sourceType = r.sourceType;
3769
+ bySource.set(source, existing);
3770
+ }
3771
+ for (const [source, data] of bySource) track({
3772
+ event: "remove",
3773
+ source,
3774
+ skills: data.skills.join(","),
3775
+ agents: targetAgents.join(","),
3776
+ ...isGlobal && { global: "1" },
3777
+ sourceType: data.sourceType
3778
+ });
3779
+ }
3780
+ if (successful.length > 0) M.success(import_picocolors.default.green(`Successfully removed ${successful.length} skill(s)`));
3781
+ if (failed.length > 0) {
3782
+ M.error(import_picocolors.default.red(`Failed to remove ${failed.length} skill(s)`));
3783
+ for (const r of failed) M.message(` ${import_picocolors.default.red("✗")} ${r.skill}: ${r.error}`);
3784
+ }
3785
+ console.log();
3786
+ Se(import_picocolors.default.green("Done!"));
3787
+ }
3788
+ function parseRemoveOptions(args) {
3789
+ const options = {};
3790
+ const skills = [];
3791
+ for (let i = 0; i < args.length; i++) {
3792
+ const arg = args[i];
3793
+ if (arg === "-g" || arg === "--global") options.global = true;
3794
+ else if (arg === "-y" || arg === "--yes") options.yes = true;
3795
+ else if (arg === "--all") options.all = true;
3796
+ else if (arg === "-a" || arg === "--agent") {
3797
+ options.agent = options.agent || [];
3798
+ i++;
3799
+ let nextArg = args[i];
3800
+ while (i < args.length && nextArg && !nextArg.startsWith("-")) {
3801
+ options.agent.push(nextArg);
3802
+ i++;
3803
+ nextArg = args[i];
3804
+ }
3805
+ i--;
3806
+ } else if (arg && !arg.startsWith("-")) skills.push(arg);
3807
+ }
3808
+ return {
3809
+ skills,
3810
+ options
3811
+ };
3812
+ }
3813
+ const __dirname = dirname(fileURLToPath(import.meta.url));
3814
+ function getVersion() {
3815
+ try {
3816
+ const pkgPath = join(__dirname, "..", "package.json");
3817
+ return JSON.parse(readFileSync(pkgPath, "utf-8")).version;
3818
+ } catch {
3819
+ return "0.0.0";
3820
+ }
3821
+ }
3822
+ const VERSION = getVersion();
3823
+ initTelemetry(VERSION);
3824
+ const RESET = "\x1B[0m";
3825
+ const BOLD = "\x1B[1m";
3826
+ const DIM = "\x1B[38;5;102m";
3827
+ const TEXT = "\x1B[38;5;145m";
3828
+ const LOGO_LINES = [
3829
+ "███████╗██╗ ██╗██████╗ ███╗ ███╗",
3830
+ "██╔════╝██║ ██╔╝██╔══██╗████╗ ████║",
3831
+ "███████╗█████╔╝ ██████╔╝██╔████╔██║",
3832
+ "╚════██║██╔═██╗ ██╔═══╝ ██║╚██╔╝██║",
3833
+ "███████║██║ ██╗██║ ██║ ╚═╝ ██║",
3834
+ "╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝"
3835
+ ];
3836
+ const GRAYS = [
3837
+ "\x1B[38;5;250m",
3838
+ "\x1B[38;5;248m",
3839
+ "\x1B[38;5;245m",
3840
+ "\x1B[38;5;243m",
3841
+ "\x1B[38;5;240m",
3842
+ "\x1B[38;5;238m"
3843
+ ];
3844
+ function showLogo() {
3845
+ console.log();
3846
+ LOGO_LINES.forEach((line, i) => {
3847
+ console.log(`${GRAYS[i]}${line}${RESET}`);
3848
+ });
3849
+ }
3850
+ function showBanner() {
3851
+ showLogo();
3852
+ console.log();
3853
+ console.log(`${DIM}The Skill Package Manager for AI Agents${RESET}`);
3854
+ console.log();
3855
+ console.log(` ${DIM}$${RESET} ${TEXT}skpm add ${DIM}<package>${RESET} ${DIM}Add a new skill${RESET}`);
3856
+ console.log(` ${DIM}$${RESET} ${TEXT}skpm remove${RESET} ${DIM}Remove installed skills${RESET}`);
3857
+ console.log(` ${DIM}$${RESET} ${TEXT}skpm list${RESET} ${DIM}List installed skills${RESET}`);
3858
+ console.log(` ${DIM}$${RESET} ${TEXT}skpm find ${DIM}[query]${RESET} ${DIM}Search for skills${RESET}`);
3859
+ console.log();
3860
+ console.log(` ${DIM}$${RESET} ${TEXT}skpm check${RESET} ${DIM}Check for updates${RESET}`);
3861
+ console.log(` ${DIM}$${RESET} ${TEXT}skpm update${RESET} ${DIM}Update all skills${RESET}`);
3862
+ console.log();
3863
+ console.log(` ${DIM}$${RESET} ${TEXT}skpm experimental_install${RESET} ${DIM}Restore from skills-lock.json${RESET}`);
3864
+ console.log(` ${DIM}$${RESET} ${TEXT}skpm init ${DIM}[name]${RESET} ${DIM}Create a new skill${RESET}`);
3865
+ console.log(` ${DIM}$${RESET} ${TEXT}skpm experimental_sync${RESET} ${DIM}Sync skills from node_modules${RESET}`);
3866
+ console.log();
3867
+ console.log(`${DIM}try:${RESET} skpm add vercel-labs/agent-skills`);
3868
+ console.log();
3869
+ console.log(`Discover more skills at ${TEXT}https://skpm.sh/${RESET}`);
3870
+ console.log();
3871
+ }
3872
+ function showHelp() {
3873
+ console.log(`
3874
+ ${BOLD}Usage:${RESET} skpm <command> [options]
3875
+
3876
+ ${BOLD}Manage Skills:${RESET}
3877
+ add <package> Add a skill package (alias: a)
3878
+ e.g. vercel-labs/agent-skills
3879
+ https://github.com/vercel-labs/agent-skills
3880
+ remove [skills] Remove installed skills
3881
+ list, ls List installed skills
3882
+ find [query] Search for skills interactively
3883
+
3884
+ ${BOLD}Updates:${RESET}
3885
+ check Check for available skill updates
3886
+ update Update all skills to latest versions
3887
+
3888
+ ${BOLD}Project:${RESET}
3889
+ experimental_install Restore skills from skills-lock.json
3890
+ init [name] Initialize a skill (creates <name>/SKILL.md or ./SKILL.md)
3891
+ experimental_sync Sync skills from node_modules into agent directories
3892
+
3893
+ ${BOLD}Add Options:${RESET}
3894
+ -g, --global Install skill globally (user-level) instead of project-level
3895
+ -a, --agent <agents> Specify agents to install to (use '*' for all agents)
3896
+ -s, --skill <skills> Specify skill names to install (use '*' for all skills)
3897
+ -l, --list List available skills in the repository without installing
3898
+ -y, --yes Skip confirmation prompts
3899
+ --copy Copy files instead of symlinking to agent directories
3900
+ --all Shorthand for --skill '*' --agent '*' -y
3901
+ --full-depth Search all subdirectories even when a root SKILL.md exists
3902
+ --trust-scripts Auto-run postInstall commands without prompting
3903
+
3904
+ ${BOLD}Remove Options:${RESET}
3905
+ -g, --global Remove from global scope
3906
+ -a, --agent <agents> Remove from specific agents (use '*' for all agents)
3907
+ -s, --skill <skills> Specify skills to remove (use '*' for all skills)
3908
+ -y, --yes Skip confirmation prompts
3909
+ --all Shorthand for --skill '*' --agent '*' -y
3910
+
3911
+ ${BOLD}Experimental Sync Options:${RESET}
3912
+ -a, --agent <agents> Specify agents to install to (use '*' for all agents)
3913
+ -y, --yes Skip confirmation prompts
3914
+
3915
+ ${BOLD}List Options:${RESET}
3916
+ -g, --global List global skills (default: project)
3917
+ -a, --agent <agents> Filter by specific agents
3918
+ --json Output as JSON (machine-readable, no ANSI codes)
3919
+
3920
+ ${BOLD}Options:${RESET}
3921
+ --help, -h Show this help message
3922
+ --version, -v Show version number
3923
+
3924
+ ${BOLD}Examples:${RESET}
3925
+ ${DIM}$${RESET} skpm add vercel-labs/agent-skills
3926
+ ${DIM}$${RESET} skpm add vercel-labs/agent-skills -g
3927
+ ${DIM}$${RESET} skpm add vercel-labs/agent-skills --agent claude-code cursor
3928
+ ${DIM}$${RESET} skpm add vercel-labs/agent-skills --skill pr-review commit
3929
+ ${DIM}$${RESET} skpm remove ${DIM}# interactive remove${RESET}
3930
+ ${DIM}$${RESET} skpm remove web-design ${DIM}# remove by name${RESET}
3931
+ ${DIM}$${RESET} skpm rm --global frontend-design
3932
+ ${DIM}$${RESET} skpm list ${DIM}# list project skills${RESET}
3933
+ ${DIM}$${RESET} skpm ls -g ${DIM}# list global skills${RESET}
3934
+ ${DIM}$${RESET} skpm ls -a claude-code ${DIM}# filter by agent${RESET}
3935
+ ${DIM}$${RESET} skpm ls --json ${DIM}# JSON output${RESET}
3936
+ ${DIM}$${RESET} skpm find ${DIM}# interactive search${RESET}
3937
+ ${DIM}$${RESET} skpm find typescript ${DIM}# search by keyword${RESET}
3938
+ ${DIM}$${RESET} skpm check
3939
+ ${DIM}$${RESET} skpm update
3940
+ ${DIM}$${RESET} skpm experimental_install ${DIM}# restore from skills-lock.json${RESET}
3941
+ ${DIM}$${RESET} skpm init my-skill
3942
+ ${DIM}$${RESET} skpm experimental_sync ${DIM}# sync from node_modules${RESET}
3943
+ ${DIM}$${RESET} skpm experimental_sync -y ${DIM}# sync without prompts${RESET}
3944
+
3945
+ Discover more skills at ${TEXT}https://skpm.sh/${RESET}
3946
+ `);
3947
+ }
3948
+ function showRemoveHelp() {
3949
+ console.log(`
3950
+ ${BOLD}Usage:${RESET} skpm remove [skills...] [options]
3951
+
3952
+ ${BOLD}Description:${RESET}
3953
+ Remove installed skills from agents. If no skill names are provided,
3954
+ an interactive selection menu will be shown.
3955
+
3956
+ ${BOLD}Arguments:${RESET}
3957
+ skills Optional skill names to remove (space-separated)
3958
+
3959
+ ${BOLD}Options:${RESET}
3960
+ -g, --global Remove from global scope (~/) instead of project scope
3961
+ -a, --agent Remove from specific agents (use '*' for all agents)
3962
+ -s, --skill Specify skills to remove (use '*' for all skills)
3963
+ -y, --yes Skip confirmation prompts
3964
+ --all Shorthand for --skill '*' --agent '*' -y
3965
+
3966
+ ${BOLD}Examples:${RESET}
3967
+ ${DIM}$${RESET} skpm remove ${DIM}# interactive selection${RESET}
3968
+ ${DIM}$${RESET} skpm remove my-skill ${DIM}# remove specific skill${RESET}
3969
+ ${DIM}$${RESET} skpm remove skill1 skill2 -y ${DIM}# remove multiple skills${RESET}
3970
+ ${DIM}$${RESET} skpm remove --global my-skill ${DIM}# remove from global scope${RESET}
3971
+ ${DIM}$${RESET} skpm rm --agent claude-code my-skill ${DIM}# remove from specific agent${RESET}
3972
+ ${DIM}$${RESET} skpm remove --all ${DIM}# remove all skills${RESET}
3973
+ ${DIM}$${RESET} skpm remove --skill '*' -a cursor ${DIM}# remove all skills from cursor${RESET}
3974
+
3975
+ Discover more skills at ${TEXT}https://skpm.sh/${RESET}
3976
+ `);
3977
+ }
3978
+ function runInit(args) {
3979
+ const cwd = process.cwd();
3980
+ const skillName = args[0] || basename(cwd);
3981
+ const hasName = args[0] !== void 0;
3982
+ const skillDir = hasName ? join(cwd, skillName) : cwd;
3983
+ const skillFile = join(skillDir, "SKILL.md");
3984
+ const displayPath = hasName ? `${skillName}/SKILL.md` : "SKILL.md";
3985
+ if (existsSync(skillFile)) {
3986
+ console.log(`${TEXT}Skill already exists at ${DIM}${displayPath}${RESET}`);
3987
+ return;
3988
+ }
3989
+ if (hasName) mkdirSync(skillDir, { recursive: true });
3990
+ writeFileSync(skillFile, `---
3991
+ name: ${skillName}
3992
+ description: A brief description of what this skill does
3993
+ ---
3994
+
3995
+ # ${skillName}
3996
+
3997
+ Instructions for the agent to follow when this skill is activated.
3998
+
3999
+ ## When to use
4000
+
4001
+ Describe when this skill should be used.
4002
+
4003
+ ## Instructions
4004
+
4005
+ 1. First step
4006
+ 2. Second step
4007
+ 3. Additional steps as needed
4008
+ `);
4009
+ console.log(`${TEXT}Initialized skill: ${DIM}${skillName}${RESET}`);
4010
+ console.log();
4011
+ console.log(`${DIM}Created:${RESET}`);
4012
+ console.log(` ${displayPath}`);
4013
+ console.log();
4014
+ console.log(`${DIM}Next steps:${RESET}`);
4015
+ console.log(` 1. Edit ${TEXT}${displayPath}${RESET} to define your skill instructions`);
4016
+ console.log(` 2. Update the ${TEXT}name${RESET} and ${TEXT}description${RESET} in the frontmatter`);
4017
+ console.log();
4018
+ console.log(`${DIM}Publishing:${RESET}`);
4019
+ console.log(` ${DIM}GitHub:${RESET} Push to a repo, then ${TEXT}npx skpm-cli add <owner>/<repo>${RESET}`);
4020
+ console.log(` ${DIM}URL:${RESET} Host the file, then ${TEXT}npx skpm-cli add https://example.com/${displayPath}${RESET}`);
4021
+ console.log();
4022
+ console.log(`Browse existing skills for inspiration at ${TEXT}https://skpm.sh/${RESET}`);
4023
+ console.log();
4024
+ }
4025
+ const AGENTS_DIR = ".agents";
4026
+ const LOCK_FILE = ".skill-lock.json";
4027
+ const CURRENT_LOCK_VERSION = 3;
4028
+ function getSkillLockPath() {
4029
+ const xdgStateHome = process.env.XDG_STATE_HOME;
4030
+ if (xdgStateHome) return join(xdgStateHome, "skills", LOCK_FILE);
4031
+ return join(homedir(), AGENTS_DIR, LOCK_FILE);
4032
+ }
4033
+ function readSkillLock() {
4034
+ const lockPath = getSkillLockPath();
4035
+ try {
4036
+ const content = readFileSync(lockPath, "utf-8");
4037
+ const parsed = JSON.parse(content);
4038
+ if (typeof parsed.version !== "number" || !parsed.skills) return {
4039
+ version: CURRENT_LOCK_VERSION,
4040
+ skills: {}
4041
+ };
4042
+ if (parsed.version < CURRENT_LOCK_VERSION) return {
4043
+ version: CURRENT_LOCK_VERSION,
4044
+ skills: {}
4045
+ };
4046
+ return parsed;
4047
+ } catch {
4048
+ return {
4049
+ version: CURRENT_LOCK_VERSION,
4050
+ skills: {}
4051
+ };
4052
+ }
4053
+ }
4054
+ function getSkipReason(entry) {
4055
+ if (entry.sourceType === "local") return "Local path";
4056
+ if (entry.sourceType === "git") return "Git URL (hash tracking not supported)";
4057
+ if (!entry.skillFolderHash) return "No version hash available";
4058
+ if (!entry.skillPath) return "No skill path recorded";
4059
+ return "No version tracking";
4060
+ }
4061
+ function printSkippedSkills(skipped) {
4062
+ if (skipped.length === 0) return;
4063
+ console.log();
4064
+ console.log(`${DIM}${skipped.length} skill(s) cannot be checked automatically:${RESET}`);
4065
+ for (const skill of skipped) {
4066
+ console.log(` ${TEXT}•${RESET} ${skill.name} ${DIM}(${skill.reason})${RESET}`);
4067
+ console.log(` ${DIM}To update: ${TEXT}npx skpm-cli add ${skill.sourceUrl} -g -y${RESET}`);
4068
+ }
4069
+ }
4070
+ async function runCheck(args = []) {
4071
+ console.log(`${TEXT}Checking for skill updates...${RESET}`);
4072
+ console.log();
4073
+ const lock = readSkillLock();
4074
+ const skillNames = Object.keys(lock.skills);
4075
+ if (skillNames.length === 0) {
4076
+ console.log(`${DIM}No skills tracked in lock file.${RESET}`);
4077
+ console.log(`${DIM}Install skills with${RESET} ${TEXT}npx skpm-cli add <package>${RESET}`);
4078
+ return;
4079
+ }
4080
+ const token = getGitHubToken();
4081
+ const skillsBySource = /* @__PURE__ */ new Map();
4082
+ const skipped = [];
4083
+ for (const skillName of skillNames) {
4084
+ const entry = lock.skills[skillName];
4085
+ if (!entry) continue;
4086
+ if (!entry.skillFolderHash || !entry.skillPath) {
4087
+ skipped.push({
4088
+ name: skillName,
4089
+ reason: getSkipReason(entry),
4090
+ sourceUrl: entry.sourceUrl
4091
+ });
4092
+ continue;
4093
+ }
4094
+ const existing = skillsBySource.get(entry.source) || [];
4095
+ existing.push({
4096
+ name: skillName,
4097
+ entry
4098
+ });
4099
+ skillsBySource.set(entry.source, existing);
4100
+ }
4101
+ const totalSkills = skillNames.length - skipped.length;
4102
+ if (totalSkills === 0) {
4103
+ console.log(`${DIM}No GitHub skills to check.${RESET}`);
4104
+ printSkippedSkills(skipped);
4105
+ return;
4106
+ }
4107
+ console.log(`${DIM}Checking ${totalSkills} skill(s) for updates...${RESET}`);
4108
+ const updates = [];
4109
+ const errors = [];
4110
+ for (const [source, skills] of skillsBySource) for (const { name, entry } of skills) try {
4111
+ const latestHash = await fetchSkillFolderHash(source, entry.skillPath, token);
4112
+ if (!latestHash) {
4113
+ errors.push({
4114
+ name,
4115
+ source,
4116
+ error: "Could not fetch from GitHub"
4117
+ });
4118
+ continue;
4119
+ }
4120
+ if (latestHash !== entry.skillFolderHash) updates.push({
4121
+ name,
4122
+ source
4123
+ });
4124
+ } catch (err) {
4125
+ errors.push({
4126
+ name,
4127
+ source,
4128
+ error: err instanceof Error ? err.message : "Unknown error"
4129
+ });
4130
+ }
4131
+ console.log();
4132
+ if (updates.length === 0) console.log(`${TEXT}✓ All skills are up to date${RESET}`);
4133
+ else {
4134
+ console.log(`${TEXT}${updates.length} update(s) available:${RESET}`);
4135
+ console.log();
4136
+ for (const update of updates) {
4137
+ console.log(` ${TEXT}↑${RESET} ${update.name}`);
4138
+ console.log(` ${DIM}source: ${update.source}${RESET}`);
4139
+ }
4140
+ console.log();
4141
+ console.log(`${DIM}Run${RESET} ${TEXT}npx skpm-cli update${RESET} ${DIM}to update all skills${RESET}`);
4142
+ }
4143
+ if (errors.length > 0) {
4144
+ console.log();
4145
+ console.log(`${DIM}Could not check ${errors.length} skill(s) (may need reinstall)${RESET}`);
4146
+ console.log();
4147
+ for (const error of errors) {
4148
+ console.log(` ${DIM}✗${RESET} ${error.name}`);
4149
+ console.log(` ${DIM}source: ${error.source}${RESET}`);
4150
+ }
4151
+ }
4152
+ printSkippedSkills(skipped);
4153
+ track({
4154
+ event: "check",
4155
+ skillCount: String(totalSkills),
4156
+ updatesAvailable: String(updates.length)
4157
+ });
4158
+ console.log();
4159
+ }
4160
+ async function runUpdate() {
4161
+ console.log(`${TEXT}Checking for skill updates...${RESET}`);
4162
+ console.log();
4163
+ const lock = readSkillLock();
4164
+ const skillNames = Object.keys(lock.skills);
4165
+ if (skillNames.length === 0) {
4166
+ console.log(`${DIM}No skills tracked in lock file.${RESET}`);
4167
+ console.log(`${DIM}Install skills with${RESET} ${TEXT}npx skpm-cli add <package>${RESET}`);
4168
+ return;
4169
+ }
4170
+ const token = getGitHubToken();
4171
+ const updates = [];
4172
+ const skipped = [];
4173
+ for (const skillName of skillNames) {
4174
+ const entry = lock.skills[skillName];
4175
+ if (!entry) continue;
4176
+ if (!entry.skillFolderHash || !entry.skillPath) {
4177
+ skipped.push({
4178
+ name: skillName,
4179
+ reason: getSkipReason(entry),
4180
+ sourceUrl: entry.sourceUrl
4181
+ });
4182
+ continue;
4183
+ }
4184
+ try {
4185
+ const latestHash = await fetchSkillFolderHash(entry.source, entry.skillPath, token);
4186
+ if (latestHash && latestHash !== entry.skillFolderHash) updates.push({
4187
+ name: skillName,
4188
+ source: entry.source,
4189
+ entry
4190
+ });
4191
+ } catch {}
4192
+ }
4193
+ if (skillNames.length - skipped.length === 0) {
4194
+ console.log(`${DIM}No skills to check.${RESET}`);
4195
+ printSkippedSkills(skipped);
4196
+ return;
4197
+ }
4198
+ if (updates.length === 0) {
4199
+ console.log(`${TEXT}✓ All skills are up to date${RESET}`);
4200
+ console.log();
4201
+ return;
4202
+ }
4203
+ console.log(`${TEXT}Found ${updates.length} update(s)${RESET}`);
4204
+ console.log();
4205
+ let successCount = 0;
4206
+ let failCount = 0;
4207
+ for (const update of updates) {
4208
+ console.log(`${TEXT}Updating ${update.name}...${RESET}`);
4209
+ let installUrl = update.entry.sourceUrl;
4210
+ if (update.entry.skillPath) {
4211
+ let skillFolder = update.entry.skillPath;
4212
+ if (skillFolder.endsWith("/SKILL.md")) skillFolder = skillFolder.slice(0, -9);
4213
+ else if (skillFolder.endsWith("SKILL.md")) skillFolder = skillFolder.slice(0, -8);
4214
+ if (skillFolder.endsWith("/")) skillFolder = skillFolder.slice(0, -1);
4215
+ installUrl = update.entry.sourceUrl.replace(/\.git$/, "").replace(/\/$/, "");
4216
+ installUrl = `${installUrl}/tree/main/${skillFolder}`;
4217
+ }
4218
+ const cliEntry = join(__dirname, "..", "bin", "cli.mjs");
4219
+ if (!existsSync(cliEntry)) {
4220
+ failCount++;
4221
+ console.log(` ${DIM}✗ Failed to update ${update.name}: CLI entrypoint not found at ${cliEntry}${RESET}`);
4222
+ continue;
4223
+ }
4224
+ if (spawnSync(process.execPath, [
4225
+ cliEntry,
4226
+ "add",
4227
+ installUrl,
4228
+ "-g",
4229
+ "-y"
4230
+ ], {
4231
+ stdio: [
4232
+ "inherit",
4233
+ "pipe",
4234
+ "pipe"
4235
+ ],
4236
+ encoding: "utf-8",
4237
+ shell: process.platform === "win32"
4238
+ }).status === 0) {
4239
+ successCount++;
4240
+ console.log(` ${TEXT}✓${RESET} Updated ${update.name}`);
4241
+ } else {
4242
+ failCount++;
4243
+ console.log(` ${DIM}✗ Failed to update ${update.name}${RESET}`);
4244
+ }
4245
+ }
4246
+ console.log();
4247
+ if (successCount > 0) console.log(`${TEXT}✓ Updated ${successCount} skill(s)${RESET}`);
4248
+ if (failCount > 0) console.log(`${DIM}Failed to update ${failCount} skill(s)${RESET}`);
4249
+ track({
4250
+ event: "update",
4251
+ skillCount: String(updates.length),
4252
+ successCount: String(successCount),
4253
+ failCount: String(failCount)
4254
+ });
4255
+ console.log();
4256
+ }
4257
+ async function main() {
4258
+ const args = process.argv.slice(2);
4259
+ if (args.length === 0) {
4260
+ showBanner();
4261
+ return;
4262
+ }
4263
+ const command = args[0];
4264
+ const restArgs = args.slice(1);
4265
+ switch (command) {
4266
+ case "find":
4267
+ case "search":
4268
+ case "f":
4269
+ case "s":
4270
+ showLogo();
4271
+ console.log();
4272
+ await runFind(restArgs);
4273
+ break;
4274
+ case "init":
4275
+ showLogo();
4276
+ console.log();
4277
+ runInit(restArgs);
4278
+ break;
4279
+ case "experimental_install":
4280
+ showLogo();
4281
+ await runInstallFromLock(restArgs);
4282
+ break;
4283
+ case "i":
4284
+ case "install":
4285
+ case "a":
4286
+ case "add": {
4287
+ showLogo();
4288
+ const { source: addSource, options: addOpts } = parseAddOptions(restArgs);
4289
+ await runAdd(addSource, addOpts);
4290
+ break;
4291
+ }
4292
+ case "remove":
4293
+ case "rm":
4294
+ case "r":
4295
+ if (restArgs.includes("--help") || restArgs.includes("-h")) {
4296
+ showRemoveHelp();
4297
+ break;
4298
+ }
4299
+ const { skills, options: removeOptions } = parseRemoveOptions(restArgs);
4300
+ await removeCommand(skills, removeOptions);
4301
+ break;
4302
+ case "experimental_sync": {
4303
+ showLogo();
4304
+ const { options: syncOptions } = parseSyncOptions(restArgs);
4305
+ await runSync(restArgs, syncOptions);
4306
+ break;
4307
+ }
4308
+ case "list":
4309
+ case "ls":
4310
+ await runList(restArgs);
4311
+ break;
4312
+ case "check":
4313
+ runCheck(restArgs);
4314
+ break;
4315
+ case "update":
4316
+ case "upgrade":
4317
+ runUpdate();
4318
+ break;
4319
+ case "--help":
4320
+ case "-h":
4321
+ showHelp();
4322
+ break;
4323
+ case "--version":
4324
+ case "-v":
4325
+ console.log(VERSION);
4326
+ break;
4327
+ default:
4328
+ console.log(`Unknown command: ${command}`);
4329
+ console.log(`Run ${BOLD}skpm --help${RESET} for usage.`);
4330
+ }
4331
+ }
4332
+ main();
4333
+ export {};