@nostrify/skills 1.3.8

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