-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathinstall.ts
More file actions
460 lines (384 loc) · 16.1 KB
/
install.ts
File metadata and controls
460 lines (384 loc) · 16.1 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
import { existsSync, mkdirSync, cpSync, rmSync, symlinkSync } from 'node:fs';
import { join } from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
import { Command, Option } from 'clipanion';
import { detectProvider, isLocalPath, getProvider, evaluateSkillDirectory, SkillScanner, formatSummary, Severity } from '@skillkit/core';
import type { SkillMetadata, GitProvider, AgentType } from '@skillkit/core';
import { isPathInside } from '@skillkit/core';
import { getAdapter, detectAgent, getAllAdapters } from '@skillkit/agents';
import { getInstallDir, saveSkillMetadata } from '../helpers.js';
import {
welcome,
colors,
symbols,
formatAgent,
getAgentIcon,
isCancel,
spinner,
quickAgentSelect,
skillMultiselect,
selectInstallMethod,
confirm,
outro,
cancel,
step,
success,
error,
warn,
showInstallSummary,
showNextSteps,
saveLastAgents,
getLastAgents,
formatQualityBadge,
getQualityGradeFromScore,
type InstallResult,
} from '../onboarding/index.js';
export class InstallCommand extends Command {
static override paths = [['install'], ['i'], ['add']];
static override usage = Command.Usage({
description: 'Install skills from GitHub, GitLab, Bitbucket, or local path',
examples: [
['Install from GitHub', '$0 install owner/repo'],
['Install from GitLab', '$0 install gitlab:owner/repo'],
['Install from Bitbucket', '$0 install bitbucket:owner/repo'],
['Install specific skill', '$0 install owner/repo --skill=pdf'],
['Install multiple skills (CI/CD)', '$0 install owner/repo --skills=pdf,xlsx'],
['Install all skills non-interactively', '$0 install owner/repo --all'],
['Install from local path', '$0 install ./my-skills'],
['Install globally', '$0 install owner/repo --global'],
['List available skills', '$0 install owner/repo --list'],
['Install to specific agents', '$0 install owner/repo --agent claude-code --agent cursor'],
],
});
source = Option.String({ required: true });
skills = Option.String('--skills,--skill,-s', {
description: 'Comma-separated list of skills to install (non-interactive)',
});
all = Option.Boolean('--all,-a', false, {
description: 'Install all discovered skills (non-interactive)',
});
yes = Option.Boolean('--yes,-y', false, {
description: 'Skip confirmation prompts',
});
global = Option.Boolean('--global,-g', false, {
description: 'Install to global skills directory',
});
force = Option.Boolean('--force,-f', false, {
description: 'Overwrite existing skills',
});
provider = Option.String('--provider,-p', {
description: 'Force specific provider (github, gitlab, bitbucket)',
});
list = Option.Boolean('--list,-l', false, {
description: 'List available skills without installing',
});
agent = Option.Array('--agent', {
description: 'Target specific agents (can specify multiple)',
});
quiet = Option.Boolean('--quiet,-q', false, {
description: 'Minimal output (no logo)',
});
scan = Option.Boolean('--scan', true, {
description: 'Run security scan before installing (default: true)',
});
async execute(): Promise<number> {
const isInteractive = process.stdin.isTTY && !this.skills && !this.all && !this.yes;
const s = spinner();
try {
// Show welcome logo for interactive mode
if (isInteractive && !this.quiet) {
welcome();
}
let providerAdapter = detectProvider(this.source);
if (this.provider) {
providerAdapter = getProvider(this.provider as GitProvider);
}
if (!providerAdapter) {
error(`Could not detect provider for: ${this.source}`);
console.log(colors.muted('Use --provider flag or specify source as:'));
console.log(colors.muted(' GitHub: owner/repo or https://github.com/owner/repo'));
console.log(colors.muted(' GitLab: gitlab:owner/repo or https://gitlab.com/owner/repo'));
console.log(colors.muted(' Bitbucket: bitbucket:owner/repo'));
console.log(colors.muted(' Local: ./path or ~/path'));
return 1;
}
s.start(`Fetching from ${providerAdapter.name}...`);
const result = await providerAdapter.clone(this.source, '', { depth: 1 });
if (!result.success || !result.path) {
s.stop(colors.error(result.error || 'Failed to fetch source'));
return 1;
}
s.stop(`Found ${result.skills?.length || 0} skill(s)`);
const discoveredSkills = result.discoveredSkills || [];
// List mode - just show skills and exit
if (this.list) {
if (discoveredSkills.length === 0) {
warn('No skills found in this repository');
} else {
console.log('');
console.log(colors.bold('Available skills:'));
console.log('');
for (const skill of discoveredSkills) {
const quality = evaluateSkillDirectory(skill.path);
const qualityBadge = quality ? ` ${formatQualityBadge(quality.overall)}` : '';
console.log(` ${colors.success(symbols.stepActive)} ${colors.primary(skill.name)}${qualityBadge}`);
}
console.log('');
console.log(colors.muted(`Total: ${discoveredSkills.length} skill(s)`));
console.log(colors.muted('To install: skillkit install <source> --skill=name'));
}
const cleanupPath = result.tempRoot || result.path;
if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) {
rmSync(cleanupPath, { recursive: true, force: true });
}
return 0;
}
let skillsToInstall = discoveredSkills;
// Non-interactive: use --skills filter
if (this.skills) {
const requestedSkills = this.skills.split(',').map(s => s.trim());
const available = discoveredSkills.map(s => s.name);
const notFound = requestedSkills.filter(s => !available.includes(s));
if (notFound.length > 0) {
error(`Skills not found: ${notFound.join(', ')}`);
console.log(colors.muted(`Available: ${available.join(', ')}`));
return 1;
}
skillsToInstall = discoveredSkills.filter(s => requestedSkills.includes(s.name));
} else if (this.all || this.yes) {
skillsToInstall = discoveredSkills;
} else if (isInteractive && discoveredSkills.length > 1) {
// Interactive skill selection
step(`Source: ${colors.cyan(this.source)}`);
const skillResult = await skillMultiselect({
message: 'Select skills to install',
skills: discoveredSkills.map(s => ({ name: s.name })),
initialValues: discoveredSkills.map(s => s.name),
});
if (isCancel(skillResult)) {
cancel('Installation cancelled');
return 0;
}
skillsToInstall = discoveredSkills.filter(s => (skillResult as string[]).includes(s.name));
}
if (skillsToInstall.length === 0) {
warn('No skills to install');
return 0;
}
// Determine target agents
let targetAgents: AgentType[];
if (this.agent && this.agent.length > 0) {
// Explicitly specified agents
targetAgents = this.agent as AgentType[];
} else if (isInteractive) {
const allAgentTypes = getAllAdapters().map(a => a.type);
const lastAgents = getLastAgents();
step(`Detected ${allAgentTypes.length} agents`);
const agentResult = await quickAgentSelect({
message: 'Install to',
agents: allAgentTypes,
lastSelected: lastAgents,
});
if (isCancel(agentResult)) {
cancel('Installation cancelled');
return 0;
}
targetAgents = (agentResult as { agents: string[] }).agents as AgentType[];
// Save selection for next time
saveLastAgents(targetAgents);
} else {
// Non-interactive: use detected agent
const detectedAgent = await detectAgent();
targetAgents = [detectedAgent];
}
// Interactive: select installation method
let installMethod: 'symlink' | 'copy' = 'copy';
if (isInteractive && targetAgents.length > 1) {
const methodResult = await selectInstallMethod({});
if (isCancel(methodResult)) {
cancel('Installation cancelled');
return 0;
}
installMethod = methodResult as 'symlink' | 'copy';
}
// Check for low-quality skills and warn
const lowQualitySkills: Array<{ name: string; score: number; warnings: string[] }> = [];
for (const skill of skillsToInstall) {
const quality = evaluateSkillDirectory(skill.path);
if (quality && quality.overall < 60) {
lowQualitySkills.push({
name: skill.name,
score: quality.overall,
warnings: quality.warnings.slice(0, 2),
});
}
}
if (this.scan) {
const scanner = new SkillScanner({ failOnSeverity: Severity.HIGH });
for (const skill of skillsToInstall) {
const scanResult = await scanner.scan(skill.path);
if (scanResult.verdict === 'fail' && !this.force) {
error(`Security scan FAILED for "${skill.name}"`);
console.log(formatSummary(scanResult));
console.log(colors.muted('Use --force to install anyway, or --no-scan to skip scanning'));
const cleanupPath = result.tempRoot || result.path;
if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) {
rmSync(cleanupPath, { recursive: true, force: true });
}
return 1;
}
if (scanResult.verdict === 'warn' && !this.quiet) {
warn(`Security warnings for "${skill.name}" (${scanResult.stats.medium} medium, ${scanResult.stats.low} low)`);
}
}
}
// Confirm installation
if (isInteractive && !this.yes) {
console.log('');
// Show low-quality warning if any
if (lowQualitySkills.length > 0) {
console.log(colors.warning(`${symbols.warning} Warning: ${lowQualitySkills.length} skill(s) have low quality scores (< 60)`));
for (const lq of lowQualitySkills) {
const grade = getQualityGradeFromScore(lq.score);
const warningText = lq.warnings.length > 0 ? ` - ${lq.warnings.join(', ')}` : '';
console.log(colors.muted(` - ${lq.name} [${grade}]${warningText}`));
}
console.log('');
}
const agentDisplay = targetAgents.length <= 3
? targetAgents.map(formatAgent).join(', ')
: `${targetAgents.slice(0, 2).map(formatAgent).join(', ')} +${targetAgents.length - 2} more`;
const confirmResult = await confirm({
message: `Install ${skillsToInstall.length} skill(s) to ${agentDisplay}?`,
initialValue: true,
});
if (isCancel(confirmResult) || !confirmResult) {
cancel('Installation cancelled');
return 0;
}
}
// Perform installation
let totalInstalled = 0;
const installResults: InstallResult[] = [];
for (const skill of skillsToInstall) {
const skillName = skill.name;
const sourcePath = skill.path;
const installedAgents: string[] = [];
let primaryPath: string | null = null;
for (const agentType of targetAgents) {
const adapter = getAdapter(agentType);
const installDir = getInstallDir(this.global, agentType);
if (!existsSync(installDir)) {
mkdirSync(installDir, { recursive: true });
}
const targetPath = join(installDir, skillName);
if (existsSync(targetPath) && !this.force) {
if (!this.quiet) {
warn(`Skipping ${skillName} for ${adapter.name} (already exists, use --force)`);
}
continue;
}
const securityRoot = result.tempRoot || result.path;
if (!isPathInside(sourcePath, securityRoot)) {
error(`Skipping ${skillName} (path traversal detected)`);
continue;
}
const isSymlinkMode = installMethod === 'symlink' && targetAgents.length > 1;
const useSymlink = isSymlinkMode && primaryPath !== null;
s.start(`Installing ${skillName} to ${adapter.name}${useSymlink ? ' (symlink)' : ''}...`);
try {
if (existsSync(targetPath)) {
rmSync(targetPath, { recursive: true, force: true });
}
if (useSymlink && primaryPath) {
symlinkSync(primaryPath, targetPath, 'dir');
} else {
cpSync(sourcePath, targetPath, { recursive: true, dereference: true });
if (isSymlinkMode && primaryPath === null) {
primaryPath = targetPath;
}
// Auto-install npm dependencies if package.json exists
const packageJsonPath = join(targetPath, 'package.json');
if (existsSync(packageJsonPath)) {
s.stop(`Installed ${skillName} to ${adapter.name}`);
s.start(`Installing npm dependencies for ${skillName}...`);
try {
await execFileAsync('npm', ['install', '--production'], { cwd: targetPath });
s.stop(`Installed dependencies for ${skillName}`);
} catch (npmErr) {
s.stop(colors.warning(`Dependencies failed for ${skillName}`));
console.log(colors.muted('Run manually: npm install in ' + targetPath));
}
s.start(`Finishing ${skillName} installation...`);
}
}
const metadata: SkillMetadata = {
name: skillName,
description: '',
source: this.source,
sourceType: providerAdapter.type,
subpath: skillName,
installedAt: new Date().toISOString(),
enabled: true,
};
saveSkillMetadata(targetPath, metadata);
installedAgents.push(agentType);
s.stop(`Installed ${skillName} to ${adapter.name}${useSymlink ? ' (symlink)' : ''}`);
} catch (err) {
s.stop(colors.error(`Failed to install ${skillName} to ${adapter.name}`));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
}
}
if (installedAgents.length > 0) {
totalInstalled++;
installResults.push({
skillName,
method: installMethod,
agents: installedAgents,
path: join(getInstallDir(this.global, installedAgents[0] as AgentType), skillName),
});
}
}
// Cleanup temp directory
const cleanupPath = result.tempRoot || result.path;
if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) {
rmSync(cleanupPath, { recursive: true, force: true });
}
// Show summary
if (totalInstalled > 0) {
if (isInteractive) {
showInstallSummary({
totalSkills: totalInstalled,
totalAgents: targetAgents.length,
results: installResults,
source: this.source,
});
outro('Installation complete!');
if (!this.yes) {
showNextSteps({
skillNames: installResults.map(r => r.skillName),
agentTypes: targetAgents,
syncNeeded: true,
});
}
} else {
success(`Installed ${totalInstalled} skill(s) to ${targetAgents.length} agent(s)`);
for (const r of installResults) {
console.log(colors.muted(` ${symbols.success} ${r.skillName} ${symbols.arrowRight} ${r.agents.map(getAgentIcon).join(' ')}`));
}
console.log('');
console.log(colors.muted('Run `skillkit sync` to update agent configs'));
}
} else {
warn('No skills were installed');
}
return 0;
} catch (err) {
s.stop(colors.error('Installation failed'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
}