@rbbtsn0w/adg 0.6.0-beta.10 → 0.6.0-beta.11

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.
Files changed (50) hide show
  1. package/README.md +10 -7
  2. package/dist/bin/adg.js +4 -3
  3. package/dist/src/agents/base.js +2 -1
  4. package/dist/src/cli/core-plugin-handlers.js +97 -0
  5. package/dist/src/cli/handlers.js +4 -82
  6. package/dist/src/manifest.js +56 -3
  7. package/dist/src/subprocess.js +53 -0
  8. package/dist/vendor/skills/src/add.js +0 -15
  9. package/dist/vendor/skills/src/git-tree.js +4 -4
  10. package/dist/vendor/skills/src/skill-lock.js +4 -3
  11. package/dist/vendor/skills/src/update.js +9 -73
  12. package/dist/vendor/skills/src/use.js +28 -4
  13. package/docs/branching-and-release.md +52 -0
  14. package/package.json +7 -2
  15. package/schemas/adg-plugin.schema.json +1 -0
  16. package/vendor/skills/PROVENANCE.md +2 -0
  17. package/vendor/skills/package.json +0 -144
  18. package/vendor/skills/src/add.ts +0 -2213
  19. package/vendor/skills/src/agents.ts +0 -811
  20. package/vendor/skills/src/blob.ts +0 -588
  21. package/vendor/skills/src/cli.ts +0 -396
  22. package/vendor/skills/src/constants.ts +0 -3
  23. package/vendor/skills/src/detect-agent.ts +0 -62
  24. package/vendor/skills/src/find.ts +0 -419
  25. package/vendor/skills/src/frontmatter.ts +0 -16
  26. package/vendor/skills/src/git-tree.ts +0 -36
  27. package/vendor/skills/src/git.ts +0 -277
  28. package/vendor/skills/src/install.ts +0 -91
  29. package/vendor/skills/src/installer.ts +0 -1307
  30. package/vendor/skills/src/list.ts +0 -231
  31. package/vendor/skills/src/local-lock.ts +0 -189
  32. package/vendor/skills/src/plugin-manifest.ts +0 -183
  33. package/vendor/skills/src/prompts/search-multiselect.ts +0 -387
  34. package/vendor/skills/src/providers/index.ts +0 -14
  35. package/vendor/skills/src/providers/registry.ts +0 -51
  36. package/vendor/skills/src/providers/types.ts +0 -97
  37. package/vendor/skills/src/providers/wellknown.ts +0 -812
  38. package/vendor/skills/src/remove.ts +0 -335
  39. package/vendor/skills/src/sanitize.ts +0 -65
  40. package/vendor/skills/src/self-cli.ts +0 -20
  41. package/vendor/skills/src/skill-lock.ts +0 -329
  42. package/vendor/skills/src/skills.ts +0 -316
  43. package/vendor/skills/src/source-parser.ts +0 -449
  44. package/vendor/skills/src/sync.ts +0 -478
  45. package/vendor/skills/src/telemetry.ts +0 -226
  46. package/vendor/skills/src/test-utils.ts +0 -73
  47. package/vendor/skills/src/types.ts +0 -129
  48. package/vendor/skills/src/update-source.ts +0 -90
  49. package/vendor/skills/src/update.ts +0 -849
  50. package/vendor/skills/src/use.ts +0 -682
