@skillsmith/cli 0.2.7 → 0.3.1

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 (67) hide show
  1. package/README.md +104 -1
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/src/commands/author/index.d.ts +16 -0
  4. package/dist/src/commands/author/index.d.ts.map +1 -0
  5. package/dist/src/commands/author/index.js +18 -0
  6. package/dist/src/commands/author/index.js.map +1 -0
  7. package/dist/src/commands/author/init.d.ts +47 -0
  8. package/dist/src/commands/author/init.d.ts.map +1 -0
  9. package/dist/src/commands/author/init.js +346 -0
  10. package/dist/src/commands/author/init.js.map +1 -0
  11. package/dist/src/commands/author/mcp-init.d.ts +20 -0
  12. package/dist/src/commands/author/mcp-init.d.ts.map +1 -0
  13. package/dist/src/commands/author/mcp-init.js +183 -0
  14. package/dist/src/commands/author/mcp-init.js.map +1 -0
  15. package/dist/src/commands/author/subagent.d.ts +22 -0
  16. package/dist/src/commands/author/subagent.d.ts.map +1 -0
  17. package/dist/src/commands/author/subagent.js +166 -0
  18. package/dist/src/commands/author/subagent.js.map +1 -0
  19. package/dist/src/commands/author/transform.d.ts +22 -0
  20. package/dist/src/commands/author/transform.d.ts.map +1 -0
  21. package/dist/src/commands/author/transform.js +141 -0
  22. package/dist/src/commands/author/transform.js.map +1 -0
  23. package/dist/src/commands/author/utils.d.ts +27 -0
  24. package/dist/src/commands/author/utils.d.ts.map +1 -0
  25. package/dist/src/commands/author/utils.js +118 -0
  26. package/dist/src/commands/author/utils.js.map +1 -0
  27. package/dist/src/commands/index.d.ts +2 -1
  28. package/dist/src/commands/index.d.ts.map +1 -1
  29. package/dist/src/commands/index.js +6 -1
  30. package/dist/src/commands/index.js.map +1 -1
  31. package/dist/src/commands/sync.d.ts +21 -0
  32. package/dist/src/commands/sync.d.ts.map +1 -0
  33. package/dist/src/commands/sync.js +373 -0
  34. package/dist/src/commands/sync.js.map +1 -0
  35. package/dist/src/import.d.ts +1 -0
  36. package/dist/src/import.d.ts.map +1 -1
  37. package/dist/src/import.js +20 -5
  38. package/dist/src/import.js.map +1 -1
  39. package/dist/src/index.d.ts +3 -0
  40. package/dist/src/index.d.ts.map +1 -1
  41. package/dist/src/index.js +9 -2
  42. package/dist/src/index.js.map +1 -1
  43. package/dist/src/utils/formatters.d.ts +39 -0
  44. package/dist/src/utils/formatters.d.ts.map +1 -0
  45. package/dist/src/utils/formatters.js +69 -0
  46. package/dist/src/utils/formatters.js.map +1 -0
  47. package/dist/tests/author.test.js +117 -32
  48. package/dist/tests/author.test.js.map +1 -1
  49. package/dist/tests/e2e/author.e2e.test.js +341 -21
  50. package/dist/tests/e2e/author.e2e.test.js.map +1 -1
  51. package/dist/tests/e2e/utils/index.d.ts +4 -0
  52. package/dist/tests/e2e/utils/index.d.ts.map +1 -1
  53. package/dist/tests/e2e/utils/index.js +4 -0
  54. package/dist/tests/e2e/utils/index.js.map +1 -1
  55. package/dist/tests/e2e/utils/mock-github.d.ts +23 -0
  56. package/dist/tests/e2e/utils/mock-github.d.ts.map +1 -0
  57. package/dist/tests/e2e/utils/mock-github.js +60 -0
  58. package/dist/tests/e2e/utils/mock-github.js.map +1 -0
  59. package/dist/tests/e2e/utils/mock-prompts.d.ts +19 -0
  60. package/dist/tests/e2e/utils/mock-prompts.d.ts.map +1 -0
  61. package/dist/tests/e2e/utils/mock-prompts.js +48 -0
  62. package/dist/tests/e2e/utils/mock-prompts.js.map +1 -0
  63. package/package.json +1 -1
  64. package/dist/src/commands/author.d.ts +0 -76
  65. package/dist/src/commands/author.d.ts.map +0 -1
  66. package/dist/src/commands/author.js +0 -857
  67. package/dist/src/commands/author.js.map +0 -1
