@dgruzd/skills 1.4.3

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