Repository navigation
Expand file tree
/
Copy pathadd.ts
More file actions
2503 lines (2227 loc) · 83.9 KB
/
Copy pathadd.ts
File metadata and controls
2503 lines (2227 loc) · 83.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as p from '@clack/prompts';
import pc from 'picocolors';
import { existsSync } from 'fs';
import { homedir } from 'os';
import { sep, join, dirname } from 'path';
import { parseSource, getOwnerRepo, parseOwnerRepo, isRepoPrivate } from './source-parser.ts';
import { stripTerminalEscapes } from './sanitize.ts';
import { searchMultiselect } from './prompts/search-multiselect.ts';
import { cloneRepo, cleanupTempDir, GitCloneError } from './git.ts';
import { discoverSkills, getSkillDisplayName, filterSkills } from './skills.ts';
import {
installSkillForAgent,
installBlobSkillForAgent,
isSkillInstalled,
getCanonicalPath,
installWellKnownSkillForAgent,
type InstallMode,
} from './installer.ts';
import {
detectInstalledAgents,
agents,
getUniversalAgents,
getVisibleUniversalAgents,
getNonUniversalAgents,
isUniversalAgent,
getEveSubagents,
} from './agents.ts';
import {
track,
setVersion,
fetchAuditData,
type AuditResponse,
type PartnerAudit,
} from './telemetry.ts';
import { detectAgent, getAgentType } from './detect-agent.ts';
import {
wellKnownProvider,
computeWellKnownSkillDigest,
WellKnownScopeNotFoundError,
type WellKnownSkill,
} from './providers/index.ts';
import { downloadSource } from './download-source.ts';
import {
addSkillToLock,
getGitHubToken,
isPromptDismissed,
dismissPrompt,
getLastSelectedAgents,
saveSelectedAgents,
} from './skill-lock.ts';
import { addSkillToLocalLock, computeSkillFolderHash } from './local-lock.ts';
import type { Skill, AgentType } from './types.ts';
import {
tryBlobInstall,
BLOB_ALLOWED_REPOS,
getSkillFolderHashFromTree,
fetchRepoTree,
type BlobSkill,
type BlobInstallResult,
} from './blob.ts';
import packageJson from '../package.json' with { type: 'json' };
import {
isNotionSource,
parseNotionSkillUrl,
prepareNotionPackSource,
prepareNotionSkillSource,
} from './notion-test.ts';
// Helper to check if a value is a cancel symbol (works with both clack and our custom prompts)
const isCancelled = (value: unknown): value is symbol => typeof value === 'symbol';
const EVE_AGENT_LABEL = 'eve agent';
/**
* Check if a source identifier (owner/repo format) represents a private GitHub repo.
* Returns true if private, false if public, null if unable to determine or not a GitHub repo.
*/
async function isSourcePrivate(source: string): Promise<boolean | null> {
const ownerRepo = parseOwnerRepo(source);
if (!ownerRepo) {
// Not in owner/repo format, assume not private (could be other providers)
return false;
}
return isRepoPrivate(ownerRepo.owner, ownerRepo.repo);
}
export function getLockSource(parsedUrl: string, normalizedSource: string | null): string | null {
// Preserve SSH URLs in lock files instead of normalizing to owner/repo shorthand.
// When normalizedSource is used, parseSource() later resolves it to HTTPS,
// breaking restore for private repos that require SSH authentication.
const isSSH = parsedUrl.startsWith('git@') || parsedUrl.startsWith('ssh://');
if (isSSH) {
return parsedUrl;
}
if (parsedUrl.startsWith('http://') || parsedUrl.startsWith('https://')) {
try {
if (new URL(parsedUrl).hostname !== 'github.com') {
return parsedUrl;
}
} catch {
return normalizedSource;
}
}
return normalizedSource;
}
export function getProjectLockSourceUrl(sourceType: string, sourceUrl: string): string | undefined {
return sourceType === 'git' || sourceType === 'gitlab' ? sourceUrl : undefined;
}
export function initTelemetry(version: string): void {
setVersion(version);
}
// ─── Security Advisory ───
function riskLabel(risk: string): string {
switch (risk) {
case 'critical':
return pc.red(pc.bold('Critical Risk'));
case 'high':
return pc.red('High Risk');
case 'medium':
return pc.yellow('Med Risk');
case 'low':
return pc.green('Low Risk');
case 'safe':
return pc.green('Safe');
default:
return pc.dim('--');
}
}
function socketLabel(audit: PartnerAudit | undefined): string {
if (!audit) return pc.dim('--');
const count = audit.alerts ?? 0;
return count > 0 ? pc.red(`${count} alert${count !== 1 ? 's' : ''}`) : pc.green('0 alerts');
}
/** Pad a string to a given visible width (ignoring ANSI escape codes). */
function padEnd(str: string, width: number): string {
// Strip ANSI codes to measure visible length
const visible = stripTerminalEscapes(str);
const pad = Math.max(0, width - visible.length);
return str + ' '.repeat(pad);
}
/**
* Render a compact security table showing partner audit results.
* Returns the lines to display, or empty array if no data.
*/
function buildSecurityLines(
auditData: AuditResponse | null,
skills: Array<{ slug: string; displayName: string }>,
source: string
): string[] {
if (!auditData) return [];
// Check if we have any audit data at all
const hasAny = skills.some((s) => {
const data = auditData[s.slug];
return data && Object.keys(data).length > 0;
});
if (!hasAny) return [];
// Compute column width for skill names
const nameWidth = Math.min(Math.max(...skills.map((s) => s.displayName.length)), 36);
// Header
const lines: string[] = [];
const header =
padEnd('', nameWidth + 2) +
padEnd(pc.dim('Gen'), 18) +
padEnd(pc.dim('Socket'), 18) +
pc.dim('Snyk');
lines.push(header);
// Rows
for (const skill of skills) {
const data = auditData[skill.slug];
const name =
skill.displayName.length > nameWidth
? skill.displayName.slice(0, nameWidth - 1) + '\u2026'
: skill.displayName;
const ath = data?.ath ? riskLabel(data.ath.risk) : pc.dim('--');
const socket = data?.socket ? socketLabel(data.socket) : pc.dim('--');
const snyk = data?.snyk ? riskLabel(data.snyk.risk) : pc.dim('--');
lines.push(padEnd(pc.cyan(name), nameWidth + 2) + padEnd(ath, 18) + padEnd(socket, 18) + snyk);
}
// Footer link
lines.push('');
lines.push(`${pc.dim('Details:')} ${pc.dim(`https://skills.sh/${source}`)}`);
return lines;
}
/**
* Shortens a path for display: replaces homedir with ~ and cwd with .
* Handles both Unix and Windows path separators.
*/
function shortenPath(fullPath: string, cwd: string): string {
const home = homedir();
// Ensure we match complete path segments by checking for separator after the prefix
if (fullPath === home || fullPath.startsWith(home + sep)) {
return '~' + fullPath.slice(home.length);
}
if (fullPath === cwd || fullPath.startsWith(cwd + sep)) {
return '.' + fullPath.slice(cwd.length);
}
return fullPath;
}
/**
* Formats a list of items, truncating if too many
*/
function formatList(items: string[], maxShow: number = 5): string {
if (items.length <= maxShow) {
return items.join(', ');
}
const shown = items.slice(0, maxShow);
const remaining = items.length - maxShow;
return `${shown.join(', ')} +${remaining} more`;
}
function formatSkillPromptSubject(skills: Skill[]): string {
const names = skills.map((skill) => pc.cyan(getSkillDisplayName(skill)));
const namedSubject = formatList(names, 3);
return stripTerminalEscapes(namedSubject).length <= 80
? namedSubject
: `${skills.length} selected skills`;
}
export function formatEveInstallPromptMessage(skills: Skill[]): string {
return `Detected an eve project. Install ${formatSkillPromptSubject(skills)} for your ${EVE_AGENT_LABEL} to use?`;
}
/**
* Splits agents into universal and non-universal (symlinked) groups.
* Returns display names for each group.
*/
function splitAgentsByType(agentTypes: AgentType[]): {
universal: string[];
symlinked: string[];
} {
const universal: string[] = [];
const symlinked: string[] = [];
for (const a of agentTypes) {
if (isUniversalAgent(a)) {
universal.push(agents[a].displayName);
} else {
symlinked.push(agents[a].displayName);
}
}
return { universal, symlinked };
}
/**
* Builds summary lines showing universal vs symlinked agents
*/
function buildAgentSummaryLines(targetAgents: AgentType[], installMode: InstallMode): string[] {
const lines: string[] = [];
const { universal, symlinked } = splitAgentsByType(targetAgents);
if (installMode === 'symlink') {
if (universal.length > 0) {
lines.push(` ${pc.green('universal:')} ${formatList(universal)}`);
}
if (symlinked.length > 0) {
lines.push(` ${pc.dim('symlink →')} ${formatList(symlinked)}`);
}
} else {
// Copy mode - all agents get copies
const allNames = targetAgents.map((a) => agents[a].displayName);
lines.push(` ${pc.dim('copy →')} ${formatList(allNames)}`);
}
return lines;
}
/**
* A concrete install destination. For Eve, `subagent` optionally targets a
* subagent's skills directory (`agent/subagents/<name>/skills`); when omitted
* the skill installs to the root agent (`agent/skills`). Other agents never set
* `subagent`.
*/
interface InstallTarget {
agent: AgentType;
subagent?: string;
}
/** Human-readable label for an install target, e.g. "Eve (research)". */
function targetDisplayName(target: InstallTarget): string {
const base = agents[target.agent].displayName;
return target.subagent ? `${base} (${target.subagent})` : base;
}
/** Stable key used to deduplicate / index per-target state. */
function targetKey(target: InstallTarget): string {
return target.subagent ? `${target.agent}:${target.subagent}` : target.agent;
}
/**
* Expand the selected agents into concrete install targets, fanning Eve out
* across the chosen subagents (root and/or named subagents).
*/
function buildInstallTargets(
targetAgents: AgentType[],
eveSubagentTargets: Array<string | undefined>
): InstallTarget[] {
const targets: InstallTarget[] = [];
for (const agent of targetAgents) {
if (agent === 'eve') {
for (const subagent of eveSubagentTargets) {
targets.push({ agent, subagent });
}
} else {
targets.push({ agent });
}
}
return targets;
}
/**
* Builds summary lines showing universal vs symlinked agents and Eve subagents.
*/
function buildTargetSummaryLines(targets: InstallTarget[], installMode: InstallMode): string[] {
const lines: string[] = [];
const rootAgents = targets.filter((t) => !t.subagent).map((t) => t.agent);
const subagentNames = targets.filter((t) => t.subagent).map(targetDisplayName);
const { universal, symlinked } = splitAgentsByType(rootAgents);
if (installMode === 'symlink') {
if (universal.length > 0) {
lines.push(` ${pc.green('universal:')} ${formatList(universal)}`);
}
if (symlinked.length > 0) {
lines.push(` ${pc.dim('symlink →')} ${formatList(symlinked)}`);
}
if (subagentNames.length > 0) {
lines.push(` ${pc.dim('copy →')} ${formatList(subagentNames)}`);
}
} else {
const allNames = targets.map(targetDisplayName);
lines.push(` ${pc.dim('copy →')} ${formatList(allNames)}`);
}
return lines;
}
/**
* Ensures universal agents are always included in the target agents list.
* Used when -y flag is passed or when auto-selecting agents.
*/
function ensureUniversalAgents(targetAgents: AgentType[]): AgentType[] {
const universalAgents = getUniversalAgents();
const result = [...targetAgents];
for (const ua of universalAgents) {
if (!result.includes(ua)) {
result.push(ua);
}
}
return result;
}
/**
* Builds result lines from installation results, splitting by universal vs symlinked
*/
function buildResultLines(
results: Array<{
agent: string;
symlinkFailed?: boolean;
skipped?: boolean;
skipReason?: string;
}>,
targetAgents: AgentType[]
): string[] {
const lines: string[] = [];
// Split target agents by type
const { universal, symlinked: symlinkAgents } = splitAgentsByType(targetAgents);
// For symlink results, also track which ones actually succeeded vs failed
// Exclude skipped agents (those whose config dir doesn't exist in the project)
const successfulSymlinks = results
.filter((r) => !r.symlinkFailed && !r.skipped && !universal.includes(r.agent))
.map((r) => r.agent);
const failedSymlinks = results.filter((r) => r.symlinkFailed && !r.skipped).map((r) => r.agent);
const skippedSymlinks = results
.filter(
(r) =>
r.skipped &&
r.skipReason === 'missing-agent-project-directory' &&
symlinkAgents.includes(r.agent)
)
.map((r) => r.agent);
if (universal.length > 0) {
lines.push(` ${pc.green('universal:')} ${formatList(universal)}`);
}
if (successfulSymlinks.length > 0) {
lines.push(` ${pc.dim('symlinked:')} ${formatList(successfulSymlinks)}`);
}
if (failedSymlinks.length > 0) {
lines.push(` ${pc.yellow('copied:')} ${formatList(failedSymlinks)}`);
}
if (skippedSymlinks.length > 0) {
lines.push(
` ${pc.yellow('skipped:')} ${formatList(skippedSymlinks)} ${pc.dim('(project directory not found)')}`
);
}
return lines;
}
/**
* Exit after an installation prompt was cancelled before anything was installed.
*
* Without a TTY the prompt cannot collect input at all: stdin EOF cancels it
* immediately. Exiting 0 there reports success to scripts and CI even though
* nothing was installed, so exit non-zero and point at the non-interactive
* flags instead. A deliberate interactive cancel still exits 0.
*/
function exitInstallationCancelled(): never {
p.cancel('Installation cancelled');
if (!process.stdin.isTTY) {
console.error(
'Interactive prompt required but stdin is not a TTY. Nothing was installed. ' +
`Use --agent <name> (or --agent '*') and -y to run non-interactively.`
);
process.exit(1);
}
process.exit(0);
}
/**
* Prompts the user to select agents using interactive search.
* Pre-selects the last used agents if available.
* Saves the selection for future use.
*/
export async function promptForAgents(
message: string,
choices: Array<{ value: AgentType; label: string; hint?: string }>
): Promise<AgentType[] | symbol> {
// Get last selected agents to pre-select
let lastSelected: string[] | undefined;
try {
lastSelected = await getLastSelectedAgents();
} catch {
// Silently ignore errors reading lock file
}
const validAgents = choices.map((c) => c.value);
// Default agents to pre-select when no valid history exists
const defaultAgents: AgentType[] = ['claude-code', 'opencode', 'codex'];
const defaultValues = defaultAgents.filter((a) => validAgents.includes(a));
let initialValues: AgentType[] = [];
if (lastSelected && lastSelected.length > 0) {
// Filter stored agents against currently valid agents
initialValues = lastSelected.filter((a) => validAgents.includes(a as AgentType)) as AgentType[];
}
// If no valid selection from history, use defaults
if (initialValues.length === 0) {
initialValues = defaultValues;
}
const selected = await searchMultiselect({
message,
items: choices,
initialSelected: initialValues,
required: true,
});
if (!isCancelled(selected)) {
// Save selection for next time
try {
await saveSelectedAgents(selected as string[]);
} catch {
// Silently ignore errors writing lock file
}
}
return selected as AgentType[] | symbol;
}
/**
* Interactive agent selection using fuzzy search.
* Shows universal agents as locked (always selected), and other agents as selectable.
*/
async function selectAgentsInteractive(options: {
global?: boolean;
}): Promise<AgentType[] | symbol> {
// Filter out agents that don't support global installation when --global is used
const supportsGlobalFilter = (a: AgentType) => !options.global || agents[a].globalSkillsDir;
const universalAgents = getUniversalAgents().filter(supportsGlobalFilter);
const visibleUniversalAgents = getVisibleUniversalAgents().filter(supportsGlobalFilter);
const otherAgents = getNonUniversalAgents().filter(
(agent) => agent !== 'eve' && supportsGlobalFilter(agent)
);
// Universal agents shown as locked section
const universalSection = {
title: 'Universal (.agents/skills)',
items: visibleUniversalAgents.map((a) => ({
value: a,
label: agents[a].displayName,
})),
hiddenCount: universalAgents.length - visibleUniversalAgents.length,
};
// Other agents are selectable with their skillsDir as hint
const otherChoices = otherAgents.map((a) => ({
value: a,
label: agents[a].displayName,
hint: options.global ? agents[a].globalSkillsDir! : agents[a].skillsDir,
}));
// Get last selected agents (filter to only non-universal ones for initial selection)
let lastSelected: string[] | undefined;
try {
lastSelected = await getLastSelectedAgents();
} catch {
// Silently ignore errors
}
const initialSelected = lastSelected
? (lastSelected.filter(
(a) => otherAgents.includes(a as AgentType) && !universalAgents.includes(a as AgentType)
) as AgentType[])
: [];
const selected = await searchMultiselect({
message: 'Which agents do you want to install to?',
items: otherChoices,
initialSelected,
lockedSection: universalSection,
});
if (!isCancelled(selected)) {
// Save selection (all agents including universal)
try {
await saveSelectedAgents(selected as string[]);
} catch {
// Silently ignore errors
}
}
return selected as AgentType[] | symbol;
}
const version = packageJson.version;
setVersion(version);
export interface AddOptions {
global?: boolean;
agent?: string[];
yes?: boolean;
skill?: string[];
/** Valid JSON to attach to the install telemetry event. */
metadata?: string;
list?: boolean;
all?: boolean;
fullDepth?: boolean;
copy?: boolean;
/**
* Eve subagent targets. Each value is a subagent name; `root` (or `.`)
* selects the root agent. Implies installing for Eve.
*/
subagent?: string[];
/** Output results as a JSON array (machine-readable, no ANSI codes). */
json?: boolean;
}
/** One entry per skill in `add --json` output. */
interface AddJsonResult {
name?: string;
status: 'installed' | 'skipped' | 'failed';
source?: string;
ref?: string | null;
hash?: string | null;
path?: string;
scope?: 'project' | 'global';
agents?: string[];
mode?: InstallMode;
security?: {
gen?: string;
socket?: string;
snyk?: string;
details?: string;
} | null;
reason?: string;
error?: string;
}
/** Build the `security` field for a JSON entry from partner audit data. */
function buildJsonSecurity(
auditData: AuditResponse | null,
skillName: string,
source: string | null
): AddJsonResult['security'] {
const data = auditData?.[skillName];
if (!data || Object.keys(data).length === 0) return null;
const socketAlerts = data.socket?.alerts ?? 0;
return {
...(data.ath && { gen: data.ath.risk }),
...(data.socket && { socket: `${socketAlerts} alert${socketAlerts !== 1 ? 's' : ''}` }),
...(data.snyk && { snyk: data.snyk.risk }),
...(source && { details: `https://skills.sh/${source}` }),
};
}
/**
* Handle skills from a well-known endpoint (RFC 8615).
* Discovers skills from /.well-known/agent-skills/index.json (preferred)
* or /.well-known/skills/index.json (legacy fallback).
*/
function isSkillsShPackUrl(url: string): boolean {
try {
const parsed = new URL(url);
const hostname = parsed.hostname.replace(/^www\./, '');
return hostname === 'skills.sh' && /^\/p\/[^/]+/.test(parsed.pathname);
} catch {
return false;
}
}
function logAutoSelectedSkills(entries: Array<{ label: string; description?: string }>): void {
const only = entries.length === 1 ? entries[0]! : null;
if (!only) {
p.log.info(`Installing all ${entries.length} skills`);
return;
}
p.log.info(`Skill: ${pc.cyan(only.label)}`);
if (only.description) p.log.message(pc.dim(only.description));
}
async function handleWellKnownSkills(
source: string,
url: string,
options: AddOptions,
spinner: ReturnType<typeof p.spinner>
): Promise<boolean> {
spinner.start('Discovering skills from well-known endpoint...');
// Fetch all skills from the well-known endpoint
let skills: WellKnownSkill[] = [];
try {
skills = await wellKnownProvider.fetchAllSkills(url, {
includeInternal: Boolean(
options.skill && options.skill.length > 0 && !options.skill.includes('*')
),
});
} catch (error) {
if (error instanceof WellKnownScopeNotFoundError) {
spinner.stop(pc.red('No matching skills'));
p.log.error(error.message);
process.exit(1);
}
}
if (skills.length === 0) {
spinner.stop(pc.dim('No well-known skills found; trying direct download...'));
return false;
}
spinner.stop(`Found ${pc.green(skills.length)} skill${skills.length > 1 ? 's' : ''}`);
// Log discovered skills
for (const skill of skills) {
p.log.info(`Skill: ${pc.cyan(skill.installName)}`);
p.log.message(pc.dim(skill.description));
if (skill.files.size > 1) {
p.log.message(pc.dim(` Files: ${Array.from(skill.files.keys()).join(', ')}`));
}
}
if (options.list) {
console.log();
p.log.step(pc.bold('Available Skills'));
for (const skill of skills) {
p.log.message(` ${pc.cyan(skill.installName)}`);
p.log.message(` ${pc.dim(skill.description)}`);
if (skill.files.size > 1) {
p.log.message(` ${pc.dim(`Files: ${skill.files.size}`)}`);
}
}
console.log();
p.outro('Run without --list to install');
process.exit(0);
}
// Filter skills if --skill option is provided
let selectedSkills: WellKnownSkill[];
const logWellKnown = (chosen: WellKnownSkill[]): void =>
logAutoSelectedSkills(
chosen.map((s) => ({ label: s.installName, description: s.description }))
);
if (options.skill?.includes('*')) {
// --skill '*' selects all skills
selectedSkills = skills;
logWellKnown(selectedSkills);
} else if (options.skill && options.skill.length > 0) {
selectedSkills = skills.filter((s) =>
options.skill!.some(
(name) =>
s.installName.toLowerCase() === name.toLowerCase() ||
s.name.toLowerCase() === name.toLowerCase()
)
);
if (selectedSkills.length === 0) {
p.log.error(`No matching skills found for: ${options.skill.join(', ')}`);
p.log.info('Available skills:');
for (const s of skills) {
p.log.message(` - ${s.installName}`);
}
process.exit(1);
}
} else if (skills.length === 1 || options.yes) {
selectedSkills = skills;
logWellKnown(selectedSkills);
} else {
// Prompt user to select skills
const skillChoices = skills.map((s) => ({
value: s,
label: s.installName,
hint: s.description.length > 60 ? s.description.slice(0, 57) + '…' : s.description,
}));
const selected = await searchMultiselect({
message: 'Select skills to install',
items: skillChoices,
initialSelected: isSkillsShPackUrl(url) ? skills : undefined,
required: true,
maxVisible: 20,
selectAll: true,
});
if (isCancelled(selected)) {
exitInstallationCancelled();
}
selectedSkills = selected as WellKnownSkill[];
}
// Detect agents
let targetAgents: AgentType[];
const validAgents = Object.keys(agents);
if (options.agent?.includes('*')) {
// --agent '*' selects all agents
targetAgents = validAgents as AgentType[];
p.log.info(`Installing to all ${targetAgents.length} agents`);
} else if (options.agent && options.agent.length > 0) {
const invalidAgents = options.agent.filter((a) => !validAgents.includes(a));
if (invalidAgents.length > 0) {
p.log.error(`Invalid agents: ${invalidAgents.join(', ')}`);
p.log.info(`Valid agents: ${validAgents.join(', ')}`);
process.exit(1);
}
targetAgents = options.agent as AgentType[];
} else {
spinner.start('Loading agents…');
const installedAgents = await detectInstalledAgents();
const totalAgents = Object.keys(agents).length;
spinner.stop(`${totalAgents} agents`);
if (installedAgents.length === 0) {
if (options.yes) {
targetAgents = validAgents as AgentType[];
p.log.info('Installing to all agents');
} else {
p.log.info('Select agents to install skills to');
const allAgentChoices = Object.entries(agents).map(([key, config]) => ({
value: key as AgentType,
label: config.displayName,
}));
// Use helper to prompt with search
const selected = await promptForAgents(
'Which agents do you want to install to?',
allAgentChoices
);
if (isCancelled(selected)) {
exitInstallationCancelled();
}
targetAgents = selected as AgentType[];
}
} else if (installedAgents.length === 1 || options.yes) {
// Auto-select detected agents + ensure universal agents are included
targetAgents = ensureUniversalAgents(installedAgents);
if (installedAgents.length === 1) {
const firstAgent = installedAgents[0]!;
p.log.info(`Installing to: ${pc.cyan(agents[firstAgent].displayName)}`);
} else {
p.log.info(
`Installing to: ${installedAgents.map((a) => pc.cyan(agents[a].displayName)).join(', ')}`
);
}
} else {
const selected = await selectAgentsInteractive({ global: options.global });
if (isCancelled(selected)) {
exitInstallationCancelled();
}
targetAgents = selected as AgentType[];
}
}
let installGlobally = options.global ?? false;
// Check if any selected agents support global installation
const supportsGlobal = targetAgents.some((a) => agents[a].globalSkillsDir !== undefined);
if (options.global === undefined && !options.yes && supportsGlobal) {
const scope = await p.select({
message: 'Installation scope',
options: [
{
value: false,
label: 'Project',
hint: 'Install in current directory (committed with your project)',
},
{
value: true,
label: 'Global',
hint: 'Install in home directory (available across all projects)',
},
],
});
if (p.isCancel(scope)) {
exitInstallationCancelled();
}
installGlobally = scope as boolean;
}
// Determine install mode (symlink vs copy)
let installMode: InstallMode = options.copy ? 'copy' : 'symlink';
// Only prompt for install mode when there are multiple unique target directories.
// When all selected agents share the same skillsDir, symlink vs copy is meaningless.
const uniqueDirs = new Set(targetAgents.map((a) => agents[a].skillsDir));
if (!options.copy && !options.yes && uniqueDirs.size > 1) {
const modeChoice = await p.select({
message: 'Installation method',
options: [
{
value: 'symlink',
label: 'Symlink (Recommended)',
hint: 'Single source of truth, easy updates',
},
{ value: 'copy', label: 'Copy to all agents', hint: 'Independent copies for each agent' },
],
});
if (p.isCancel(modeChoice)) {
exitInstallationCancelled();
}
installMode = modeChoice as InstallMode;
} else if (uniqueDirs.size <= 1) {
// Single target directory — default to copy (no symlink needed)
installMode = 'copy';
}
const cwd = process.cwd();
// Build installation summary
const summaryLines: string[] = [];
const agentNames = targetAgents.map((a) => agents[a].displayName);
// Check if any skill will be overwritten (parallel)
const overwriteChecks = await Promise.all(
selectedSkills.flatMap((skill) =>
targetAgents.map(async (agent) => ({
skillName: skill.installName,
agent,
installed: await isSkillInstalled(skill.installName, agent, { global: installGlobally }),
}))
)
);
const overwriteStatus = new Map<string, Map<string, boolean>>();
for (const { skillName, agent, installed } of overwriteChecks) {
if (!overwriteStatus.has(skillName)) {
overwriteStatus.set(skillName, new Map());
}
overwriteStatus.get(skillName)!.set(agent, installed);
}
for (const skill of selectedSkills) {
if (summaryLines.length > 0) summaryLines.push('');
const canonicalPath = getCanonicalPath(skill.installName, { global: installGlobally });
const shortCanonical = shortenPath(canonicalPath, cwd);
summaryLines.push(`${pc.cyan(shortCanonical)}`);
summaryLines.push(...buildAgentSummaryLines(targetAgents, installMode));
if (skill.files.size > 1) {
summaryLines.push(` ${pc.dim('files:')} ${skill.files.size}`);
}
const skillOverwrites = overwriteStatus.get(skill.installName);
const overwriteAgents = targetAgents
.filter((a) => skillOverwrites?.get(a))
.map((a) => agents[a].displayName);
if (overwriteAgents.length > 0) {
summaryLines.push(` ${pc.yellow('overwrites:')} ${formatList(overwriteAgents)}`);
}
}
console.log();
p.note(summaryLines.join('\n'), 'Installation Summary');
if (!options.yes) {
const confirmed = await p.confirm({ message: 'Proceed with installation?' });
if (p.isCancel(confirmed) || !confirmed) {
exitInstallationCancelled();
}
}
// Kick off privacy check early so it runs in parallel with installation
const sourceIdentifier = wellKnownProvider.getSourceIdentifier(url);
const wellKnownPrivacyPromise = isSourcePrivate(sourceIdentifier).catch(() => null);
spinner.start('Installing skills…');
const results: {
skill: string;
agent: string;
success: boolean;
path: string;
canonicalPath?: string;
mode: InstallMode;
symlinkFailed?: boolean;
error?: string;
}[] = [];
for (const skill of selectedSkills) {
for (const agent of targetAgents) {
const result = await installWellKnownSkillForAgent(skill, agent, {
global: installGlobally,
mode: installMode,
});
results.push({
skill: skill.installName,
agent: agents[agent].displayName,
...result,
});
}
}
spinner.stop('Installation complete');
console.log();
const successful = results.filter((r) => r.success);
const failed = results.filter((r) => !r.success);
const successfulSkillNames = new Set(successful.map((r) => r.skill));
// Build skillFiles map: { skillName: sourceUrl }
const skillFiles: Record<string, string> = {};
for (const skill of selectedSkills) {
skillFiles[skill.installName] = skill.sourceUrl;
}
// Privacy promise was started before installation — should be resolved by now
const isPrivate = await wellKnownPrivacyPromise;
if (isPrivate !== true) {
track({
event: 'install',
source: sourceIdentifier,
skills: selectedSkills.map((s) => s.installName).join(','),
agents: targetAgents.join(','),
...(installGlobally && { global: '1' }),
skillFiles: JSON.stringify(skillFiles),
installUrl: url,
metadata: options.metadata,
sourceType: 'well-known',
});
}