@@ -1,857 +0,0 @@
1
- /**
2
- * SMI-746: Skill Authoring Commands
3
- *
4
- * Provides CLI commands for creating, validating, and publishing skills.
5
- */
6
- import { Command } from 'commander';
7
- import { input, confirm, select } from '@inquirer/prompts';
8
- import chalk from 'chalk';
9
- import ora from 'ora';
10
- import { mkdir, writeFile, readFile, stat } from 'fs/promises';
11
- import { dirname, join, resolve } from 'path';
12
- import { createHash } from 'crypto';
13
- import { SkillParser } from '@skillsmith/core';
14
- import { SKILL_MD_TEMPLATE, README_MD_TEMPLATE, renderSubagentTemplate, renderClaudeMdSnippet, renderMcpServerTemplates, } from '../templates/index.js';
15
- import { sanitizeError } from '../utils/sanitize.js';
16
- import { analyzeToolRequirements, formatToolList, parseToolsString, validateTools, } from '../utils/tool-analyzer.js';
17
- import { homedir } from 'os';
18
- import { access } from 'fs/promises';
19
- /**
20
- * Initialize a new skill directory
21
- */
22
- async function initSkill(name, targetPath) {
23
- // Interactive prompts if name not provided
24
- const skillName = name ||
25
- (await input({
26
- message: 'Skill name:',
27
- validate: (value) => {
28
- if (!value.trim())
29
- return 'Name is required';
30
- if (!/^[a-zA-Z][a-zA-Z0-9-_]*$/.test(value)) {
31
- return 'Name must start with a letter and contain only letters, numbers, hyphens, and underscores';
32
- }
33
- return true;
34
- },
35
- }));
36
- const description = await input({
37
- message: 'Description:',
38
- default: `A Claude skill for ${skillName}`,
39
- });
40
- const author = await input({
41
- message: 'Author:',
42
- default: process.env['USER'] || 'author',
43
- });
44
- const category = await select({
45
- message: 'Category:',
46
- choices: [
47
- { name: 'Development', value: 'development' },
48
- { name: 'Productivity', value: 'productivity' },
49
- { name: 'Communication', value: 'communication' },
50
- { name: 'Data', value: 'data' },
51
- { name: 'Security', value: 'security' },
52
- { name: 'Other', value: 'other' },
53
- ],
54
- });
55
- const skillDir = resolve(targetPath, skillName);
56
- // Check if directory already exists
57
- try {
58
- await stat(skillDir);
59
- const overwrite = await confirm({
60
- message: `Directory ${skillDir} already exists. Overwrite?`,
61
- default: false,
62
- });
63
- if (!overwrite) {
64
- console.log(chalk.yellow('Initialization cancelled'));
65
- return;
66
- }
67
- }
68
- catch {
69
- // Directory doesn't exist, continue
70
- }
71
- const spinner = ora('Creating skill structure...').start();
72
- try {
73
- // Create directory structure
74
- await mkdir(skillDir, { recursive: true });
75
- await mkdir(join(skillDir, 'scripts'), { recursive: true });
76
- await mkdir(join(skillDir, 'resources'), { recursive: true });
77
- // Generate SKILL.md from template
78
- const skillMdContent = SKILL_MD_TEMPLATE.replace(/\{\{name\}\}/g, skillName)
79
- .replace(/\{\{description\}\}/g, description)
80
- .replace(/\{\{author\}\}/g, author)
81
- .replace(/\{\{category\}\}/g, category)
82
- .replace(/\{\{date\}\}/g, new Date().toISOString().split('T')[0] || '');
83
- await writeFile(join(skillDir, 'SKILL.md'), skillMdContent, 'utf-8');
84
- // Generate README.md from template
85
- const readmeContent = README_MD_TEMPLATE.replace(/\{\{name\}\}/g, skillName).replace(/\{\{description\}\}/g, description);
86
- await writeFile(join(skillDir, 'README.md'), readmeContent, 'utf-8');
87
- // Create placeholder script
88
- const placeholderScript = `#!/usr/bin/env node
89
- /**
90
- * ${skillName} - Example Script
91
- *
92
- * Add your skill's automation scripts here.
93
- */
94
-
95
- console.log('${skillName} script executed');
96
- `;
97
- await writeFile(join(skillDir, 'scripts', 'example.js'), placeholderScript, 'utf-8');
98
- // Create .gitignore
99
- const gitignore = `# Dependencies
100
- node_modules/
101
-
102
- # Build output
103
- dist/
104
-
105
- # Environment
106
- .env
107
- .env.local
108
-
109
- # OS files
110
- .DS_Store
111
- Thumbs.db
112
- `;
113
- await writeFile(join(skillDir, '.gitignore'), gitignore, 'utf-8');
114
- spinner.succeed(`Created skill at ${skillDir}`);
115
- console.log(chalk.bold('\nNext steps:'));
116
- console.log(chalk.dim(` 1. cd ${skillDir}`));
117
- console.log(chalk.dim(' 2. Edit SKILL.md to customize your skill'));
118
- console.log(chalk.dim(' 3. Add scripts to the scripts/ directory'));
119
- console.log(chalk.dim(' 4. Run skillsmith validate to check your skill'));
120
- console.log(chalk.dim(' 5. Run skillsmith publish to prepare for sharing'));
121
- console.log();
122
- }
123
- catch (error) {
124
- spinner.fail(`Failed to create skill: ${sanitizeError(error)}`);
125
- throw error;
126
- }
127
- }
128
- /**
129
- * Pretty print validation errors and warnings
130
- */
131
- function printValidationResult(result, filePath) {
132
- console.log(chalk.bold(`\nValidation Result for ${filePath}:\n`));
133
- if (result.valid) {
134
- console.log(chalk.green.bold(' VALID'));
135
- }
136
- else {
137
- console.log(chalk.red.bold(' INVALID'));
138
- }
139
- if (result.errors.length > 0) {
140
- console.log(chalk.red.bold('\nErrors:'));
141
- for (const error of result.errors) {
142
- console.log(chalk.red(` - ${error}`));
143
- }
144
- }
145
- if (result.warnings.length > 0) {
146
- console.log(chalk.yellow.bold('\nWarnings:'));
147
- for (const warning of result.warnings) {
148
- console.log(chalk.yellow(` - ${warning}`));
149
- }
150
- }
151
- console.log();
152
- }
153
- /**
154
- * Validate a local SKILL.md file
155
- */
156
- async function validateSkill(skillPath) {
157
- const spinner = ora('Validating skill...').start();
158
- try {
159
- // Resolve path
160
- let filePath = resolve(skillPath);
161
- // Check if it's a directory, look for SKILL.md
162
- try {
163
- const stats = await stat(filePath);
164
- if (stats.isDirectory()) {
165
- filePath = join(filePath, 'SKILL.md');
166
- }
167
- }
168
- catch {
169
- // If path doesn't exist, try adding SKILL.md
170
- if (!filePath.endsWith('.md')) {
171
- filePath = join(filePath, 'SKILL.md');
172
- }
173
- }
174
- // Read file
175
- const content = await readFile(filePath, 'utf-8');
176
- // Parse and validate
177
- const parser = new SkillParser({ requireName: true });
178
- const { validation, metadata, frontmatter } = parser.parseWithValidation(content);
179
- spinner.stop();
180
- printValidationResult(validation, filePath);
181
- if (metadata) {
182
- console.log(chalk.bold('Parsed Metadata:'));
183
- console.log(chalk.dim(` Name: ${metadata.name}`));
184
- console.log(chalk.dim(` Description: ${metadata.description || 'N/A'}`));
185
- console.log(chalk.dim(` Author: ${metadata.author || 'N/A'}`));
186
- console.log(chalk.dim(` Version: ${metadata.version || 'N/A'}`));
187
- console.log(chalk.dim(` Tags: ${metadata.tags.join(', ') || 'None'}`));
188
- console.log(chalk.dim(` Trust Tier: ${parser.inferTrustTier(metadata)}`));
189
- console.log();
190
- }
191
- if (frontmatter) {
192
- console.log(chalk.bold('Frontmatter Fields:'));
193
- for (const [key, value] of Object.entries(frontmatter)) {
194
- if (value !== undefined && value !== null) {
195
- const displayValue = Array.isArray(value) ? value.join(', ') : String(value);
196
- console.log(chalk.dim(` ${key}: ${displayValue}`));
197
- }
198
- }
199
- console.log();
200
- }
201
- return validation.valid;
202
- }
203
- catch (error) {
204
- spinner.fail(`Validation failed: ${sanitizeError(error)}`);
205
- return false;
206
- }
207
- }
208
- /**
209
- * Prepare skill for publishing
210
- * @returns true if publishing succeeded, false if validation failed
211
- */
212
- async function publishSkill(skillPath) {
213
- const spinner = ora('Preparing skill for publishing...').start();
214
- try {
215
- // Resolve path
216
- let dirPath = resolve(skillPath || '.');
217
- // Check if it's a file, get directory
218
- try {
219
- const stats = await stat(dirPath);
220
- if (!stats.isDirectory()) {
221
- dirPath = dirname(dirPath);
222
- }
223
- }
224
- catch {
225
- // Path doesn't exist
226
- spinner.fail(`Directory not found: ${dirPath}`);
227
- return false;
228
- }
229
- const skillMdPath = join(dirPath, 'SKILL.md');
230
- // Validate first
231
- spinner.text = 'Validating skill...';
232
- const content = await readFile(skillMdPath, 'utf-8');
233
- const parser = new SkillParser({ requireName: true });
234
- const { validation, metadata } = parser.parseWithValidation(content);
235
- if (!validation.valid) {
236
- spinner.fail('Skill validation failed');
237
- printValidationResult(validation, skillMdPath);
238
- return false;
239
- }
240
- if (!metadata) {
241
- spinner.fail('Could not parse skill metadata');
242
- return false;
243
- }
244
- // Generate checksum
245
- spinner.text = 'Generating checksum...';
246
- const checksum = createHash('sha256').update(content).digest('hex');
247
- // Create publish info
248
- const publishInfo = {
249
- name: metadata.name,
250
- version: metadata.version || '1.0.0',
251
- checksum,
252
- publishedAt: new Date().toISOString(),
253
- trustTier: parser.inferTrustTier(metadata),
254
- };
255
- // Write publish manifest
256
- const manifestPath = join(dirPath, '.skillsmith-publish.json');
257
- await writeFile(manifestPath, JSON.stringify(publishInfo, null, 2), 'utf-8');
258
- spinner.succeed('Skill prepared for publishing');
259
- console.log(chalk.bold('\nPublish Information:'));
260
- console.log(chalk.dim(` Name: ${publishInfo.name}`));
261
- console.log(chalk.dim(` Version: ${publishInfo.version}`));
262
- console.log(chalk.dim(` Checksum: ${publishInfo.checksum.slice(0, 16)}...`));
263
- console.log(chalk.dim(` Trust Tier: ${publishInfo.trustTier}`));
264
- console.log();
265
- console.log(chalk.bold('To share this skill:'));
266
- console.log(chalk.cyan('\n Option 1: GitHub'));
267
- console.log(chalk.dim(' 1. Push to a GitHub repository'));
268
- console.log(chalk.dim(' 2. Add topic "claude-skill" to the repository'));
269
- console.log(chalk.dim(' 3. The skill will be automatically discovered'));
270
- console.log(chalk.cyan('\n Option 2: Manual Installation'));
271
- console.log(chalk.dim(` 1. Share the ${dirPath} directory`));
272
- console.log(chalk.dim(' 2. Users can copy to ~/.claude/skills/'));
273
- console.log(chalk.cyan('\n Option 3: Archive'));
274
- console.log(chalk.dim(` 1. Create archive: tar -czf ${metadata.name}.tar.gz ${dirPath}`));
275
- console.log(chalk.dim(' 2. Share the archive'));
276
- console.log();
277
- return true;
278
- }
279
- catch (error) {
280
- spinner.fail(`Publishing failed: ${sanitizeError(error)}`);
281
- return false;
282
- }
283
- }
284
- /**
285
- * Create init command
286
- */
287
- export function createInitCommand() {
288
- return new Command('init')
289
- .description('Initialize a new skill directory')
290
- .argument('[name]', 'Skill name')
291
- .option('-p, --path <path>', 'Target directory', '.')
292
- .action(async (name, opts) => {
293
- const targetPath = opts['path'] || '.';
294
- try {
295
- await initSkill(name, targetPath);
296
- }
297
- catch (error) {
298
- console.error(chalk.red('Error initializing skill:'), sanitizeError(error));
299
- process.exit(1);
300
- }
301
- });
302
- }
303
- /**
304
- * Create validate command
305
- */
306
- export function createValidateCommand() {
307
- return new Command('validate')
308
- .description('Validate a local SKILL.md file')
309
- .argument('[path]', 'Path to SKILL.md or skill directory', '.')
310
- .action(async (skillPath) => {
311
- try {
312
- const valid = await validateSkill(skillPath);
313
- process.exit(valid ? 0 : 1);
314
- }
315
- catch (error) {
316
- console.error(chalk.red('Error validating skill:'), sanitizeError(error));
317
- process.exit(1);
318
- }
319
- });
320
- }
321
- /**
322
- * Create publish command
323
- */
324
- export function createPublishCommand() {
325
- return new Command('publish')
326
- .description('Prepare skill for sharing')
327
- .argument('[path]', 'Path to skill directory', '.')
328
- .action(async (skillPath) => {
329
- try {
330
- const success = await publishSkill(skillPath);
331
- process.exit(success ? 0 : 1);
332
- }
333
- catch (error) {
334
- console.error(chalk.red('Error publishing skill:'), sanitizeError(error));
335
- process.exit(1);
336
- }
337
- });
338
- }
339
- /**
340
- * SMI-1389: Extract trigger phrases from skill description
341
- */
342
- function extractTriggerPhrases(description) {
343
- const phrases = [];
344
- // Pattern: "Use when [phrases]" or "when the user asks to [phrases]"
345
- const patterns = [
346
- /use when (?:the user asks to )?["']([^"']+)["']/gi,
347
- /when (?:the user asks to )?["']([^"']+)["']/gi,
348
- /trigger(?:ed)? (?:by|when|phrases?)[\s:]+["']([^"']+)["']/gi,
349
- /invoke when (?:the user )?["']([^"']+)["']/gi,
350
- ];
351
- for (const pattern of patterns) {
352
- const matches = description.matchAll(pattern);
353
- for (const match of matches) {
354
- if (match[1]) {
355
- phrases.push(match[1]);
356
- }
357
- }
358
- }
359
- return phrases;
360
- }
361
- /**
362
- * SMI-1389: Validate subagent definition structure
363
- */
364
- function validateSubagentDefinition(content) {
365
- const errors = [];
366
- const warnings = [];
367
- // Check for YAML frontmatter
368
- if (!content.trim().startsWith('---')) {
369
- errors.push('Missing YAML frontmatter');
370
- }
371
- // Extract and validate frontmatter
372
- const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
373
- if (frontmatterMatch) {
374
- const frontmatter = frontmatterMatch[1] || '';
375
- const requiredFields = ['name', 'description', 'skills', 'tools', 'model'];
376
- for (const field of requiredFields) {
377
- if (!frontmatter.includes(`${field}:`)) {
378
- errors.push(`Missing required field: ${field}`);
379
- }
380
- }
381
- }
382
- else {
383
- errors.push('Could not parse YAML frontmatter');
384
- }
385
- // Check for operating protocol section
386
- if (!content.includes('## Operating Protocol')) {
387
- warnings.push('Missing Operating Protocol section');
388
- }
389
- // Check for output format section
390
- if (!content.includes('## Output Format')) {
391
- warnings.push('Missing Output Format section');
392
- }
393
- return {
394
- valid: errors.length === 0,
395
- errors,
396
- warnings,
397
- };
398
- }
399
- /**
400
- * Ensure ~/.claude/agents directory exists
401
- */
402
- async function ensureAgentsDirectory(customPath) {
403
- const agentsDir = customPath
404
- ? resolve(customPath.replace(/^~/, homedir()))
405
- : join(homedir(), '.claude', 'agents');
406
- await mkdir(agentsDir, { recursive: true });
407
- return agentsDir;
408
- }
409
- /**
410
- * Check if file exists
411
- */
412
- async function fileExists(path) {
413
- try {
414
- await access(path);
415
- return true;
416
- }
417
- catch {
418
- return false;
419
- }
420
- }
421
- /**
422
- * SMI-1389: Generate a companion subagent for a skill
423
- */
424
- async function generateSubagent(skillPath, options) {
425
- const spinner = ora('Generating subagent...').start();
426
- try {
427
- // Resolve skill path
428
- let dirPath = resolve(skillPath || '.');
429
- let skillMdPath;
430
- // Check if it's a directory or file
431
- try {
432
- const stats = await stat(dirPath);
433
- if (stats.isDirectory()) {
434
- skillMdPath = join(dirPath, 'SKILL.md');
435
- }
436
- else {
437
- skillMdPath = dirPath;
438
- dirPath = dirname(dirPath);
439
- }
440
- }
441
- catch {
442
- // Try adding SKILL.md
443
- skillMdPath = dirPath.endsWith('.md') ? dirPath : join(dirPath, 'SKILL.md');
444
- }
445
- // Read and parse SKILL.md
446
- spinner.text = 'Reading SKILL.md...';
447
- const content = await readFile(skillMdPath, 'utf-8');
448
- const parser = new SkillParser({ requireName: true });
449
- const { validation, metadata } = parser.parseWithValidation(content);
450
- if (!validation.valid || !metadata) {
451
- spinner.fail('SKILL.md validation failed');
452
- printValidationResult(validation, skillMdPath);
453
- return;
454
- }
455
- // Analyze tool requirements
456
- spinner.text = 'Analyzing tool requirements...';
457
- const toolAnalysis = analyzeToolRequirements(content);
458
- // Override tools if specified
459
- let tools = toolAnalysis.requiredTools;
460
- if (options.tools) {
461
- const customTools = parseToolsString(options.tools);
462
- const validation = validateTools(customTools);
463
- if (!validation.valid) {
464
- spinner.fail(`Unrecognized tools: ${validation.unrecognized.join(', ')}`);
465
- return;
466
- }
467
- tools = customTools;
468
- }
469
- // Extract trigger phrases
470
- const triggerPhrases = extractTriggerPhrases(metadata.description || '');
471
- // Determine model
472
- const model = options.model || 'sonnet';
473
- if (!['sonnet', 'opus', 'haiku'].includes(model)) {
474
- spinner.fail(`Invalid model: ${model}. Must be sonnet, opus, or haiku.`);
475
- return;
476
- }
477
- // Generate subagent content
478
- spinner.text = 'Generating subagent definition...';
479
- const subagentContent = renderSubagentTemplate({
480
- skillName: metadata.name,
481
- description: metadata.description || `Specialist for ${metadata.name}`,
482
- triggerPhrases,
483
- tools,
484
- model,
485
- });
486
- // Validate generated content
487
- const subagentValidation = validateSubagentDefinition(subagentContent);
488
- if (!subagentValidation.valid) {
489
- spinner.fail('Generated subagent is invalid');
490
- console.log(chalk.red('\nGeneration errors:'));
491
- for (const error of subagentValidation.errors) {
492
- console.log(chalk.red(` - ${error}`));
493
- }
494
- return;
495
- }
496
- // Ensure agents directory exists
497
- const agentsDir = await ensureAgentsDirectory(options.output);
498
- const subagentPath = join(agentsDir, `${metadata.name}-specialist.md`);
499
- // Check if subagent already exists
500
- if (await fileExists(subagentPath)) {
501
- if (!options.force) {
502
- spinner.warn(`Subagent already exists: ${subagentPath}`);
503
- console.log(chalk.yellow(' Use --force to overwrite'));
504
- return;
505
- }
506
- }
507
- // Write subagent file
508
- await writeFile(subagentPath, subagentContent, 'utf-8');
509
- spinner.succeed(`Generated subagent: ${subagentPath}`);
510
- // Show tool analysis
511
- console.log(chalk.bold('\nTool Analysis:'));
512
- console.log(chalk.dim(` Confidence: ${toolAnalysis.confidence}`));
513
- console.log(chalk.dim(` Tools: ${formatToolList(tools)}`));
514
- if (toolAnalysis.detectedPatterns.length > 0) {
515
- console.log(chalk.dim(' Detected patterns:'));
516
- for (const pattern of toolAnalysis.detectedPatterns.slice(0, 5)) {
517
- console.log(chalk.dim(` - ${pattern}`));
518
- }
519
- }
520
- // Generate and display CLAUDE.md snippet
521
- if (!options.skipClaudeMd) {
522
- const snippet = renderClaudeMdSnippet({
523
- skillName: metadata.name,
524
- description: metadata.description || '',
525
- triggerPhrases,
526
- tools,
527
- model,
528
- });
529
- console.log(chalk.bold('\nCLAUDE.md Integration Snippet:'));
530
- console.log(chalk.cyan('─'.repeat(50)));
531
- console.log(snippet);
532
- console.log(chalk.cyan('─'.repeat(50)));
533
- console.log(chalk.dim('\nAdd this snippet to your project CLAUDE.md to enable delegation.'));
534
- }
535
- console.log();
536
- }
537
- catch (error) {
538
- spinner.fail(`Failed to generate subagent: ${sanitizeError(error)}`);
539
- throw error;
540
- }
541
- }
542
- /**
543
- * SMI-1390: Transform existing skill by generating subagent (non-destructive)
544
- */
545
- async function transformSkill(skillPath, options) {
546
- const spinner = ora('Transforming skill...').start();
547
- try {
548
- const dirPath = resolve(skillPath || '.');
549
- // Check if batch mode
550
- if (options.batch) {
551
- spinner.text = 'Scanning for skills...';
552
- const entries = await readFile(dirPath, 'utf-8').catch(() => null);
553
- if (entries === null) {
554
- // It's a directory, scan for subdirectories with SKILL.md
555
- const { readdir } = await import('fs/promises');
556
- const subdirs = await readdir(dirPath, { withFileTypes: true });
557
- const skillDirs = [];
558
- for (const entry of subdirs) {
559
- if (entry.isDirectory()) {
560
- const skillMdPath = join(dirPath, entry.name, 'SKILL.md');
561
- if (await fileExists(skillMdPath)) {
562
- skillDirs.push(join(dirPath, entry.name));
563
- }
564
- }
565
- }
566
- if (skillDirs.length === 0) {
567
- spinner.warn('No skills found in directory');
568
- return;
569
- }
570
- spinner.succeed(`Found ${skillDirs.length} skills`);
571
- // Process each skill
572
- for (const skillDir of skillDirs) {
573
- console.log(chalk.dim(`\nProcessing: ${skillDir}`));
574
- await transformSkill(skillDir, {
575
- ...options,
576
- batch: false, // Don't recurse
577
- });
578
- }
579
- return;
580
- }
581
- }
582
- // Single skill transform
583
- const skillMdPath = join(dirPath, 'SKILL.md');
584
- if (!(await fileExists(skillMdPath))) {
585
- spinner.fail(`No SKILL.md found at: ${skillMdPath}`);
586
- return;
587
- }
588
- // Read and parse
589
- spinner.text = 'Reading SKILL.md...';
590
- const content = await readFile(skillMdPath, 'utf-8');
591
- const parser = new SkillParser({ requireName: true });
592
- const { validation, metadata } = parser.parseWithValidation(content);
593
- if (!validation.valid || !metadata) {
594
- spinner.fail('SKILL.md validation failed');
595
- printValidationResult(validation, skillMdPath);
596
- return;
597
- }
598
- // Check if subagent already exists
599
- const agentsDir = join(homedir(), '.claude', 'agents');
600
- const subagentPath = join(agentsDir, `${metadata.name}-specialist.md`);
601
- if (await fileExists(subagentPath)) {
602
- if (!options.force) {
603
- spinner.warn(`Subagent already exists: ${subagentPath}`);
604
- console.log(chalk.yellow(' Use --force to overwrite'));
605
- return;
606
- }
607
- }
608
- if (options.dryRun) {
609
- spinner.succeed('Dry run - would generate:');
610
- console.log(chalk.dim(` Subagent: ${subagentPath}`));
611
- // Show tool analysis
612
- const toolAnalysis = analyzeToolRequirements(content);
613
- console.log(chalk.dim(` Tools: ${formatToolList(toolAnalysis.requiredTools)}`));
614
- console.log(chalk.dim(` Confidence: ${toolAnalysis.confidence}`));
615
- return;
616
- }
617
- spinner.stop();
618
- // Generate subagent using existing function
619
- await generateSubagent(dirPath, {
620
- force: options.force,
621
- tools: options.tools,
622
- model: options.model,
623
- skipClaudeMd: false,
624
- });
625
- }
626
- catch (error) {
627
- spinner.fail(`Failed to transform skill: ${sanitizeError(error)}`);
628
- throw error;
629
- }
630
- }
631
- /**
632
- * Create subagent command
633
- */
634
- export function createSubagentCommand() {
635
- return new Command('subagent')
636
- .description('Generate a companion subagent for a skill')
637
- .argument('[path]', 'Path to skill directory', '.')
638
- .option('-o, --output <path>', 'Output directory', '~/.claude/agents')
639
- .option('--tools <tools>', 'Override detected tools (comma-separated)')
640
- .option('--model <model>', 'Model for subagent: sonnet|opus|haiku', 'sonnet')
641
- .option('--skip-claude-md', 'Skip CLAUDE.md snippet generation')
642
- .option('--force', 'Overwrite existing subagent definition')
643
- .action(async (skillPath, opts) => {
644
- try {
645
- await generateSubagent(skillPath, {
646
- output: opts['output'],
647
- tools: opts['tools'],
648
- model: opts['model'],
649
- skipClaudeMd: opts['skipClaudeMd'],
650
- force: opts['force'],
651
- });
652
- }
653
- catch (error) {
654
- console.error(chalk.red('Error generating subagent:'), sanitizeError(error));
655
- process.exit(1);
656
- }
657
- });
658
- }
659
- /**
660
- * Create transform command
661
- */
662
- export function createTransformCommand() {
663
- return new Command('transform')
664
- .description('Upgrade existing skill with subagent configuration')
665
- .argument('[path]', 'Path to skill directory', '.')
666
- .option('--dry-run', 'Preview what would be generated')
667
- .option('--force', 'Overwrite existing subagent')
668
- .option('--batch', 'Process directory of skills')
669
- .option('--tools <tools>', 'Override detected tools (comma-separated)')
670
- .option('--model <model>', 'Model for subagent: sonnet|opus|haiku', 'sonnet')
671
- .action(async (skillPath, opts) => {
672
- try {
673
- await transformSkill(skillPath, {
674
- dryRun: opts['dryRun'],
675
- force: opts['force'],
676
- batch: opts['batch'],
677
- tools: opts['tools'],
678
- model: opts['model'],
679
- });
680
- }
681
- catch (error) {
682
- console.error(chalk.red('Error transforming skill:'), sanitizeError(error));
683
- process.exit(1);
684
- }
685
- });
686
- }
687
- /**
688
- * SMI-1433: Initialize a new MCP server project
689
- */
690
- async function initMcpServer(name, options) {
691
- // Interactive prompts if name not provided
692
- const serverName = name ||
693
- (await input({
694
- message: 'MCP server name:',
695
- validate: (value) => {
696
- if (!value.trim())
697
- return 'Name is required';
698
- if (!/^[a-z][a-z0-9-]*$/.test(value)) {
699
- return 'Name must be lowercase, start with a letter, and contain only letters, numbers, and hyphens';
700
- }
701
- return true;
702
- },
703
- }));
704
- const description = await input({
705
- message: 'Description:',
706
- default: `An MCP server for ${serverName}`,
707
- });
708
- const author = await input({
709
- message: 'Author:',
710
- default: process.env['USER'] || 'author',
711
- });
712
- // Parse initial tools if provided
713
- const initialTools = [];
714
- const toolNameRegex = /^[a-z][a-z0-9_-]*$/;
715
- if (options.tools) {
716
- const toolNames = options.tools
717
- .split(',')
718
- .map((t) => t.trim())
719
- .filter((t) => t.length > 0);
720
- for (const toolName of toolNames) {
721
- if (!toolNameRegex.test(toolName)) {
722
- console.log(chalk.red(`Invalid tool name: ${toolName}. Must be lowercase, start with a letter, and contain only letters, numbers, underscores, and hyphens.`));
723
- return;
724
- }
725
- initialTools.push({
726
- name: toolName,
727
- description: `${toolName} tool`,
728
- parameters: [],
729
- });
730
- }
731
- }
732
- // Ask about tools if none specified
733
- if (initialTools.length === 0) {
734
- const addTools = await confirm({
735
- message: 'Would you like to define initial tools interactively?',
736
- default: false,
737
- });
738
- if (addTools) {
739
- let addMore = true;
740
- while (addMore) {
741
- const toolName = await input({
742
- message: 'Tool name:',
743
- validate: (value) => {
744
- if (!value.trim())
745
- return 'Tool name is required';
746
- if (!/^[a-z][a-z0-9_-]*$/.test(value)) {
747
- return 'Tool name must be lowercase with letters, numbers, underscores, and hyphens';
748
- }
749
- return true;
750
- },
751
- });
752
- const toolDescription = await input({
753
- message: 'Tool description:',
754
- default: `${toolName} tool`,
755
- });
756
- initialTools.push({
757
- name: toolName,
758
- description: toolDescription,
759
- parameters: [],
760
- });
761
- addMore = await confirm({
762
- message: 'Add another tool?',
763
- default: false,
764
- });
765
- }
766
- }
767
- }
768
- const targetDir = options.output ? resolve(options.output) : resolve('.', serverName);
769
- // Check if directory already exists
770
- try {
771
- await stat(targetDir);
772
- if (!options.force) {
773
- const overwrite = await confirm({
774
- message: `Directory ${targetDir} already exists. Overwrite?`,
775
- default: false,
776
- });
777
- if (!overwrite) {
778
- console.log(chalk.yellow('Initialization cancelled'));
779
- return;
780
- }
781
- }
782
- }
783
- catch {
784
- // Directory doesn't exist, continue
785
- }
786
- const spinner = ora('Creating MCP server...').start();
787
- try {
788
- // Generate templates
789
- const files = renderMcpServerTemplates({
790
- name: serverName,
791
- description,
792
- tools: initialTools,
793
- author,
794
- });
795
- // Create directory structure
796
- await mkdir(targetDir, { recursive: true });
797
- await mkdir(join(targetDir, 'src'), { recursive: true });
798
- await mkdir(join(targetDir, 'src', 'tools'), { recursive: true });
799
- // Write all files
800
- for (const [filePath, content] of files) {
801
- const fullPath = join(targetDir, filePath);
802
- const dir = dirname(fullPath);
803
- await mkdir(dir, { recursive: true });
804
- await writeFile(fullPath, content, 'utf-8');
805
- }
806
- spinner.succeed(`Created MCP server at ${targetDir}`);
807
- console.log(chalk.bold('\nNext steps:'));
808
- console.log(chalk.dim(` 1. cd ${targetDir}`));
809
- console.log(chalk.dim(' 2. npm install'));
810
- console.log(chalk.dim(' 3. npm run dev # Run in development mode'));
811
- console.log(chalk.dim(' 4. Edit src/tools/ to add your tool implementations'));
812
- console.log();
813
- console.log(chalk.bold('Configure in Claude Code:'));
814
- console.log(chalk.cyan('─'.repeat(50)));
815
- console.log(chalk.dim(`Add to ~/.claude/settings.json:`));
816
- console.log(chalk.white(`{
817
- "mcpServers": {
818
- "${serverName}": {
819
- "command": "npx",
820
- "args": ["tsx", "${join(targetDir, 'src', 'index.ts')}"]
821
- }
822
- }
823
- }`));
824
- console.log(chalk.cyan('─'.repeat(50)));
825
- console.log();
826
- }
827
- catch (error) {
828
- spinner.fail(`Failed to create MCP server: ${sanitizeError(error)}`);
829
- throw error;
830
- }
831
- }
832
- /**
833
- * Create mcp-init command
834
- */
835
- export function createMcpInitCommand() {
836
- return new Command('mcp-init')
837
- .description('Scaffold a new MCP server project')
838
- .argument('[name]', 'MCP server name')
839
- .option('-o, --output <path>', 'Output directory')
840
- .option('--tools <tools>', 'Initial tools (comma-separated)')
841
- .option('--force', 'Overwrite existing directory')
842
- .action(async (name, opts) => {
843
- try {
844
- await initMcpServer(name, {
845
- output: opts['output'],
846
- tools: opts['tools'],
847
- force: opts['force'],
848
- });
849
- }
850
- catch (error) {
851
- console.error(chalk.red('Error creating MCP server:'), sanitizeError(error));
852
- process.exit(1);
853
- }
854
- });
855
- }
856
- export { initSkill, validateSkill, publishSkill, generateSubagent, transformSkill, initMcpServer };
857
- //# sourceMappingURL=author.js.map