@@ -1,2213 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import * as p from '@clack/prompts';
3
- import pc from 'picocolors';
4
- import { existsSync } from 'fs';
5
- import { homedir } from 'os';
6
- import { sep, join, dirname } from 'path';
7
- import { parseSource, getOwnerRepo, parseOwnerRepo, isRepoPrivate } from './source-parser.ts';
8
- import { stripTerminalEscapes } from './sanitize.ts';
9
- import { searchMultiselect } from './prompts/search-multiselect.ts';
10
-
11
- // Helper to check if a value is a cancel symbol (works with both clack and our custom prompts)
12
- const isCancelled = (value: unknown): value is symbol => typeof value === 'symbol';
13
- const EVE_AGENT_LABEL = 'eve agent';
14
-
15
- /**
16
- * Check if a source identifier (owner/repo format) represents a private GitHub repo.
17
- * Returns true if private, false if public, null if unable to determine or not a GitHub repo.
18
- */
19
- async function isSourcePrivate(source: string): Promise<boolean | null> {
20
- const ownerRepo = parseOwnerRepo(source);
21
- if (!ownerRepo) {
22
- // Not in owner/repo format, assume not private (could be other providers)
23
- return false;
24
- }
25
- return isRepoPrivate(ownerRepo.owner, ownerRepo.repo);
26
- }
27
-
28
- export function getLockSource(parsedUrl: string, normalizedSource: string | null): string | null {
29
- // Preserve SSH URLs in lock files instead of normalizing to owner/repo shorthand.
30
- // When normalizedSource is used, parseSource() later resolves it to HTTPS,
31
- // breaking restore for private repos that require SSH authentication.
32
- const isSSH = parsedUrl.startsWith('git@') || parsedUrl.startsWith('ssh://');
33
- return isSSH ? parsedUrl : normalizedSource;
34
- }
35
- import { cloneRepo, cleanupTempDir, GitCloneError } from './git.ts';
36
- import { gitTreeShaForFolder } from './git-tree.ts';
37
- import { discoverSkills, getSkillDisplayName, filterSkills } from './skills.ts';
38
- import {
39
- installSkillForAgent,
40
- installBlobSkillForAgent,
41
- isSkillInstalled,
42
- getCanonicalPath,
43
- installWellKnownSkillForAgent,
44
- type InstallMode,
45
- } from './installer.ts';
46
- import {
47
- detectInstalledAgents,
48
- agents,
49
- getUniversalAgents,
50
- getVisibleUniversalAgents,
51
- getNonUniversalAgents,
52
- isUniversalAgent,
53
- getEveSubagents,
54
- } from './agents.ts';
55
- import {
56
- track,
57
- fetchAuditData,
58
- type AuditResponse,
59
- type PartnerAudit,
60
- } from './telemetry.ts';
61
- import { detectAgent, getAgentType } from './detect-agent.ts';
62
- import { wellKnownProvider, type WellKnownSkill } from './providers/index.ts';
63
- import {
64
- addSkillToLock,
65
- fetchSkillFolderHash,
66
- getGitHubToken,
67
- isPromptDismissed,
68
- dismissPrompt,
69
- getLastSelectedAgents,
70
- saveSelectedAgents,
71
- } from './skill-lock.ts';
72
- import { addSkillToLocalLock, computeSkillFolderHash } from './local-lock.ts';
73
- import type { Skill, AgentType } from './types.ts';
74
- import {
75
- tryBlobInstall,
76
- BLOB_ALLOWED_REPOS,
77
- getSkillFolderHashFromTree,
78
- fetchRepoTree,
79
- type BlobSkill,
80
- type BlobInstallResult,
81
- } from './blob.ts';
82
-
83
- // ─── Security Advisory ───
84
-
85
- function riskLabel(risk: string): string {
86
- switch (risk) {
87
- case 'critical':
88
- return pc.red(pc.bold('Critical Risk'));
89
- case 'high':
90
- return pc.red('High Risk');
91
- case 'medium':
92
- return pc.yellow('Med Risk');
93
- case 'low':
94
- return pc.green('Low Risk');
95
- case 'safe':
96
- return pc.green('Safe');
97
- default:
98
- return pc.dim('--');
99
- }
100
- }
101
-
102
- function socketLabel(audit: PartnerAudit | undefined): string {
103
- if (!audit) return pc.dim('--');
104
- const count = audit.alerts ?? 0;
105
- return count > 0 ? pc.red(`${count} alert${count !== 1 ? 's' : ''}`) : pc.green('0 alerts');
106
- }
107
-
108
- /** Pad a string to a given visible width (ignoring ANSI escape codes). */
109
- function padEnd(str: string, width: number): string {
110
- // Strip ANSI codes to measure visible length
111
- const visible = stripTerminalEscapes(str);
112
- const pad = Math.max(0, width - visible.length);
113
- return str + ' '.repeat(pad);
114
- }
115
-
116
- /**
117
- * Render a compact security table showing partner audit results.
118
- * Returns the lines to display, or empty array if no data.
119
- */
120
- function buildSecurityLines(
121
- auditData: AuditResponse | null,
122
- skills: Array<{ slug: string; displayName: string }>,
123
- source: string
124
- ): string[] {
125
- if (!auditData) return [];
126
-
127
- // Check if we have any audit data at all
128
- const hasAny = skills.some((s) => {
129
- const data = auditData[s.slug];
130
- return data && Object.keys(data).length > 0;
131
- });
132
- if (!hasAny) return [];
133
-
134
- // Compute column width for skill names
135
- const nameWidth = Math.min(Math.max(...skills.map((s) => s.displayName.length)), 36);
136
-
137
- // Header
138
- const lines: string[] = [];
139
- const header =
140
- padEnd('', nameWidth + 2) +
141
- padEnd(pc.dim('Gen'), 18) +
142
- padEnd(pc.dim('Socket'), 18) +
143
- pc.dim('Snyk');
144
- lines.push(header);
145
-
146
- // Rows
147
- for (const skill of skills) {
148
- const data = auditData[skill.slug];
149
- const name =
150
- skill.displayName.length > nameWidth
151
- ? skill.displayName.slice(0, nameWidth - 1) + '\u2026'
152
- : skill.displayName;
153
-
154
- const ath = data?.ath ? riskLabel(data.ath.risk) : pc.dim('--');
155
- const socket = data?.socket ? socketLabel(data.socket) : pc.dim('--');
156
- const snyk = data?.snyk ? riskLabel(data.snyk.risk) : pc.dim('--');
157
-
158
- lines.push(padEnd(pc.cyan(name), nameWidth + 2) + padEnd(ath, 18) + padEnd(socket, 18) + snyk);
159
- }
160
-
161
- // Footer link
162
- lines.push('');
163
- lines.push(`${pc.dim('Details:')} ${pc.dim(`https://skills.sh/${source}`)}`);
164
-
165
- return lines;
166
- }
167
-
168
- /**
169
- * Shortens a path for display: replaces homedir with ~ and cwd with .
170
- * Handles both Unix and Windows path separators.
171
- */
172
- function shortenPath(fullPath: string, cwd: string): string {
173
- const home = homedir();
174
- // Ensure we match complete path segments by checking for separator after the prefix
175
- if (fullPath === home || fullPath.startsWith(home + sep)) {
176
- return '~' + fullPath.slice(home.length);
177
- }
178
- if (fullPath === cwd || fullPath.startsWith(cwd + sep)) {
179
- return '.' + fullPath.slice(cwd.length);
180
- }
181
- return fullPath;
182
- }
183
-
184
- function computeSingleFileSkillHash(contents: string): string {
185
- const hash = createHash('sha256');
186
- hash.update('SKILL.md');
187
- hash.update(contents);
188
- return hash.digest('hex');
189
- }
190
-
191
- /**
192
- * Formats a list of items, truncating if too many
193
- */
194
- function formatList(items: string[], maxShow: number = 5): string {
195
- if (items.length <= maxShow) {
196
- return items.join(', ');
197
- }
198
- const shown = items.slice(0, maxShow);
199
- const remaining = items.length - maxShow;
200
- return `${shown.join(', ')} +${remaining} more`;
201
- }
202
-
203
- function formatSkillPromptSubject(skills: Skill[]): string {
204
- const names = skills.map((skill) => pc.cyan(getSkillDisplayName(skill)));
205
- const namedSubject = formatList(names, 3);
206
- return stripTerminalEscapes(namedSubject).length <= 80
207
- ? namedSubject
208
- : `${skills.length} selected skills`;
209
- }
210
-
211
- export function formatEveInstallPromptMessage(skills: Skill[]): string {
212
- return `Detected an eve project. Install ${formatSkillPromptSubject(skills)} for your ${EVE_AGENT_LABEL} to use?`;
213
- }
214
-
215
- /**
216
- * Splits agents into universal and non-universal (symlinked) groups.
217
- * Returns display names for each group.
218
- */
219
- function splitAgentsByType(agentTypes: AgentType[]): {
220
- universal: string[];
221
- symlinked: string[];
222
- } {
223
- const universal: string[] = [];
224
- const symlinked: string[] = [];
225
-
226
- for (const a of agentTypes) {
227
- if (isUniversalAgent(a)) {
228
- universal.push(agents[a].displayName);
229
- } else {
230
- symlinked.push(agents[a].displayName);
231
- }
232
- }
233
-
234
- return { universal, symlinked };
235
- }
236
-
237
- /**
238
- * Builds summary lines showing universal vs symlinked agents
239
- */
240
- function buildAgentSummaryLines(targetAgents: AgentType[], installMode: InstallMode): string[] {
241
- const lines: string[] = [];
242
- const { universal, symlinked } = splitAgentsByType(targetAgents);
243
-
244
- if (installMode === 'symlink') {
245
- if (universal.length > 0) {
246
- lines.push(` ${pc.green('universal:')} ${formatList(universal)}`);
247
- }
248
- if (symlinked.length > 0) {
249
- lines.push(` ${pc.dim('symlink →')} ${formatList(symlinked)}`);
250
- }
251
- } else {
252
- // Copy mode - all agents get copies
253
- const allNames = targetAgents.map((a) => agents[a].displayName);
254
- lines.push(` ${pc.dim('copy →')} ${formatList(allNames)}`);
255
- }
256
-
257
- return lines;
258
- }
259
-
260
- /**
261
- * A concrete install destination. For Eve, `subagent` optionally targets a
262
- * subagent's skills directory (`agent/subagents/<name>/skills`); when omitted
263
- * the skill installs to the root agent (`agent/skills`). Other agents never set
264
- * `subagent`.
265
- */
266
- interface InstallTarget {
267
- agent: AgentType;
268
- subagent?: string;
269
- }
270
-
271
- /** Human-readable label for an install target, e.g. "Eve (research)". */
272
- function targetDisplayName(target: InstallTarget): string {
273
- const base = agents[target.agent].displayName;
274
- return target.subagent ? `${base} (${target.subagent})` : base;
275
- }
276
-
277
- /** Stable key used to deduplicate / index per-target state. */
278
- function targetKey(target: InstallTarget): string {
279
- return target.subagent ? `${target.agent}:${target.subagent}` : target.agent;
280
- }
281
-
282
- /**
283
- * Expand the selected agents into concrete install targets, fanning Eve out
284
- * across the chosen subagents (root and/or named subagents).
285
- */
286
- function buildInstallTargets(
287
- targetAgents: AgentType[],
288
- eveSubagentTargets: Array<string | undefined>
289
- ): InstallTarget[] {
290
- const targets: InstallTarget[] = [];
291
- for (const agent of targetAgents) {
292
- if (agent === 'eve') {
293
- for (const subagent of eveSubagentTargets) {
294
- targets.push({ agent, subagent });
295
- }
296
- } else {
297
- targets.push({ agent });
298
- }
299
- }
300
- return targets;
301
- }
302
-
303
- /**
304
- * Builds summary lines showing universal vs symlinked agents and Eve subagents.
305
- */
306
- function buildTargetSummaryLines(targets: InstallTarget[], installMode: InstallMode): string[] {
307
- const lines: string[] = [];
308
- const rootAgents = targets.filter((t) => !t.subagent).map((t) => t.agent);
309
- const subagentNames = targets.filter((t) => t.subagent).map(targetDisplayName);
310
- const { universal, symlinked } = splitAgentsByType(rootAgents);
311
-
312
- if (installMode === 'symlink') {
313
- if (universal.length > 0) {
314
- lines.push(` ${pc.green('universal:')} ${formatList(universal)}`);
315
- }
316
- if (symlinked.length > 0) {
317
- lines.push(` ${pc.dim('symlink →')} ${formatList(symlinked)}`);
318
- }
319
- if (subagentNames.length > 0) {
320
- lines.push(` ${pc.dim('copy →')} ${formatList(subagentNames)}`);
321
- }
322
- } else {
323
- const allNames = targets.map(targetDisplayName);
324
- lines.push(` ${pc.dim('copy →')} ${formatList(allNames)}`);
325
- }
326
-
327
- return lines;
328
- }
329
-
330
- /**
331
- * Ensures universal agents are always included in the target agents list.
332
- * Used when -y flag is passed or when auto-selecting agents.
333
- */
334
- function ensureUniversalAgents(targetAgents: AgentType[]): AgentType[] {
335
- const universalAgents = getUniversalAgents();
336
- const result = [...targetAgents];
337
-
338
- for (const ua of universalAgents) {
339
- if (!result.includes(ua)) {
340
- result.push(ua);
341
- }
342
- }
343
-
344
- return result;
345
- }
346
-
347
- /**
348
- * Builds result lines from installation results, splitting by universal vs symlinked
349
- */
350
- function buildResultLines(
351
- results: Array<{
352
- agent: string;
353
- symlinkFailed?: boolean;
354
- skipped?: boolean;
355
- }>,
356
- targetAgents: AgentType[]
357
- ): string[] {
358
- const lines: string[] = [];
359
-
360
- // Split target agents by type
361
- const { universal, symlinked: symlinkAgents } = splitAgentsByType(targetAgents);
362
-
363
- // For symlink results, also track which ones actually succeeded vs failed
364
- // Exclude skipped agents (those whose config dir doesn't exist in the project)
365
- const successfulSymlinks = results
366
- .filter((r) => !r.symlinkFailed && !r.skipped && !universal.includes(r.agent))
367
- .map((r) => r.agent);
368
- const failedSymlinks = results.filter((r) => r.symlinkFailed && !r.skipped).map((r) => r.agent);
369
-
370
- if (universal.length > 0) {
371
- lines.push(` ${pc.green('universal:')} ${formatList(universal)}`);
372
- }
373
- if (successfulSymlinks.length > 0) {
374
- lines.push(` ${pc.dim('symlinked:')} ${formatList(successfulSymlinks)}`);
375
- }
376
- if (failedSymlinks.length > 0) {
377
- lines.push(` ${pc.yellow('copied:')} ${formatList(failedSymlinks)}`);
378
- }
379
-
380
- return lines;
381
- }
382
-
383
- /**
384
- * Wrapper around p.multiselect that adds a hint for keyboard usage.
385
- * Accepts options with required labels (matching our usage pattern).
386
- */
387
- function multiselect<Value>(opts: {
388
- message: string;
389
- options: Array<{ value: Value; label: string; hint?: string }>;
390
- initialValues?: Value[];
391
- required?: boolean;
392
- }) {
393
- return p.multiselect({
394
- ...opts,
395
- // Cast is safe: our options always have labels, which satisfies p.Option requirements
396
- options: opts.options as p.Option<Value>[],
397
- message: `${opts.message} ${pc.dim('(space to toggle)')}`,
398
- }) as Promise<Value[] | symbol>;
399
- }
400
-
401
- /**
402
- * Prompts the user to select agents using interactive search.
403
- * Pre-selects the last used agents if available.
404
- * Saves the selection for future use.
405
- */
406
- export async function promptForAgents(
407
- message: string,
408
- choices: Array<{ value: AgentType; label: string; hint?: string }>
409
- ): Promise<AgentType[] | symbol> {
410
- // Get last selected agents to pre-select
411
- let lastSelected: string[] | undefined;
412
- try {
413
- lastSelected = await getLastSelectedAgents();
414
- } catch {
415
- // Silently ignore errors reading lock file
416
- }
417
-
418
- const validAgents = choices.map((c) => c.value);
419
-
420
- // Default agents to pre-select when no valid history exists
421
- const defaultAgents: AgentType[] = ['claude-code', 'opencode', 'codex'];
422
- const defaultValues = defaultAgents.filter((a) => validAgents.includes(a));
423
-
424
- let initialValues: AgentType[] = [];
425
-
426
- if (lastSelected && lastSelected.length > 0) {
427
- // Filter stored agents against currently valid agents
428
- initialValues = lastSelected.filter((a) => validAgents.includes(a as AgentType)) as AgentType[];
429
- }
430
-
431
- // If no valid selection from history, use defaults
432
- if (initialValues.length === 0) {
433
- initialValues = defaultValues;
434
- }
435
-
436
- const selected = await searchMultiselect({
437
- message,
438
- items: choices,
439
- initialSelected: initialValues,
440
- required: true,
441
- });
442
-
443
- if (!isCancelled(selected)) {
444
- // Save selection for next time
445
- try {
446
- await saveSelectedAgents(selected as string[]);
447
- } catch {
448
- // Silently ignore errors writing lock file
449
- }
450
- }
451
-
452
- return selected as AgentType[] | symbol;
453
- }
454
-
455
- /**
456
- * Interactive agent selection using fuzzy search.
457
- * Shows universal agents as locked (always selected), and other agents as selectable.
458
- */
459
- async function selectAgentsInteractive(options: {
460
- global?: boolean;
461
- }): Promise<AgentType[] | symbol> {
462
- // Filter out agents that don't support global installation when --global is used
463
- const supportsGlobalFilter = (a: AgentType) => !options.global || agents[a].globalSkillsDir;
464
-
465
- const universalAgents = getUniversalAgents().filter(supportsGlobalFilter);
466
- const visibleUniversalAgents = getVisibleUniversalAgents().filter(supportsGlobalFilter);
467
- const otherAgents = getNonUniversalAgents().filter(
468
- (agent) => agent !== 'eve' && supportsGlobalFilter(agent)
469
- );
470
-
471
- // Universal agents shown as locked section
472
- const universalSection = {
473
- title: 'Universal (.agents/skills)',
474
- items: visibleUniversalAgents.map((a) => ({
475
- value: a,
476
- label: agents[a].displayName,
477
- })),
478
- hiddenCount: universalAgents.length - visibleUniversalAgents.length,
479
- };
480
-
481
- // Other agents are selectable with their skillsDir as hint
482
- const otherChoices = otherAgents.map((a) => ({
483
- value: a,
484
- label: agents[a].displayName,
485
- hint: options.global ? agents[a].globalSkillsDir! : agents[a].skillsDir,
486
- }));
487
-
488
- // Get last selected agents (filter to only non-universal ones for initial selection)
489
- let lastSelected: string[] | undefined;
490
- try {
491
- lastSelected = await getLastSelectedAgents();
492
- } catch {
493
- // Silently ignore errors
494
- }
495
-
496
- const initialSelected = lastSelected
497
- ? (lastSelected.filter(
498
- (a) => otherAgents.includes(a as AgentType) && !universalAgents.includes(a as AgentType)
499
- ) as AgentType[])
500
- : [];
501
-
502
- const selected = await searchMultiselect({
503
- message: 'Which agents do you want to install to?',
504
- items: otherChoices,
505
- initialSelected,
506
- lockedSection: universalSection,
507
- });
508
-
509
- if (!isCancelled(selected)) {
510
- // Save selection (all agents including universal)
511
- try {
512
- await saveSelectedAgents(selected as string[]);
513
- } catch {
514
- // Silently ignore errors
515
- }
516
- }
517
-
518
- return selected as AgentType[] | symbol;
519
- }
520
-
521
- export interface AddOptions {
522
- global?: boolean;
523
- agent?: string[];
524
- yes?: boolean;
525
- skill?: string[];
526
- list?: boolean;
527
- all?: boolean;
528
- fullDepth?: boolean;
529
- copy?: boolean;
530
- /**
531
- * Eve subagent targets. Each value is a subagent name; `root` (or `.`)
532
- * selects the root agent. Implies installing for Eve.
533
- */
534
- subagent?: string[];
535
- dangerouslyAcceptOpenclawRisks?: boolean;
536
- }
537
-
538
- /**
539
- * Handle skills from a well-known endpoint (RFC 8615).
540
- * Discovers skills from /.well-known/agent-skills/index.json (preferred)
541
- * or /.well-known/skills/index.json (legacy fallback).
542
- */
543
- async function handleWellKnownSkills(
544
- source: string,
545
- url: string,
546
- options: AddOptions,
547
- spinner: ReturnType<typeof p.spinner>
548
- ): Promise<void> {
549
- spinner.start('Discovering skills from well-known endpoint...');
550
-
551
- // Fetch all skills from the well-known endpoint
552
- const skills = await wellKnownProvider.fetchAllSkills(url);
553
-
554
- if (skills.length === 0) {
555
- spinner.stop(pc.red('No skills found'));
556
- p.outro(
557
- pc.red(
558
- 'No skills found at this URL. Make sure the server has a /.well-known/agent-skills/index.json or /.well-known/skills/index.json file.'
559
- )
560
- );
561
- process.exit(1);
562
- }
563
-
564
- spinner.stop(`Found ${pc.green(skills.length)} skill${skills.length > 1 ? 's' : ''}`);
565
-
566
- // Log discovered skills
567
- for (const skill of skills) {
568
- p.log.info(`Skill: ${pc.cyan(skill.installName)}`);
569
- p.log.message(pc.dim(skill.description));
570
- if (skill.files.size > 1) {
571
- p.log.message(pc.dim(` Files: ${Array.from(skill.files.keys()).join(', ')}`));
572
- }
573
- }
574
-
575
- if (options.list) {
576
- console.log();
577
- p.log.step(pc.bold('Available Skills'));
578
- for (const skill of skills) {
579
- p.log.message(` ${pc.cyan(skill.installName)}`);
580
- p.log.message(` ${pc.dim(skill.description)}`);
581
- if (skill.files.size > 1) {
582
- p.log.message(` ${pc.dim(`Files: ${skill.files.size}`)}`);
583
- }
584
- }
585
- console.log();
586
- p.outro('Run without --list to install');
587
- process.exit(0);
588
- }
589
-
590
- // Filter skills if --skill option is provided
591
- let selectedSkills: WellKnownSkill[];
592
-
593
- if (options.skill?.includes('*')) {
594
- // --skill '*' selects all skills
595
- selectedSkills = skills;
596
- p.log.info(`Installing all ${skills.length} skills`);
597
- } else if (options.skill && options.skill.length > 0) {
598
- selectedSkills = skills.filter((s) =>
599
- options.skill!.some(
600
- (name) =>
601
- s.installName.toLowerCase() === name.toLowerCase() ||
602
- s.name.toLowerCase() === name.toLowerCase()
603
- )
604
- );
605
-
606
- if (selectedSkills.length === 0) {
607
- p.log.error(`No matching skills found for: ${options.skill.join(', ')}`);
608
- p.log.info('Available skills:');
609
- for (const s of skills) {
610
- p.log.message(` - ${s.installName}`);
611
- }
612
- process.exit(1);
613
- }
614
- } else if (skills.length === 1) {
615
- selectedSkills = skills;
616
- const firstSkill = skills[0]!;
617
- p.log.info(`Skill: ${pc.cyan(firstSkill.installName)}`);
618
- } else if (options.yes) {
619
- selectedSkills = skills;
620
- p.log.info(`Installing all ${skills.length} skills`);
621
- } else {
622
- // Prompt user to select skills
623
- const skillChoices = skills.map((s) => ({
624
- value: s,
625
- label: s.installName,
626
- hint: s.description.length > 60 ? s.description.slice(0, 57) + '...' : s.description,
627
- }));
628
-
629
- const selected = await multiselect({
630
- message: 'Select skills to install',
631
- options: skillChoices,
632
- required: true,
633
- });
634
-
635
- if (p.isCancel(selected)) {
636
- p.cancel('Installation cancelled');
637
- process.exit(0);
638
- }
639
-
640
- selectedSkills = selected as WellKnownSkill[];
641
- }
642
-
643
- // Detect agents
644
- let targetAgents: AgentType[];
645
- const validAgents = Object.keys(agents);
646
-
647
- if (options.agent?.includes('*')) {
648
- // --agent '*' selects all agents
649
- targetAgents = validAgents as AgentType[];
650
- p.log.info(`Installing to all ${targetAgents.length} agents`);
651
- } else if (options.agent && options.agent.length > 0) {
652
- const invalidAgents = options.agent.filter((a) => !validAgents.includes(a));
653
-
654
- if (invalidAgents.length > 0) {
655
- p.log.error(`Invalid agents: ${invalidAgents.join(', ')}`);
656
- p.log.info(`Valid agents: ${validAgents.join(', ')}`);
657
- process.exit(1);
658
- }
659
-
660
- targetAgents = options.agent as AgentType[];
661
- } else {
662
- spinner.start('Loading agents...');
663
- const installedAgents = await detectInstalledAgents();
664
- const totalAgents = Object.keys(agents).length;
665
- spinner.stop(`${totalAgents} agents`);
666
-
667
- if (installedAgents.length === 0) {
668
- if (options.yes) {
669
- targetAgents = validAgents as AgentType[];
670
- p.log.info('Installing to all agents');
671
- } else {
672
- p.log.info('Select agents to install skills to');
673
-
674
- const allAgentChoices = Object.entries(agents).map(([key, config]) => ({
675
- value: key as AgentType,
676
- label: config.displayName,
677
- }));
678
-
679
- // Use helper to prompt with search
680
- const selected = await promptForAgents(
681
- 'Which agents do you want to install to?',
682
- allAgentChoices
683
- );
684
-
685
- if (p.isCancel(selected)) {
686
- p.cancel('Installation cancelled');
687
- process.exit(0);
688
- }
689
-
690
- targetAgents = selected as AgentType[];
691
- }
692
- } else if (installedAgents.length === 1 || options.yes) {
693
- // Auto-select detected agents + ensure universal agents are included
694
- targetAgents = ensureUniversalAgents(installedAgents);
695
- if (installedAgents.length === 1) {
696
- const firstAgent = installedAgents[0]!;
697
- p.log.info(`Installing to: ${pc.cyan(agents[firstAgent].displayName)}`);
698
- } else {
699
- p.log.info(
700
- `Installing to: ${installedAgents.map((a) => pc.cyan(agents[a].displayName)).join(', ')}`
701
- );
702
- }
703
- } else {
704
- const selected = await selectAgentsInteractive({ global: options.global });
705
-
706
- if (p.isCancel(selected)) {
707
- p.cancel('Installation cancelled');
708
- process.exit(0);
709
- }
710
-
711
- targetAgents = selected as AgentType[];
712
- }
713
- }
714
-
715
- let installGlobally = options.global ?? false;
716
-
717
- // Check if any selected agents support global installation
718
- const supportsGlobal = targetAgents.some((a) => agents[a].globalSkillsDir !== undefined);
719
-
720
- if (options.global === undefined && !options.yes && supportsGlobal) {
721
- const scope = await p.select({
722
- message: 'Installation scope',
723
- options: [
724
- {
725
- value: false,
726
- label: 'Project',
727
- hint: 'Install in current directory (committed with your project)',
728
- },
729
- {
730
- value: true,
731
- label: 'Global',
732
- hint: 'Install in home directory (available across all projects)',
733
- },
734
- ],
735
- });
736
-
737
- if (p.isCancel(scope)) {
738
- p.cancel('Installation cancelled');
739
- process.exit(0);
740
- }
741
-
742
- installGlobally = scope as boolean;
743
- }
744
-
745
- // Determine install mode (symlink vs copy)
746
- let installMode: InstallMode = options.copy ? 'copy' : 'symlink';
747
-
748
- // Only prompt for install mode when there are multiple unique target directories.
749
- // When all selected agents share the same skillsDir, symlink vs copy is meaningless.
750
- const uniqueDirs = new Set(targetAgents.map((a) => agents[a].skillsDir));
751
-
752
- if (!options.copy && !options.yes && uniqueDirs.size > 1) {
753
- const modeChoice = await p.select({
754
- message: 'Installation method',
755
- options: [
756
- {
757
- value: 'symlink',
758
- label: 'Symlink (Recommended)',
759
- hint: 'Single source of truth, easy updates',
760
- },
761
- { value: 'copy', label: 'Copy to all agents', hint: 'Independent copies for each agent' },
762
- ],
763
- });
764
-
765
- if (p.isCancel(modeChoice)) {
766
- p.cancel('Installation cancelled');
767
- process.exit(0);
768
- }
769
-
770
- installMode = modeChoice as InstallMode;
771
- } else if (uniqueDirs.size <= 1) {
772
- // Single target directory — default to copy (no symlink needed)
773
- installMode = 'copy';
774
- }
775
-
776
- const cwd = process.cwd();
777
-
778
- // Build installation summary
779
- const summaryLines: string[] = [];
780
- const agentNames = targetAgents.map((a) => agents[a].displayName);
781
-
782
- // Check if any skill will be overwritten (parallel)
783
- const overwriteChecks = await Promise.all(
784
- selectedSkills.flatMap((skill) =>
785
- targetAgents.map(async (agent) => ({
786
- skillName: skill.installName,
787
- agent,
788
- installed: await isSkillInstalled(skill.installName, agent, { global: installGlobally }),
789
- }))
790
- )
791
- );
792
- const overwriteStatus = new Map<string, Map<string, boolean>>();
793
- for (const { skillName, agent, installed } of overwriteChecks) {
794
- if (!overwriteStatus.has(skillName)) {
795
- overwriteStatus.set(skillName, new Map());
796
- }
797
- overwriteStatus.get(skillName)!.set(agent, installed);
798
- }
799
-
800
- for (const skill of selectedSkills) {
801
- if (summaryLines.length > 0) summaryLines.push('');
802
-
803
- const canonicalPath = getCanonicalPath(skill.installName, { global: installGlobally });
804
- const shortCanonical = shortenPath(canonicalPath, cwd);
805
- summaryLines.push(`${pc.cyan(shortCanonical)}`);
806
- summaryLines.push(...buildAgentSummaryLines(targetAgents, installMode));
807
- if (skill.files.size > 1) {
808
- summaryLines.push(` ${pc.dim('files:')} ${skill.files.size}`);
809
- }
810
-
811
- const skillOverwrites = overwriteStatus.get(skill.installName);
812
- const overwriteAgents = targetAgents
813
- .filter((a) => skillOverwrites?.get(a))
814
- .map((a) => agents[a].displayName);
815
-
816
- if (overwriteAgents.length > 0) {
817
- summaryLines.push(` ${pc.yellow('overwrites:')} ${formatList(overwriteAgents)}`);
818
- }
819
- }
820
-
821
- console.log();
822
- p.note(summaryLines.join('\n'), 'Installation Summary');
823
-
824
- if (!options.yes) {
825
- const confirmed = await p.confirm({ message: 'Proceed with installation?' });
826
-
827
- if (p.isCancel(confirmed) || !confirmed) {
828
- p.cancel('Installation cancelled');
829
- process.exit(0);
830
- }
831
- }
832
-
833
- // Kick off privacy check early so it runs in parallel with installation
834
- const sourceIdentifier = wellKnownProvider.getSourceIdentifier(url);
835
- const wellKnownPrivacyPromise = isSourcePrivate(sourceIdentifier).catch(() => null);
836
-
837
- spinner.start('Installing skills...');
838
-
839
- const results: {
840
- skill: string;
841
- agent: string;
842
- success: boolean;
843
- path: string;
844
- canonicalPath?: string;
845
- mode: InstallMode;
846
- symlinkFailed?: boolean;
847
- error?: string;
848
- }[] = [];
849
-
850
- for (const skill of selectedSkills) {
851
- for (const agent of targetAgents) {
852
- const result = await installWellKnownSkillForAgent(skill, agent, {
853
- global: installGlobally,
854
- mode: installMode,
855
- });
856
- results.push({
857
- skill: skill.installName,
858
- agent: agents[agent].displayName,
859
- ...result,
860
- });
861
- }
862
- }
863
-
864
- spinner.stop('Installation complete');
865
-
866
- console.log();
867
- const successful = results.filter((r) => r.success);
868
- const failed = results.filter((r) => !r.success);
869
-
870
- // Build skillFiles map: { skillName: sourceUrl }
871
- const skillFiles: Record<string, string> = {};
872
- for (const skill of selectedSkills) {
873
- skillFiles[skill.installName] = skill.sourceUrl;
874
- }
875
-
876
- // Privacy promise was started before installation — should be resolved by now
877
- const isPrivate = await wellKnownPrivacyPromise;
878
- if (isPrivate !== true) {
879
- track({
880
- event: 'install',
881
- source: sourceIdentifier,
882
- skills: selectedSkills.map((s) => s.installName).join(','),
883
- agents: targetAgents.join(','),
884
- ...(installGlobally && { global: '1' }),
885
- skillFiles: JSON.stringify(skillFiles),
886
- sourceType: 'well-known',
887
- });
888
- }
889
-
890
- // Add to skill lock file for update tracking (only for global installs)
891
- if (successful.length > 0 && installGlobally) {
892
- const successfulSkillNames = new Set(successful.map((r) => r.skill));
893
- for (const skill of selectedSkills) {
894
- if (successfulSkillNames.has(skill.installName)) {
895
- try {
896
- await addSkillToLock(skill.installName, {
897
- source: sourceIdentifier,
898
- sourceType: 'well-known',
899
- sourceUrl: skill.sourceUrl,
900
- skillFolderHash: '', // Well-known skills don't have a folder hash
901
- });
902
- } catch {
903
- // Don't fail installation if lock file update fails
904
- }
905
- }
906
- }
907
- }
908
-
909
- // Add to local lock file for project-scoped installs
910
- if (successful.length > 0 && !installGlobally) {
911
- const successfulSkillNames = new Set(successful.map((r) => r.skill));
912
- for (const skill of selectedSkills) {
913
- if (successfulSkillNames.has(skill.installName)) {
914
- try {
915
- const matchingResult = successful.find((r) => r.skill === skill.installName);
916
- const installDir = matchingResult?.canonicalPath || matchingResult?.path;
917
- if (installDir) {
918
- const computedHash = await computeSkillFolderHash(installDir);
919
- await addSkillToLocalLock(
920
- skill.installName,
921
- {
922
- source: sourceIdentifier,
923
- sourceType: 'well-known',
924
- computedHash,
925
- },
926
- cwd
927
- );
928
- }
929
- } catch {
930
- // Don't fail installation if lock file update fails
931
- }
932
- }
933
- }
934
- }
935
-
936
- if (successful.length > 0) {
937
- const bySkill = new Map<string, typeof results>();
938
- for (const r of successful) {
939
- const skillResults = bySkill.get(r.skill) || [];
940
- skillResults.push(r);
941
- bySkill.set(r.skill, skillResults);
942
- }
943
-
944
- const skillCount = bySkill.size;
945
- const symlinkFailures = successful.filter((r) => r.mode === 'symlink' && r.symlinkFailed);
946
- const copiedAgents = symlinkFailures.map((r) => r.agent);
947
- const resultLines: string[] = [];
948
-
949
- for (const [skillName, skillResults] of bySkill) {
950
- const firstResult = skillResults[0]!;
951
-
952
- if (firstResult.mode === 'copy') {
953
- // Copy mode: show skill name and list all agent paths
954
- resultLines.push(`${pc.green('✓')} ${skillName} ${pc.dim('(copied)')}`);
955
- for (const r of skillResults) {
956
- const shortPath = shortenPath(r.path, cwd);
957
- resultLines.push(` ${pc.dim('→')} ${shortPath}`);
958
- }
959
- } else {
960
- // Symlink mode: show canonical path and universal/symlinked agents
961
- if (firstResult.canonicalPath) {
962
- const shortPath = shortenPath(firstResult.canonicalPath, cwd);
963
- resultLines.push(`${pc.green('✓')} ${shortPath}`);
964
- } else {
965
- resultLines.push(`${pc.green('✓')} ${skillName}`);
966
- }
967
- resultLines.push(...buildResultLines(skillResults, targetAgents));
968
- }
969
- }
970
-
971
- const title = pc.green(`Installed ${skillCount} skill${skillCount !== 1 ? 's' : ''}`);
972
- p.note(resultLines.join('\n'), title);
973
-
974
- // Show symlink failure warning (only for symlink mode)
975
- if (symlinkFailures.length > 0) {
976
- p.log.warn(pc.yellow(`Symlinks failed for: ${formatList(copiedAgents)}`));
977
- p.log.message(
978
- pc.dim(
979
- ' Files were copied instead. On Windows, enable Developer Mode for symlink support.'
980
- )
981
- );
982
- }
983
- }
984
-
985
- if (failed.length > 0) {
986
- console.log();
987
- p.log.error(pc.red(`Failed to install ${failed.length}`));
988
- for (const r of failed) {
989
- p.log.message(` ${pc.red('✗')} ${r.skill} → ${r.agent}: ${pc.dim(r.error)}`);
990
- }
991
- }
992
-
993
- console.log();
994
- p.outro(
995
- pc.green('Done!') + pc.dim(' Review skills before use; they run with full agent permissions.')
996
- );
997
-
998
- // Prompt for find-skills after successful install
999
- await promptForFindSkills(options, targetAgents);
1000
- }
1001
-
1002
- export async function runAdd(args: string[], options: AddOptions = {}): Promise<void> {
1003
- const source = args[0];
1004
- let installTipShown = false;
1005
-
1006
- const showInstallTip = (): void => {
1007
- if (installTipShown) return;
1008
- p.log.message(
1009
- pc.dim('Tip: use the --yes (-y) and --global (-g) flags to install without prompts.')
1010
- );
1011
- installTipShown = true;
1012
- };
1013
-
1014
- if (!source) {
1015
- console.log();
1016
- console.log(
1017
- pc.bgRed(pc.white(pc.bold(' ERROR '))) + ' ' + pc.red('Missing required argument: source')
1018
- );
1019
- console.log();
1020
- console.log(pc.dim(' Usage:'));
1021
- console.log(` ${pc.cyan('adg skills add')} ${pc.yellow('<source>')} ${pc.dim('[options]')}`);
1022
- console.log();
1023
- console.log(pc.dim(' Example:'));
1024
- console.log(` ${pc.cyan('adg skills add')} ${pc.yellow('vercel-labs/agent-skills')}`);
1025
- console.log();
1026
- process.exit(1);
1027
- }
1028
-
1029
- // --all implies --skill '*' and --agent '*' and -y
1030
- if (options.all) {
1031
- options.skill = ['*'];
1032
- options.agent = ['*'];
1033
- options.yes = true;
1034
- }
1035
-
1036
- // Auto-enable non-interactive mode when running inside an AI agent
1037
- const agentResult = await detectAgent();
1038
- if (agentResult.isAgent) {
1039
- options.yes = true;
1040
- // Auto-select the detected agent + universal agents (unless user explicitly specified agents)
1041
- if (!options.agent || options.agent.length === 0) {
1042
- const mappedAgent = getAgentType(agentResult.agent.name);
1043
- if (mappedAgent) {
1044
- options.agent = ensureUniversalAgents([mappedAgent]);
1045
- }
1046
- }
1047
- }
1048
-
1049
- console.log();
1050
- if (!agentResult.isAgent) {
1051
- p.intro(pc.bgCyan(pc.black(' skills ')));
1052
- }
1053
-
1054
- if (agentResult.isAgent) {
1055
- p.log.info(
1056
- pc.bgCyan(pc.black(pc.bold(` ${agentResult.agent.name} `))) +
1057
- ' ' +
1058
- 'Agent detected — installing non-interactively'
1059
- );
1060
- } else if (!process.stdin.isTTY) {
1061
- showInstallTip();
1062
- }
1063
-
1064
- let tempDir: string | null = null;
1065
-
1066
- try {
1067
- const spinner = p.spinner();
1068
-
1069
- spinner.start('Parsing source...');
1070
- const parsed = parseSource(source);
1071
- spinner.stop(
1072
- `Source: ${parsed.type === 'local' ? parsed.localPath! : parsed.url}${parsed.ref ? ` @ ${pc.yellow(parsed.ref)}` : ''}${parsed.subpath ? ` (${parsed.subpath})` : ''}${parsed.skillFilter ? ` ${pc.dim('@')}${pc.cyan(parsed.skillFilter)}` : ''}`
1073
- );
1074
-
1075
- // Kick off the repo privacy check early so it runs in parallel with
1076
- // cloning/discovering/installing. The result is only needed later for
1077
- // telemetry gating — it should never block user-visible output.
1078
- const ownerRepoRaw = getOwnerRepo(parsed);
1079
- const repoPrivacyPromise: Promise<boolean | null> = (() => {
1080
- if (!ownerRepoRaw) return Promise.resolve(null);
1081
- const ownerRepo = parseOwnerRepo(ownerRepoRaw);
1082
- if (!ownerRepo) return Promise.resolve(null);
1083
- return isRepoPrivate(ownerRepo.owner, ownerRepo.repo).catch(() => null);
1084
- })();
1085
-
1086
- // Block openclaw sources unless explicitly opted in
1087
- const sourceOwner = ownerRepoRaw?.split('/')[0]?.toLowerCase();
1088
- if (sourceOwner === 'openclaw' && !options.dangerouslyAcceptOpenclawRisks) {
1089
- console.log();
1090
- p.log.warn(pc.yellow(pc.bold('⚠ OpenClaw skills are unverified community submissions.')));
1091
- p.log.message(
1092
- pc.yellow(
1093
- 'This source contains user-submitted skills that have not been reviewed for safety or quality.'
1094
- )
1095
- );
1096
- p.log.message(pc.yellow('Skills run with full agent permissions and could be malicious.'));
1097
- console.log();
1098
- p.log.message(
1099
- `If you understand the risks, re-run with:\n\n ${pc.cyan(`adg skills add ${source} --dangerously-accept-openclaw-risks`)}\n`
1100
- );
1101
- p.outro(pc.red('Installation blocked'));
1102
- process.exit(1);
1103
- }
1104
-
1105
- // Handle well-known skills from arbitrary URLs
1106
- if (parsed.type === 'well-known') {
1107
- await handleWellKnownSkills(source, parsed.url, options, spinner);
1108
- return;
1109
- }
1110
-
1111
- // If skillFilter is present from @skill syntax (e.g., owner/repo@skill-name),
1112
- // merge it into options.skill
1113
- if (parsed.skillFilter) {
1114
- options.skill = options.skill || [];
1115
- if (!options.skill.includes(parsed.skillFilter)) {
1116
- options.skill.push(parsed.skillFilter);
1117
- }
1118
- }
1119
-
1120
- // Include internal skills when a specific skill is explicitly requested
1121
- // (via --skill or @skill syntax)
1122
- const includeInternal = !!(options.skill && options.skill.length > 0);
1123
-
1124
- let skills: Skill[];
1125
- let blobResult: BlobInstallResult | null = null;
1126
-
1127
- if (parsed.type === 'local') {
1128
- // Use local path directly, no cloning needed
1129
- spinner.start('Validating local path...');
1130
- if (!existsSync(parsed.localPath!)) {
1131
- spinner.stop(pc.red('Path not found'));
1132
- p.outro(pc.red(`Local path does not exist: ${parsed.localPath}`));
1133
- process.exit(1);
1134
- }
1135
- spinner.stop('Local path validated');
1136
-
1137
- spinner.start('Discovering skills...');
1138
- skills = await discoverSkills(parsed.localPath!, parsed.subpath, {
1139
- includeInternal,
1140
- fullDepth: options.fullDepth,
1141
- });
1142
- } else if (parsed.type === 'github' && !options.fullDepth) {
1143
- // Try the blob-based fast install for GitHub sources; skip for --full-depth.
1144
- // Eligible per repo (a BLOB_ALLOWED_REPOS entry = self-hosted download URL) or
1145
- // per owner (BLOB_ALLOWED_OWNERS = all their repos, skills.sh-hosted).
1146
- const BLOB_ALLOWED_OWNERS = ['vercel', 'vercel-labs', 'heygen-com'];
1147
- const ownerRepo = getOwnerRepo(parsed);
1148
- const owner = ownerRepo?.split('/')[0]?.toLowerCase();
1149
- const isSelfHostedRepo =
1150
- !!ownerRepo && Object.hasOwn(BLOB_ALLOWED_REPOS, ownerRepo.toLowerCase());
1151
- if (ownerRepo && owner && (isSelfHostedRepo || BLOB_ALLOWED_OWNERS.includes(owner))) {
1152
- spinner.start('Fetching skills...');
1153
- blobResult = await tryBlobInstall(ownerRepo, {
1154
- subpath: parsed.subpath,
1155
- skillFilter: parsed.skillFilter,
1156
- ref: parsed.ref,
1157
- getToken: getGitHubToken,
1158
- includeInternal,
1159
- });
1160
- if (!blobResult) {
1161
- spinner.stop(pc.dim('Falling back to clone...'));
1162
- }
1163
- }
1164
-
1165
- if (blobResult) {
1166
- skills = blobResult.skills;
1167
- spinner.stop(`Found ${pc.green(skills.length)} skill${skills.length > 1 ? 's' : ''}`);
1168
- } else {
1169
- // Blob failed — fall back to git clone
1170
- spinner.start('Cloning repository...');
1171
- tempDir = await cloneRepo(parsed.url, parsed.ref);
1172
- spinner.stop('Repository cloned');
1173
-
1174
- spinner.start('Discovering skills...');
1175
- skills = await discoverSkills(tempDir, parsed.subpath, {
1176
- includeInternal,
1177
- fullDepth: options.fullDepth,
1178
- });
1179
- }
1180
- } else {
1181
- // GitLab, git URL, or --full-depth: always clone
1182
- spinner.start('Cloning repository...');
1183
- tempDir = await cloneRepo(parsed.url, parsed.ref);
1184
- spinner.stop('Repository cloned');
1185
-
1186
- spinner.start('Discovering skills...');
1187
- skills = await discoverSkills(tempDir, parsed.subpath, {
1188
- includeInternal,
1189
- fullDepth: options.fullDepth,
1190
- });
1191
- }
1192
-
1193
- if (skills.length === 0) {
1194
- spinner.stop(pc.red('No skills found'));
1195
- p.outro(
1196
- pc.red('No valid skills found. Skills require a SKILL.md with name and description.')
1197
- );
1198
- await cleanup(tempDir);
1199
- process.exit(1);
1200
- }
1201
-
1202
- if (!blobResult) {
1203
- spinner.stop(`Found ${pc.green(skills.length)} skill${skills.length > 1 ? 's' : ''}`);
1204
- }
1205
-
1206
- if (options.list) {
1207
- console.log();
1208
- p.log.step(pc.bold('Available Skills'));
1209
-
1210
- // Group available skills by plugin for list output
1211
- const groupedSkills: Record<string, Skill[]> = {};
1212
- const ungroupedSkills: Skill[] = [];
1213
-
1214
- for (const skill of skills) {
1215
- if (skill.pluginName) {
1216
- const group = skill.pluginName;
1217
- if (!groupedSkills[group]) groupedSkills[group] = [];
1218
- groupedSkills[group].push(skill);
1219
- } else {
1220
- ungroupedSkills.push(skill);
1221
- }
1222
- }
1223
-
1224
- // Print groups
1225
- const sortedGroups = Object.keys(groupedSkills).sort();
1226
- for (const group of sortedGroups) {
1227
- // Convert kebab-case to Title Case for display header
1228
- const title = group
1229
- .split('-')
1230
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
1231
- .join(' ');
1232
-
1233
- console.log(pc.bold(title));
1234
- for (const skill of groupedSkills[group]!) {
1235
- p.log.message(` ${pc.cyan(getSkillDisplayName(skill))}`);
1236
- p.log.message(` ${pc.dim(skill.description)}`);
1237
- }
1238
- console.log();
1239
- }
1240
-
1241
- // Print ungrouped
1242
- if (ungroupedSkills.length > 0) {
1243
- if (sortedGroups.length > 0) console.log(pc.bold('General'));
1244
- for (const skill of ungroupedSkills) {
1245
- p.log.message(` ${pc.cyan(getSkillDisplayName(skill))}`);
1246
- p.log.message(` ${pc.dim(skill.description)}`);
1247
- }
1248
- }
1249
-
1250
- console.log();
1251
- p.outro('Use --skill <name> to install specific skills');
1252
- await cleanup(tempDir);
1253
- process.exit(0);
1254
- }
1255
-
1256
- let selectedSkills: Skill[];
1257
-
1258
- if (options.skill?.includes('*')) {
1259
- // --skill '*' selects all skills
1260
- selectedSkills = skills;
1261
- p.log.info(`Installing all ${skills.length} skills`);
1262
- } else if (options.skill && options.skill.length > 0) {
1263
- selectedSkills = filterSkills(skills, options.skill);
1264
-
1265
- if (selectedSkills.length === 0) {
1266
- p.log.error(`No matching skills found for: ${options.skill.join(', ')}`);
1267
- p.log.info('Available skills:');
1268
- for (const s of skills) {
1269
- p.log.message(` - ${getSkillDisplayName(s)}`);
1270
- }
1271
- await cleanup(tempDir);
1272
- process.exit(1);
1273
- }
1274
-
1275
- p.log.info(
1276
- `Selected ${selectedSkills.length} skill${selectedSkills.length !== 1 ? 's' : ''}: ${selectedSkills.map((s) => pc.cyan(getSkillDisplayName(s))).join(', ')}`
1277
- );
1278
- } else if (skills.length === 1) {
1279
- selectedSkills = skills;
1280
- const firstSkill = skills[0]!;
1281
- p.log.info(`Skill: ${pc.cyan(getSkillDisplayName(firstSkill))}`);
1282
- p.log.message(pc.dim(firstSkill.description));
1283
- } else if (options.yes) {
1284
- selectedSkills = skills;
1285
- p.log.info(`Installing all ${skills.length} skills`);
1286
- } else {
1287
- // Sort skills by plugin name first, then by skill name
1288
- const sortedSkills = [...skills].sort((a, b) => {
1289
- if (a.pluginName && !b.pluginName) return -1;
1290
- if (!a.pluginName && b.pluginName) return 1;
1291
- if (a.pluginName && b.pluginName && a.pluginName !== b.pluginName) {
1292
- return a.pluginName.localeCompare(b.pluginName);
1293
- }
1294
- return getSkillDisplayName(a).localeCompare(getSkillDisplayName(b));
1295
- });
1296
-
1297
- // Check if any skills have plugin grouping
1298
- const hasGroups = sortedSkills.some((s) => s.pluginName);
1299
-
1300
- // Pre-check which skills are already installed (project .agents/skills/ or global ~/.agents/skills/)
1301
- // Uses the 'universal' agent which maps to the ADG canonical paths for both scopes.
1302
- const alreadyInstalledSet = new Set<string>();
1303
- {
1304
- const checks = await Promise.all(
1305
- sortedSkills.map(async (s) => {
1306
- const name = getSkillDisplayName(s);
1307
- const [projectInstalled, globalInstalled] = await Promise.all([
1308
- isSkillInstalled(name, 'universal', { global: false }),
1309
- isSkillInstalled(name, 'universal', { global: true }),
1310
- ]);
1311
- return { name, installed: projectInstalled || globalInstalled };
1312
- })
1313
- );
1314
- for (const { name, installed } of checks) {
1315
- if (installed) alreadyInstalledSet.add(name);
1316
- }
1317
- }
1318
-
1319
- const skillLabel = (s: Skill): string => {
1320
- const name = getSkillDisplayName(s);
1321
- const badge = alreadyInstalledSet.has(name) ? pc.dim('[↑] ') : ' ';
1322
- return `${badge}${name}`;
1323
- };
1324
-
1325
- let selected: Skill[] | symbol;
1326
-
1327
- if (hasGroups) {
1328
- // Build grouped options for groupMultiselect
1329
- const kebabToTitle = (s: string) =>
1330
- s
1331
- .split('-')
1332
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
1333
- .join(' ');
1334
-
1335
- const grouped: Record<string, p.Option<Skill>[]> = {};
1336
- for (const s of sortedSkills) {
1337
- const groupName = s.pluginName ? kebabToTitle(s.pluginName) : 'Other';
1338
- if (!grouped[groupName]) grouped[groupName] = [];
1339
- grouped[groupName]!.push({
1340
- value: s,
1341
- label: skillLabel(s),
1342
- hint: s.description.length > 60 ? s.description.slice(0, 57) + '...' : s.description,
1343
- });
1344
- }
1345
-
1346
- selected = await p.groupMultiselect({
1347
- message: `Select skills to install ${pc.dim('(space to toggle)')}`,
1348
- options: grouped,
1349
- required: true,
1350
- });
1351
- } else {
1352
- const skillChoices = sortedSkills.map((s) => ({
1353
- value: s,
1354
- label: skillLabel(s),
1355
- hint: s.description.length > 60 ? s.description.slice(0, 57) + '...' : s.description,
1356
- }));
1357
-
1358
- selected = await multiselect({
1359
- message: 'Select skills to install',
1360
- options: skillChoices,
1361
- required: true,
1362
- });
1363
- }
1364
-
1365
- if (p.isCancel(selected)) {
1366
- p.cancel('Installation cancelled');
1367
- await cleanup(tempDir);
1368
- process.exit(0);
1369
- }
1370
-
1371
- selectedSkills = selected as Skill[];
1372
- }
1373
-
1374
- // Kick off security audit fetch early (non-blocking) so it runs
1375
- // in parallel with agent selection, scope, and mode prompts.
1376
- const ownerRepoForAudit = getOwnerRepo(parsed);
1377
- const auditPromise = ownerRepoForAudit
1378
- ? fetchAuditData(
1379
- ownerRepoForAudit,
1380
- selectedSkills.map((s) => getSkillDisplayName(s))
1381
- )
1382
- : Promise.resolve(null);
1383
-
1384
- let targetAgents: AgentType[];
1385
- const validAgents = Object.keys(agents);
1386
-
1387
- if (options.agent?.includes('*')) {
1388
- // --agent '*' selects all agents
1389
- targetAgents = validAgents as AgentType[];
1390
- p.log.info(`Installing to all ${targetAgents.length} agents`);
1391
- } else if (options.agent && options.agent.length > 0) {
1392
- const invalidAgents = options.agent.filter((a) => !validAgents.includes(a));
1393
-
1394
- if (invalidAgents.length > 0) {
1395
- p.log.error(`Invalid agents: ${invalidAgents.join(', ')}`);
1396
- p.log.info(`Valid agents: ${validAgents.join(', ')}`);
1397
- await cleanup(tempDir);
1398
- process.exit(1);
1399
- }
1400
-
1401
- targetAgents = options.agent as AgentType[];
1402
- } else {
1403
- spinner.start('Loading agents...');
1404
- const installedAgents = await detectInstalledAgents();
1405
- const totalAgents = Object.keys(agents).length;
1406
- spinner.stop(`${totalAgents} agents`);
1407
-
1408
- if (installedAgents.includes('eve') && (options.yes || !agentResult.isAgent)) {
1409
- const useEve = options.yes
1410
- ? true
1411
- : await p.confirm({
1412
- message: formatEveInstallPromptMessage(selectedSkills),
1413
- initialValue: true,
1414
- });
1415
-
1416
- if (p.isCancel(useEve)) {
1417
- p.cancel('Installation cancelled');
1418
- await cleanup(tempDir);
1419
- process.exit(0);
1420
- }
1421
-
1422
- if (useEve) {
1423
- targetAgents = ['eve'];
1424
- p.log.info(`Installing to: ${pc.cyan(EVE_AGENT_LABEL)}`);
1425
- } else {
1426
- const selected = await selectAgentsInteractive({ global: options.global });
1427
-
1428
- if (p.isCancel(selected)) {
1429
- p.cancel('Installation cancelled');
1430
- await cleanup(tempDir);
1431
- process.exit(0);
1432
- }
1433
-
1434
- targetAgents = selected as AgentType[];
1435
- }
1436
- } else if (installedAgents.length === 0) {
1437
- if (options.yes) {
1438
- targetAgents = validAgents as AgentType[];
1439
- p.log.info('Installing to all agents');
1440
- } else {
1441
- p.log.info('Select agents to install skills to');
1442
-
1443
- const allAgentChoices = Object.entries(agents)
1444
- .filter(([key]) => key !== 'eve')
1445
- .map(([key, config]) => ({
1446
- value: key as AgentType,
1447
- label: config.displayName,
1448
- }));
1449
-
1450
- // Use helper to prompt with search
1451
- const selected = await promptForAgents(
1452
- 'Which agents do you want to install to?',
1453
- allAgentChoices
1454
- );
1455
-
1456
- if (p.isCancel(selected)) {
1457
- p.cancel('Installation cancelled');
1458
- await cleanup(tempDir);
1459
- process.exit(0);
1460
- }
1461
-
1462
- targetAgents = selected as AgentType[];
1463
- }
1464
- } else if (installedAgents.length === 1 || options.yes) {
1465
- // Auto-select detected agents + ensure universal agents are included
1466
- targetAgents = ensureUniversalAgents(installedAgents);
1467
- if (installedAgents.length === 1) {
1468
- const firstAgent = installedAgents[0]!;
1469
- p.log.info(`Installing to: ${pc.cyan(agents[firstAgent].displayName)}`);
1470
- } else {
1471
- p.log.info(
1472
- `Installing to: ${installedAgents.map((a) => pc.cyan(agents[a].displayName)).join(', ')}`
1473
- );
1474
- }
1475
- } else {
1476
- const selected = await selectAgentsInteractive({ global: options.global });
1477
-
1478
- if (p.isCancel(selected)) {
1479
- p.cancel('Installation cancelled');
1480
- await cleanup(tempDir);
1481
- process.exit(0);
1482
- }
1483
-
1484
- targetAgents = selected as AgentType[];
1485
- }
1486
- }
1487
-
1488
- // An explicit --subagent flag implies the user wants to target Eve.
1489
- if (options.subagent && options.subagent.length > 0 && !targetAgents.includes('eve')) {
1490
- targetAgents = [...targetAgents, 'eve'];
1491
- }
1492
-
1493
- // Eve supports subagents, each with their own skills directory at
1494
- // agent/subagents/<name>/skills in addition to the root agent/skills.
1495
- // When Eve is a target, choose which of those to install into.
1496
- let eveSubagentTargets: Array<string | undefined> = [undefined];
1497
- if (targetAgents.includes('eve')) {
1498
- const availableSubagents = getEveSubagents(process.cwd());
1499
-
1500
- if (options.subagent && options.subagent.length > 0) {
1501
- // Non-interactive: 'root' or '.' selects the root agent.
1502
- eveSubagentTargets = options.subagent.map((s) =>
1503
- s === 'root' || s === '.' ? undefined : s
1504
- );
1505
- } else if (availableSubagents.length > 0 && !options.yes) {
1506
- const subagentChoices = [
1507
- { value: '', label: 'Root agent', hint: 'agent/skills' },
1508
- ...availableSubagents.map((name) => ({
1509
- value: name,
1510
- label: name,
1511
- hint: `agent/subagents/${name}/skills`,
1512
- })),
1513
- ];
1514
-
1515
- const selectedSubagents = await p.multiselect({
1516
- message: 'Where should Eve skills be installed?',
1517
- options: subagentChoices,
1518
- initialValues: [''],
1519
- required: true,
1520
- });
1521
-
1522
- if (p.isCancel(selectedSubagents)) {
1523
- p.cancel('Installation cancelled');
1524
- await cleanup(tempDir);
1525
- process.exit(0);
1526
- }
1527
-
1528
- eveSubagentTargets = (selectedSubagents as string[]).map((s) => (s === '' ? undefined : s));
1529
- }
1530
- }
1531
-
1532
- const installTargets = buildInstallTargets(targetAgents, eveSubagentTargets);
1533
-
1534
- let installGlobally = options.global ?? false;
1535
-
1536
- // Check if any selected agents support global installation
1537
- const supportsGlobal = targetAgents.some((a) => agents[a].globalSkillsDir !== undefined);
1538
-
1539
- if (options.global === undefined && !options.yes && supportsGlobal) {
1540
- const scope = await p.select({
1541
- message: 'Installation scope',
1542
- options: [
1543
- {
1544
- value: false,
1545
- label: 'Project',
1546
- hint: 'Install in current directory (committed with your project)',
1547
- },
1548
- {
1549
- value: true,
1550
- label: 'Global',
1551
- hint: 'Install in home directory (available across all projects)',
1552
- },
1553
- ],
1554
- });
1555
-
1556
- if (p.isCancel(scope)) {
1557
- p.cancel('Installation cancelled');
1558
- await cleanup(tempDir);
1559
- process.exit(0);
1560
- }
1561
-
1562
- installGlobally = scope as boolean;
1563
- }
1564
-
1565
- // Determine install mode (symlink vs copy)
1566
- let installMode: InstallMode = options.copy ? 'copy' : 'symlink';
1567
-
1568
- // Only prompt for install mode when there are multiple unique target directories.
1569
- // When all selected targets share the same skillsDir, symlink vs copy is meaningless.
1570
- // Eve writes skill files directly into each (sub)agent dir, so a symlink prompt is
1571
- // never meaningful when every target is Eve.
1572
- const allEve = installTargets.every((t) => t.agent === 'eve');
1573
- const uniqueDirs = new Set(
1574
- installTargets.map((t) =>
1575
- t.subagent ? `eve:subagent:${t.subagent}` : agents[t.agent].skillsDir
1576
- )
1577
- );
1578
-
1579
- if (!options.copy && !options.yes && uniqueDirs.size > 1 && !allEve) {
1580
- const modeChoice = await p.select({
1581
- message: 'Installation method',
1582
- options: [
1583
- {
1584
- value: 'symlink',
1585
- label: 'Symlink (Recommended)',
1586
- hint: 'Single source of truth, easy updates',
1587
- },
1588
- { value: 'copy', label: 'Copy to all agents', hint: 'Independent copies for each agent' },
1589
- ],
1590
- });
1591
-
1592
- if (p.isCancel(modeChoice)) {
1593
- p.cancel('Installation cancelled');
1594
- await cleanup(tempDir);
1595
- process.exit(0);
1596
- }
1597
-
1598
- installMode = modeChoice as InstallMode;
1599
- } else if (uniqueDirs.size <= 1 || allEve) {
1600
- // Single target directory (or all-Eve) — default to copy (no symlink needed)
1601
- installMode = 'copy';
1602
- }
1603
-
1604
- const cwd = process.cwd();
1605
-
1606
- // Build installation summary
1607
- const summaryLines: string[] = [];
1608
-
1609
- // Check if any skill will be overwritten (parallel)
1610
- const overwriteChecks = await Promise.all(
1611
- selectedSkills.flatMap((skill) =>
1612
- installTargets.map(async (target) => ({
1613
- skillName: skill.name,
1614
- target,
1615
- installed: await isSkillInstalled(skill.name, target.agent, {
1616
- global: installGlobally,
1617
- eveSubagent: target.subagent,
1618
- }),
1619
- }))
1620
- )
1621
- );
1622
- // Keyed by skill name → target key → installed?
1623
- const overwriteStatus = new Map<string, Map<string, boolean>>();
1624
- for (const { skillName, target, installed } of overwriteChecks) {
1625
- if (!overwriteStatus.has(skillName)) {
1626
- overwriteStatus.set(skillName, new Map());
1627
- }
1628
- overwriteStatus.get(skillName)!.set(targetKey(target), installed);
1629
- }
1630
-
1631
- // Group selected skills for summary
1632
- const groupedSummary: Record<string, Skill[]> = {};
1633
- const ungroupedSummary: Skill[] = [];
1634
-
1635
- for (const skill of selectedSkills) {
1636
- if (skill.pluginName) {
1637
- const group = skill.pluginName;
1638
- if (!groupedSummary[group]) groupedSummary[group] = [];
1639
- groupedSummary[group].push(skill);
1640
- } else {
1641
- ungroupedSummary.push(skill);
1642
- }
1643
- }
1644
-
1645
- // Helper to print summary lines for a list of skills
1646
- const printSkillSummary = (skills: Skill[]) => {
1647
- for (const skill of skills) {
1648
- if (summaryLines.length > 0) summaryLines.push('');
1649
-
1650
- const canonicalPath =
1651
- installTargets.length === 1
1652
- ? getCanonicalPath(skill.name, {
1653
- global: installGlobally,
1654
- agent: installTargets[0]!.agent,
1655
- eveSubagent: installTargets[0]!.subagent,
1656
- })
1657
- : getCanonicalPath(skill.name, { global: installGlobally });
1658
- const shortCanonical = shortenPath(canonicalPath, cwd);
1659
- summaryLines.push(`${pc.cyan(shortCanonical)}`);
1660
- summaryLines.push(...buildTargetSummaryLines(installTargets, installMode));
1661
-
1662
- const skillOverwrites = overwriteStatus.get(skill.name);
1663
- const overwriteAgents = installTargets
1664
- .filter((t) => skillOverwrites?.get(targetKey(t)))
1665
- .map(targetDisplayName);
1666
-
1667
- if (overwriteAgents.length > 0) {
1668
- summaryLines.push(` ${pc.yellow('overwrites:')} ${formatList(overwriteAgents)}`);
1669
- }
1670
- }
1671
- };
1672
-
1673
- // Build grouped summary
1674
- const sortedGroups = Object.keys(groupedSummary).sort();
1675
-
1676
- for (const group of sortedGroups) {
1677
- const title = group
1678
- .split('-')
1679
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
1680
- .join(' ');
1681
-
1682
- summaryLines.push('');
1683
- summaryLines.push(pc.bold(title));
1684
- printSkillSummary(groupedSummary[group]!);
1685
- }
1686
-
1687
- if (ungroupedSummary.length > 0) {
1688
- if (sortedGroups.length > 0) {
1689
- summaryLines.push('');
1690
- summaryLines.push(pc.bold('General'));
1691
- }
1692
- printSkillSummary(ungroupedSummary);
1693
- }
1694
-
1695
- console.log();
1696
- p.note(summaryLines.join('\n'), 'Installation Summary');
1697
-
1698
- // Await and display security audit results (started earlier in parallel)
1699
- // Wrapped in try/catch so a failed audit fetch never blocks installation.
1700
- try {
1701
- const auditData = await auditPromise;
1702
- if (auditData && ownerRepoForAudit) {
1703
- const securityLines = buildSecurityLines(
1704
- auditData,
1705
- selectedSkills.map((s) => ({
1706
- slug: getSkillDisplayName(s),
1707
- displayName: getSkillDisplayName(s),
1708
- })),
1709
- ownerRepoForAudit
1710
- );
1711
- if (securityLines.length > 0) {
1712
- p.note(securityLines.join('\n'), 'Security Risk Assessments');
1713
- }
1714
- }
1715
- } catch {
1716
- // Silently skip — security info is advisory only
1717
- }
1718
-
1719
- if (!options.yes) {
1720
- const confirmed = await p.confirm({ message: 'Proceed with installation?' });
1721
-
1722
- if (p.isCancel(confirmed) || !confirmed) {
1723
- p.cancel('Installation cancelled');
1724
- await cleanup(tempDir);
1725
- process.exit(0);
1726
- }
1727
- }
1728
-
1729
- spinner.start('Installing skills...');
1730
-
1731
- const results: {
1732
- skill: string;
1733
- agent: string;
1734
- success: boolean;
1735
- path: string;
1736
- canonicalPath?: string;
1737
- mode: InstallMode;
1738
- symlinkFailed?: boolean;
1739
- error?: string;
1740
- pluginName?: string;
1741
- }[] = [];
1742
-
1743
- for (const skill of selectedSkills) {
1744
- for (const target of installTargets) {
1745
- const { agent, subagent } = target;
1746
- let result;
1747
- if (blobResult && 'files' in skill) {
1748
- // Blob-based install: write files from snapshot
1749
- const blobSkill = skill as BlobSkill;
1750
- result = await installBlobSkillForAgent(
1751
- { installName: blobSkill.name, files: blobSkill.files },
1752
- agent,
1753
- { global: installGlobally, mode: installMode, eveSubagent: subagent }
1754
- );
1755
- } else if (tempDir && skill.path === tempDir && skill.rawContent) {
1756
- // Remote root-level SKILL.md: install the skill file, not the whole repository.
1757
- result = await installBlobSkillForAgent(
1758
- { installName: skill.name, files: [{ path: 'SKILL.md', contents: skill.rawContent }] },
1759
- agent,
1760
- { global: installGlobally, mode: installMode }
1761
- );
1762
- } else {
1763
- // Disk-based install: copy from cloned/local directory
1764
- result = await installSkillForAgent(skill, agent, {
1765
- global: installGlobally,
1766
- mode: installMode,
1767
- eveSubagent: subagent,
1768
- });
1769
- }
1770
- results.push({
1771
- skill: getSkillDisplayName(skill),
1772
- agent: targetDisplayName(target),
1773
- pluginName: skill.pluginName,
1774
- ...result,
1775
- });
1776
- }
1777
- }
1778
-
1779
- spinner.stop('Installation complete');
1780
-
1781
- console.log();
1782
- const successful = results.filter((r) => r.success);
1783
- const failed = results.filter((r) => !r.success);
1784
- // Track installation result
1785
- // Build skillFiles map: { skillName: relative path to SKILL.md from repo root }
1786
- const skillFiles: Record<string, string> = {};
1787
- for (const skill of selectedSkills) {
1788
- if (blobResult && 'repoPath' in skill) {
1789
- // Blob-based: repoPath is already the repo-relative path (e.g., "skills/react/SKILL.md")
1790
- skillFiles[skill.name] = (skill as BlobSkill).repoPath;
1791
- } else if (tempDir && skill.path === tempDir) {
1792
- // Skill is at root level of repo
1793
- skillFiles[skill.name] = 'SKILL.md';
1794
- } else if (tempDir && skill.path.startsWith(tempDir + sep)) {
1795
- // Compute path relative to repo root (tempDir), not search path
1796
- // Use forward slashes for telemetry (URL-style paths)
1797
- skillFiles[skill.name] =
1798
- skill.path
1799
- .slice(tempDir.length + 1)
1800
- .split(sep)
1801
- .join('/') + '/SKILL.md';
1802
- } else {
1803
- // Local path - skip telemetry for local installs
1804
- continue;
1805
- }
1806
- }
1807
-
1808
- // Normalize source to owner/repo format for telemetry
1809
- const normalizedSource = getOwnerRepo(parsed);
1810
-
1811
- const lockSource = getLockSource(parsed.url, normalizedSource);
1812
-
1813
- // Only track if we have a valid remote source and it's not a private repo.
1814
- // repoPrivacyPromise was started early (right after parsing) so it has
1815
- // already been running in parallel with the entire install — no stall here.
1816
- if (normalizedSource) {
1817
- const ownerRepo = parseOwnerRepo(normalizedSource);
1818
- if (ownerRepo) {
1819
- const isPrivate = await repoPrivacyPromise;
1820
- // Only send telemetry if repo is public (isPrivate === false)
1821
- // If we can't determine (null), err on the side of caution and skip telemetry
1822
- if (isPrivate === false) {
1823
- track({
1824
- event: 'install',
1825
- source: normalizedSource,
1826
- skills: selectedSkills.map((s) => s.name).join(','),
1827
- agents: targetAgents.join(','),
1828
- ...(installGlobally && { global: '1' }),
1829
- skillFiles: JSON.stringify(skillFiles),
1830
- });
1831
- }
1832
- } else {
1833
- // If we can't parse owner/repo, still send telemetry (for non-GitHub sources)
1834
- track({
1835
- event: 'install',
1836
- source: normalizedSource,
1837
- skills: selectedSkills.map((s) => s.name).join(','),
1838
- agents: targetAgents.join(','),
1839
- ...(installGlobally && { global: '1' }),
1840
- skillFiles: JSON.stringify(skillFiles),
1841
- });
1842
- }
1843
- }
1844
-
1845
- // Add to skill lock file for update tracking (only for global installs)
1846
- if (successful.length > 0 && installGlobally && normalizedSource) {
1847
- const successfulSkillNames = new Set(successful.map((r) => r.skill));
1848
-
1849
- // For GitHub clone installs, fetch the repo tree once and reuse it
1850
- // for all skills — avoids N sequential API calls that take ~400ms each.
1851
- let cachedTree: Awaited<ReturnType<typeof fetchRepoTree>> | undefined;
1852
- if (parsed.type === 'github' && !blobResult) {
1853
- cachedTree = await fetchRepoTree(normalizedSource, parsed.ref, getGitHubToken);
1854
- }
1855
-
1856
- for (const skill of selectedSkills) {
1857
- const skillDisplayName = getSkillDisplayName(skill);
1858
- if (successfulSkillNames.has(skillDisplayName)) {
1859
- try {
1860
- let skillFolderHash = '';
1861
- const skillPathValue = skillFiles[skill.name];
1862
-
1863
- if (blobResult && skillPathValue) {
1864
- const hash = getSkillFolderHashFromTree(blobResult.tree, skillPathValue);
1865
- if (hash) skillFolderHash = hash;
1866
- } else if (parsed.type === 'github' && skillPathValue && cachedTree) {
1867
- const hash = getSkillFolderHashFromTree(cachedTree, skillPathValue);
1868
- if (hash) skillFolderHash = hash;
1869
- } else if (skillPathValue && tempDir) {
1870
- const folder = dirname(skillPathValue);
1871
- if (parsed.type === 'github') {
1872
- // ADG patch: github sources are compared against the git tree SHA
1873
- // at update time. When the tree API failed and we fell back to a
1874
- // clone, derive that same tree SHA from the clone instead of a
1875
- // sha256 content hash — otherwise every update perpetually
1876
- // re-flags this skill (hash schemes can never match).
1877
- const treeSha = await gitTreeShaForFolder(tempDir, folder === '.' ? '' : folder);
1878
- if (treeSha) skillFolderHash = treeSha;
1879
- } else {
1880
- const skillDir = join(tempDir, folder);
1881
- const hash = await computeSkillFolderHash(skillDir);
1882
- if (hash) skillFolderHash = hash;
1883
- }
1884
- }
1885
-
1886
- await addSkillToLock(skill.name, {
1887
- source: lockSource || normalizedSource,
1888
- sourceType: parsed.type,
1889
- sourceUrl: parsed.url,
1890
- ref: parsed.ref,
1891
- skillPath: skillPathValue,
1892
- skillFolderHash,
1893
- pluginName: skill.pluginName,
1894
- });
1895
- } catch {
1896
- // Don't fail installation if lock file update fails
1897
- }
1898
- }
1899
- }
1900
- }
1901
-
1902
- // Add to local lock file for project-scoped installs
1903
- if (successful.length > 0 && !installGlobally) {
1904
- const successfulSkillNames = new Set(successful.map((r) => r.skill));
1905
- // Record Eve subagent placement (root = '') so `update` can restore it.
1906
- // Only meaningful when Eve is among the targets and a non-root subagent
1907
- // was selected; otherwise omit for a clean, minimal lock entry.
1908
- const eveSubagents = targetAgents.includes('eve')
1909
- ? eveSubagentTargets.map((s) => s ?? '')
1910
- : undefined;
1911
- const recordSubagents =
1912
- eveSubagents && (eveSubagents.length > 1 || eveSubagents.some((s) => s !== ''));
1913
- for (const skill of selectedSkills) {
1914
- const skillDisplayName = getSkillDisplayName(skill);
1915
- if (successfulSkillNames.has(skillDisplayName)) {
1916
- try {
1917
- // For blob skills, use the snapshot hash; for disk skills, compute from files
1918
- const computedHash =
1919
- blobResult && 'snapshotHash' in skill
1920
- ? (skill as BlobSkill).snapshotHash
1921
- : tempDir && skill.path === tempDir && skill.rawContent
1922
- ? computeSingleFileSkillHash(skill.rawContent)
1923
- : await computeSkillFolderHash(skill.path);
1924
- const skillPathValue = skillFiles[skill.name];
1925
- await addSkillToLocalLock(
1926
- skill.name,
1927
- {
1928
- source: lockSource || parsed.url,
1929
- ref: parsed.ref,
1930
- sourceType: parsed.type,
1931
- ...(skillPathValue && { skillPath: skillPathValue }),
1932
- computedHash,
1933
- ...(recordSubagents && { subagents: eveSubagents }),
1934
- },
1935
- cwd
1936
- );
1937
- } catch {
1938
- // Don't fail installation if lock file update fails
1939
- }
1940
- }
1941
- }
1942
- }
1943
-
1944
- if (successful.length > 0) {
1945
- const bySkill = new Map<string, typeof results>();
1946
-
1947
- // Group results by plugin name
1948
- const groupedResults: Record<string, typeof results> = {};
1949
- const ungroupedResults: typeof results = [];
1950
-
1951
- for (const r of successful) {
1952
- const skillResults = bySkill.get(r.skill) || [];
1953
- skillResults.push(r);
1954
- bySkill.set(r.skill, skillResults);
1955
-
1956
- // We only need to group once per skill (take the first result for that skill)
1957
- if (skillResults.length === 1) {
1958
- if (r.pluginName) {
1959
- const group = r.pluginName;
1960
- if (!groupedResults[group]) groupedResults[group] = [];
1961
- // We'll store just one entry per skill here to drive the loop
1962
- groupedResults[group].push(r);
1963
- } else {
1964
- ungroupedResults.push(r);
1965
- }
1966
- }
1967
- }
1968
-
1969
- const skillCount = bySkill.size;
1970
- const symlinkFailures = successful.filter((r) => r.mode === 'symlink' && r.symlinkFailed);
1971
- const copiedAgents = symlinkFailures.map((r) => r.agent);
1972
- const resultLines: string[] = [];
1973
-
1974
- const printSkillResults = (entries: typeof results) => {
1975
- for (const entry of entries) {
1976
- const skillResults = bySkill.get(entry.skill) || [];
1977
- const firstResult = skillResults[0]!;
1978
-
1979
- if (firstResult.mode === 'copy') {
1980
- // Copy mode: show skill name and list all agent paths
1981
- resultLines.push(`${pc.green('✓')} ${entry.skill} ${pc.dim('(copied)')}`);
1982
- for (const r of skillResults) {
1983
- const shortPath = shortenPath(r.path, cwd);
1984
- resultLines.push(` ${pc.dim('→')} ${shortPath}`);
1985
- }
1986
- } else {
1987
- // Symlink mode: show canonical path and universal/symlinked agents
1988
- if (firstResult.canonicalPath) {
1989
- const shortPath = shortenPath(firstResult.canonicalPath, cwd);
1990
- resultLines.push(`${pc.green('✓')} ${shortPath}`);
1991
- } else {
1992
- resultLines.push(`${pc.green('✓')} ${entry.skill}`);
1993
- }
1994
- resultLines.push(...buildResultLines(skillResults, targetAgents));
1995
- }
1996
- }
1997
- };
1998
-
1999
- // Print grouped results
2000
- const sortedResultGroups = Object.keys(groupedResults).sort();
2001
-
2002
- for (const group of sortedResultGroups) {
2003
- const title = group
2004
- .split('-')
2005
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
2006
- .join(' ');
2007
-
2008
- resultLines.push('');
2009
- resultLines.push(pc.bold(title));
2010
- printSkillResults(groupedResults[group]!);
2011
- }
2012
-
2013
- if (ungroupedResults.length > 0) {
2014
- if (sortedResultGroups.length > 0) {
2015
- resultLines.push('');
2016
- resultLines.push(pc.bold('General'));
2017
- }
2018
- printSkillResults(ungroupedResults);
2019
- }
2020
-
2021
- const title = pc.green(`Installed ${skillCount} skill${skillCount !== 1 ? 's' : ''}`);
2022
- p.note(resultLines.join('\n'), title);
2023
-
2024
- // Show symlink failure warning (only for symlink mode)
2025
- if (symlinkFailures.length > 0) {
2026
- p.log.warn(pc.yellow(`Symlinks failed for: ${formatList(copiedAgents)}`));
2027
- p.log.message(
2028
- pc.dim(
2029
- ' Files were copied instead. On Windows, enable Developer Mode for symlink support.'
2030
- )
2031
- );
2032
- }
2033
- }
2034
-
2035
- if (failed.length > 0) {
2036
- console.log();
2037
- p.log.error(pc.red(`Failed to install ${failed.length}`));
2038
- for (const r of failed) {
2039
- p.log.message(` ${pc.red('✗')} ${r.skill} → ${r.agent}: ${pc.dim(r.error)}`);
2040
- }
2041
- }
2042
-
2043
- console.log();
2044
- p.outro(
2045
- pc.green('Done!') +
2046
- pc.dim(' Review skills before use; they run with full agent permissions.')
2047
- );
2048
-
2049
- // Prompt for find-skills after successful install
2050
- await promptForFindSkills(options, targetAgents);
2051
- } catch (error) {
2052
- if (error instanceof GitCloneError) {
2053
- p.log.error(pc.red('Failed to clone repository'));
2054
- // Print each line of the error message separately for better formatting
2055
- for (const line of error.message.split('\n')) {
2056
- p.log.message(pc.dim(line));
2057
- }
2058
- } else {
2059
- p.log.error(error instanceof Error ? error.message : 'Unknown error occurred');
2060
- }
2061
- showInstallTip();
2062
- p.outro(pc.red('Installation failed'));
2063
- process.exit(1);
2064
- } finally {
2065
- await cleanup(tempDir);
2066
- }
2067
- }
2068
-
2069
- // Cleanup helper
2070
- async function cleanup(tempDir: string | null) {
2071
- if (tempDir) {
2072
- try {
2073
- await cleanupTempDir(tempDir);
2074
- } catch {
2075
- // Ignore cleanup errors
2076
- }
2077
- }
2078
- }
2079
-
2080
- /**
2081
- * Prompt user to install the find-skills skill after their first installation.
2082
- */
2083
- async function promptForFindSkills(
2084
- options?: AddOptions,
2085
- targetAgents?: AgentType[]
2086
- ): Promise<void> {
2087
- // Skip if already dismissed or not in interactive mode
2088
- if (!process.stdin.isTTY) return;
2089
- if (options?.yes) return;
2090
-
2091
- try {
2092
- const dismissed = await isPromptDismissed('findSkillsPrompt');
2093
- if (dismissed) return;
2094
-
2095
- // Check if find-skills is already installed
2096
- const findSkillsInstalled = await isSkillInstalled('find-skills', 'claude-code', {
2097
- global: true,
2098
- });
2099
- if (findSkillsInstalled) {
2100
- // Mark as dismissed so we don't check again
2101
- await dismissPrompt('findSkillsPrompt');
2102
- return;
2103
- }
2104
-
2105
- console.log();
2106
- p.log.message(pc.dim("One-time prompt - you won't be asked again if you dismiss."));
2107
- const install = await p.confirm({
2108
- message: `Install the ${pc.cyan('find-skills')} skill? It helps your agent discover and suggest skills.`,
2109
- });
2110
-
2111
- if (p.isCancel(install)) {
2112
- await dismissPrompt('findSkillsPrompt');
2113
- return;
2114
- }
2115
-
2116
- if (install) {
2117
- // Install find-skills to the same agents the user selected, excluding replit
2118
- await dismissPrompt('findSkillsPrompt');
2119
-
2120
- // Filter out replit from target agents
2121
- const findSkillsAgents = targetAgents?.filter((a) => a !== 'replit');
2122
-
2123
- // Skip if no valid agents remain after filtering
2124
- if (!findSkillsAgents || findSkillsAgents.length === 0) {
2125
- return;
2126
- }
2127
-
2128
- console.log();
2129
- p.log.step('Installing find-skills skill...');
2130
-
2131
- try {
2132
- // Call runAdd directly
2133
- await runAdd(['vercel-labs/skills'], {
2134
- skill: ['find-skills'],
2135
- global: true,
2136
- yes: true,
2137
- agent: findSkillsAgents,
2138
- });
2139
- } catch {
2140
- p.log.warn('Failed to install find-skills. You can try again with:');
2141
- p.log.message(pc.dim(' adg skills add vercel-labs/skills@find-skills -g -y --all'));
2142
- }
2143
- } else {
2144
- // User declined - dismiss the prompt
2145
- await dismissPrompt('findSkillsPrompt');
2146
- p.log.message(
2147
- pc.dim('You can install it later with: adg skills add vercel-labs/skills@find-skills')
2148
- );
2149
- }
2150
- } catch {
2151
- // Don't fail the main installation if prompt fails
2152
- }
2153
- }
2154
-
2155
- // Parse command line options from args array
2156
- export function parseAddOptions(args: string[]): { source: string[]; options: AddOptions } {
2157
- const options: AddOptions = {};
2158
- const source: string[] = [];
2159
-
2160
- for (let i = 0; i < args.length; i++) {
2161
- const arg = args[i];
2162
-
2163
- if (arg === '-g' || arg === '--global') {
2164
- options.global = true;
2165
- } else if (arg === '-y' || arg === '--yes') {
2166
- options.yes = true;
2167
- } else if (arg === '-l' || arg === '--list') {
2168
- options.list = true;
2169
- } else if (arg === '--all') {
2170
- options.all = true;
2171
- } else if (arg === '-a' || arg === '--agent') {
2172
- options.agent = options.agent || [];
2173
- i++;
2174
- let nextArg = args[i];
2175
- while (i < args.length && nextArg && !nextArg.startsWith('-')) {
2176
- options.agent.push(nextArg);
2177
- i++;
2178
- nextArg = args[i];
2179
- }
2180
- i--; // Back up one since the loop will increment
2181
- } else if (arg === '-s' || arg === '--skill') {
2182
- options.skill = options.skill || [];
2183
- i++;
2184
- let nextArg = args[i];
2185
- while (i < args.length && nextArg && !nextArg.startsWith('-')) {
2186
- options.skill.push(nextArg);
2187
- i++;
2188
- nextArg = args[i];
2189
- }
2190
- i--; // Back up one since the loop will increment
2191
- } else if (arg === '--full-depth') {
2192
- options.fullDepth = true;
2193
- } else if (arg === '--copy') {
2194
- options.copy = true;
2195
- } else if (arg === '--dangerously-accept-openclaw-risks') {
2196
- options.dangerouslyAcceptOpenclawRisks = true;
2197
- } else if (arg === '--subagent') {
2198
- options.subagent = options.subagent || [];
2199
- i++;
2200
- let nextArg = args[i];
2201
- while (i < args.length && nextArg && !nextArg.startsWith('-')) {
2202
- options.subagent.push(nextArg);
2203
- i++;
2204
- nextArg = args[i];
2205
- }
2206
- i--; // Back up one since the loop will increment
2207
- } else if (arg && !arg.startsWith('-')) {
2208
- source.push(arg);
2209
- }
2210
- }
2211
-
2212
- return { source, options };
2213
- }