mirror of
https://github.com/rohitg00/skillkit.git
synced 2026-11-18 18:04:26 +00:00
feat(agents): add skill-to-subagent converter command (#34)
* feat(agents): add skill-to-subagent converter command Add `skillkit agent from-skill` command to convert SkillKit skills into Claude Code native subagent format (.md files in .claude/agents/). Features: - Reference mode (default): generates subagent with `skills: [skill-name]` - Inline mode (--inline): embeds full skill content in system prompt - Options: --model, --permission, --global, --output, --dry-run New files: - packages/core/src/agents/skill-converter.ts - packages/core/src/agents/__tests__/skill-converter.test.ts (23 tests) Closes #22 * fix(agents): address code review feedback - Update CLI option descriptions to list all valid values (model: inherit, permission: bypassPermissions) - Add filename sanitization to prevent path traversal attacks via --output - Fix parseAllowedTools to handle both string and YAML array formats - Support space-separated tool lists in allowed-tools - Add tests for array and space-separated formats
This commit is contained in:
@@ -52,6 +52,7 @@ import {
|
||||
AgentListCommand,
|
||||
AgentShowCommand,
|
||||
AgentCreateCommand,
|
||||
AgentFromSkillCommand,
|
||||
AgentTranslateCommand,
|
||||
AgentSyncCommand,
|
||||
AgentValidateCommand,
|
||||
@@ -153,6 +154,7 @@ cli.register(AgentCommand);
|
||||
cli.register(AgentListCommand);
|
||||
cli.register(AgentShowCommand);
|
||||
cli.register(AgentCreateCommand);
|
||||
cli.register(AgentFromSkillCommand);
|
||||
cli.register(AgentTranslateCommand);
|
||||
cli.register(AgentSyncCommand);
|
||||
cli.register(AgentValidateCommand);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import chalk from 'chalk';
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { join, basename } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import {
|
||||
findAllAgents,
|
||||
@@ -17,8 +17,14 @@ import {
|
||||
validateAgent,
|
||||
translateAgent,
|
||||
getAgentTargetDirectory,
|
||||
discoverSkills,
|
||||
readSkillContent,
|
||||
generateSubagentFromSkill,
|
||||
type CustomAgent,
|
||||
type AgentType,
|
||||
type Skill,
|
||||
type AgentPermissionMode,
|
||||
type SkillToSubagentOptions,
|
||||
} from '@skillkit/core';
|
||||
import {
|
||||
getBundledAgents,
|
||||
@@ -43,17 +49,19 @@ export class AgentCommand extends Command {
|
||||
that can be invoked with @mentions or the --agent flag.
|
||||
|
||||
Sub-commands:
|
||||
agent list - List all installed agents
|
||||
agent show - Show agent details
|
||||
agent create - Create a new agent
|
||||
agent translate - Translate agents between formats
|
||||
agent sync - Sync agents to target AI agent
|
||||
agent validate - Validate agent definitions
|
||||
agent list - List all installed agents
|
||||
agent show - Show agent details
|
||||
agent create - Create a new agent
|
||||
agent from-skill - Convert a skill to a subagent
|
||||
agent translate - Translate agents between formats
|
||||
agent sync - Sync agents to target AI agent
|
||||
agent validate - Validate agent definitions
|
||||
`,
|
||||
examples: [
|
||||
['List all agents', '$0 agent list'],
|
||||
['Show agent details', '$0 agent show architect'],
|
||||
['Create new agent', '$0 agent create security-reviewer'],
|
||||
['Convert skill to subagent', '$0 agent from-skill code-simplifier'],
|
||||
['Translate to Cursor format', '$0 agent translate --to cursor'],
|
||||
['Sync agents', '$0 agent sync --agent claude-code'],
|
||||
],
|
||||
@@ -64,6 +72,7 @@ export class AgentCommand extends Command {
|
||||
console.log(' agent list List all installed agents');
|
||||
console.log(' agent show <name> Show agent details');
|
||||
console.log(' agent create <name> Create a new agent');
|
||||
console.log(' agent from-skill <name> Convert a skill to a subagent');
|
||||
console.log(' agent translate Translate agents between formats');
|
||||
console.log(' agent sync Sync agents to target AI agent');
|
||||
console.log(' agent validate [path] Validate agent definitions');
|
||||
@@ -831,9 +840,174 @@ export class AgentAvailableCommand extends Command {
|
||||
}
|
||||
}
|
||||
|
||||
export class AgentFromSkillCommand extends Command {
|
||||
static override paths = [['agent', 'from-skill']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Convert a skill into a Claude Code subagent',
|
||||
details: `
|
||||
Converts a SkillKit skill into a Claude Code native subagent format.
|
||||
The generated .md file can be used with @mentions in Claude Code.
|
||||
|
||||
By default, the subagent references the skill (skills: [skill-name]).
|
||||
Use --inline to embed the full skill content in the system prompt.
|
||||
`,
|
||||
examples: [
|
||||
['Convert skill to subagent', '$0 agent from-skill code-simplifier'],
|
||||
['Create global subagent', '$0 agent from-skill code-simplifier --global'],
|
||||
['Embed skill content inline', '$0 agent from-skill code-simplifier --inline'],
|
||||
['Set model for subagent', '$0 agent from-skill code-simplifier --model opus'],
|
||||
['Preview without writing', '$0 agent from-skill code-simplifier --dry-run'],
|
||||
],
|
||||
});
|
||||
|
||||
skillName = Option.String({ required: true });
|
||||
|
||||
inline = Option.Boolean('--inline,-i', false, {
|
||||
description: 'Embed full skill content in system prompt',
|
||||
});
|
||||
|
||||
model = Option.String('--model,-m', {
|
||||
description: 'Model to use (sonnet, opus, haiku, inherit)',
|
||||
});
|
||||
|
||||
permission = Option.String('--permission,-p', {
|
||||
description: 'Permission mode (default, plan, auto-edit, full-auto, bypassPermissions)',
|
||||
});
|
||||
|
||||
global = Option.Boolean('--global,-g', false, {
|
||||
description: 'Create in ~/.claude/agents/ instead of .claude/agents/',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Custom output filename (without .md)',
|
||||
});
|
||||
|
||||
dryRun = Option.Boolean('--dry-run,-n', false, {
|
||||
description: 'Preview without writing files',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const skills = discoverSkills(process.cwd());
|
||||
const skill = skills.find((s: Skill) => s.name === this.skillName);
|
||||
|
||||
if (!skill) {
|
||||
console.log(chalk.red(`Skill not found: ${this.skillName}`));
|
||||
console.log(chalk.dim('Available skills:'));
|
||||
for (const s of skills.slice(0, 10)) {
|
||||
console.log(chalk.dim(` - ${s.name}`));
|
||||
}
|
||||
if (skills.length > 10) {
|
||||
console.log(chalk.dim(` ... and ${skills.length - 10} more`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skillContent = readSkillContent(skill.path);
|
||||
if (!skillContent) {
|
||||
console.log(chalk.red(`Could not read skill content: ${skill.path}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const options: SkillToSubagentOptions = {
|
||||
inline: this.inline,
|
||||
};
|
||||
|
||||
if (this.model) {
|
||||
const validModels = ['sonnet', 'opus', 'haiku', 'inherit'];
|
||||
if (!validModels.includes(this.model)) {
|
||||
console.log(chalk.red(`Invalid model: ${this.model}`));
|
||||
console.log(chalk.dim(`Valid options: ${validModels.join(', ')}`));
|
||||
return 1;
|
||||
}
|
||||
options.model = this.model as 'sonnet' | 'opus' | 'haiku' | 'inherit';
|
||||
}
|
||||
|
||||
if (this.permission) {
|
||||
const validModes = ['default', 'plan', 'auto-edit', 'full-auto', 'bypassPermissions'];
|
||||
if (!validModes.includes(this.permission)) {
|
||||
console.log(chalk.red(`Invalid permission mode: ${this.permission}`));
|
||||
console.log(chalk.dim(`Valid options: ${validModes.join(', ')}`));
|
||||
return 1;
|
||||
}
|
||||
options.permissionMode = this.permission as AgentPermissionMode;
|
||||
}
|
||||
|
||||
const content = generateSubagentFromSkill(skill, skillContent, options);
|
||||
|
||||
const targetDir = this.global
|
||||
? join(homedir(), '.claude', 'agents')
|
||||
: join(process.cwd(), '.claude', 'agents');
|
||||
|
||||
let filename: string;
|
||||
if (this.output) {
|
||||
const sanitized = sanitizeFilename(this.output);
|
||||
if (!sanitized) {
|
||||
console.log(chalk.red(`Invalid output filename: ${this.output}`));
|
||||
console.log(chalk.dim('Filename must contain only alphanumeric characters, hyphens, and underscores'));
|
||||
return 1;
|
||||
}
|
||||
filename = `${sanitized}.md`;
|
||||
} else {
|
||||
filename = `${skill.name}.md`;
|
||||
}
|
||||
|
||||
const outputPath = join(targetDir, filename);
|
||||
|
||||
if (this.dryRun) {
|
||||
console.log(chalk.cyan('Preview (dry run):\n'));
|
||||
console.log(chalk.dim(`Would write to: ${outputPath}`));
|
||||
console.log(chalk.dim('─'.repeat(50)));
|
||||
console.log(content);
|
||||
console.log(chalk.dim('─'.repeat(50)));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!existsSync(targetDir)) {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
}
|
||||
|
||||
if (existsSync(outputPath)) {
|
||||
console.log(chalk.yellow(`Overwriting existing file: ${outputPath}`));
|
||||
}
|
||||
|
||||
writeFileSync(outputPath, content);
|
||||
|
||||
console.log(chalk.green(`Created subagent: ${outputPath}`));
|
||||
console.log();
|
||||
console.log(chalk.dim(`Invoke with: @${skill.name}`));
|
||||
if (!this.inline) {
|
||||
console.log(chalk.dim(`Skills referenced: ${skill.name}`));
|
||||
} else {
|
||||
console.log(chalk.dim('Skill content embedded inline'));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function formatCategoryName(category: string): string {
|
||||
return category
|
||||
.split('-')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
function sanitizeFilename(input: string): string | null {
|
||||
const base = basename(input);
|
||||
const stem = base.replace(/\.md$/i, '');
|
||||
|
||||
if (!stem || stem.startsWith('.') || stem.startsWith('-')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(stem)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (stem.length > 64) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return stem;
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ export {
|
||||
AgentListCommand,
|
||||
AgentShowCommand,
|
||||
AgentCreateCommand,
|
||||
AgentFromSkillCommand,
|
||||
AgentTranslateCommand,
|
||||
AgentSyncCommand,
|
||||
AgentValidateCommand,
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* Skill to Subagent Converter Tests
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
skillToSubagent,
|
||||
generateSubagentFromSkill,
|
||||
} from '../skill-converter.js';
|
||||
import type { Skill } from '../../types.js';
|
||||
|
||||
describe('Skill Converter', () => {
|
||||
const mockSkill: Skill = {
|
||||
name: 'code-simplifier',
|
||||
description: 'Simplifies and refines code for clarity and maintainability',
|
||||
path: '/path/to/skills/code-simplifier',
|
||||
location: 'project',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const mockSkillContent = `---
|
||||
name: code-simplifier
|
||||
description: Simplifies and refines code for clarity and maintainability
|
||||
version: "1.0.0"
|
||||
author: skillkit
|
||||
tags: [refactoring, code-quality]
|
||||
allowed-tools: Edit, Read, Grep
|
||||
---
|
||||
|
||||
# Code Simplifier
|
||||
|
||||
You are an expert at simplifying code.
|
||||
|
||||
## Guidelines
|
||||
|
||||
- Remove unnecessary complexity
|
||||
- Improve readability
|
||||
- Preserve functionality
|
||||
`;
|
||||
|
||||
describe('skillToSubagent', () => {
|
||||
it('should convert skill to canonical agent in reference mode', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent);
|
||||
|
||||
expect(result.name).toBe('code-simplifier');
|
||||
expect(result.description).toBe('Simplifies and refines code for clarity and maintainability');
|
||||
expect(result.skills).toEqual(['code-simplifier']);
|
||||
expect(result.sourceFormat).toBe('claude-agent');
|
||||
expect(result.userInvocable).toBe(true);
|
||||
});
|
||||
|
||||
it('should not include skills array in inline mode', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent, { inline: true });
|
||||
|
||||
expect(result.name).toBe('code-simplifier');
|
||||
expect(result.skills).toBeUndefined();
|
||||
expect(result.content).toContain('Code Simplifier');
|
||||
expect(result.content).toContain('Remove unnecessary complexity');
|
||||
});
|
||||
|
||||
it('should parse allowed-tools from skill frontmatter', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent);
|
||||
|
||||
expect(result.allowedTools).toEqual(['Edit', 'Read', 'Grep']);
|
||||
});
|
||||
|
||||
it('should use option tools over frontmatter tools', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent, {
|
||||
tools: ['Bash', 'Write'],
|
||||
});
|
||||
|
||||
expect(result.allowedTools).toEqual(['Bash', 'Write']);
|
||||
});
|
||||
|
||||
it('should set model from options', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent, {
|
||||
model: 'opus',
|
||||
});
|
||||
|
||||
expect(result.model).toBe('opus');
|
||||
});
|
||||
|
||||
it('should not set model when inherit is specified', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent, {
|
||||
model: 'inherit',
|
||||
});
|
||||
|
||||
expect(result.model).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should set permission mode from options', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent, {
|
||||
permissionMode: 'plan',
|
||||
});
|
||||
|
||||
expect(result.permissionMode).toBe('plan');
|
||||
});
|
||||
|
||||
it('should set disallowed tools from options', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent, {
|
||||
disallowedTools: ['Bash', 'Write'],
|
||||
});
|
||||
|
||||
expect(result.disallowedTools).toEqual(['Bash', 'Write']);
|
||||
});
|
||||
|
||||
it('should preserve version and author from frontmatter', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent);
|
||||
|
||||
expect(result.version).toBe('1.0.0');
|
||||
expect(result.author).toBe('skillkit');
|
||||
});
|
||||
|
||||
it('should preserve tags from frontmatter', () => {
|
||||
const result = skillToSubagent(mockSkill, mockSkillContent);
|
||||
|
||||
expect(result.tags).toEqual(['refactoring', 'code-quality']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateSubagentFromSkill', () => {
|
||||
it('should generate valid markdown with frontmatter in reference mode', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
|
||||
|
||||
expect(content).toContain('---');
|
||||
expect(content).toContain('name: code-simplifier');
|
||||
expect(content).toContain('description: Simplifies and refines code');
|
||||
expect(content).toContain('skills:');
|
||||
expect(content).toContain(' - code-simplifier');
|
||||
expect(content).toContain('user-invocable: true');
|
||||
});
|
||||
|
||||
it('should generate valid markdown in inline mode', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, { inline: true });
|
||||
|
||||
expect(content).toContain('---');
|
||||
expect(content).toContain('name: code-simplifier');
|
||||
expect(content).not.toContain('skills:');
|
||||
expect(content).toContain('# Code Simplifier');
|
||||
expect(content).toContain('Remove unnecessary complexity');
|
||||
});
|
||||
|
||||
it('should include tools in frontmatter', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
|
||||
|
||||
expect(content).toContain('tools:');
|
||||
expect(content).toContain(' - Edit');
|
||||
expect(content).toContain(' - Read');
|
||||
expect(content).toContain(' - Grep');
|
||||
});
|
||||
|
||||
it('should include model in frontmatter when specified', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, {
|
||||
model: 'opus',
|
||||
});
|
||||
|
||||
expect(content).toContain('model: opus');
|
||||
});
|
||||
|
||||
it('should include permission mode in frontmatter when specified', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, {
|
||||
permissionMode: 'plan',
|
||||
});
|
||||
|
||||
expect(content).toContain('permissionMode: plan');
|
||||
});
|
||||
|
||||
it('should include disallowed tools in frontmatter when specified', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, {
|
||||
disallowedTools: ['Bash'],
|
||||
});
|
||||
|
||||
expect(content).toContain('disallowedTools:');
|
||||
expect(content).toContain(' - Bash');
|
||||
});
|
||||
|
||||
it('should include version and author in frontmatter', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
|
||||
|
||||
expect(content).toContain('version: "1.0.0"');
|
||||
expect(content).toContain('author: skillkit');
|
||||
});
|
||||
|
||||
it('should include tags in frontmatter', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
|
||||
|
||||
expect(content).toContain('tags: [refactoring, code-quality]');
|
||||
});
|
||||
|
||||
it('should generate reference content with skill description', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
|
||||
|
||||
expect(content).toContain('# Code Simplifier');
|
||||
expect(content).toContain('uses the "code-simplifier" skill');
|
||||
expect(content).toContain('## Skill Description');
|
||||
expect(content).toContain('Simplifies and refines code');
|
||||
});
|
||||
|
||||
it('should embed full skill content in inline mode', () => {
|
||||
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, { inline: true });
|
||||
|
||||
expect(content).toContain('You are a specialized assistant');
|
||||
expect(content).toContain('Remove unnecessary complexity');
|
||||
expect(content).toContain('Improve readability');
|
||||
expect(content).toContain('Preserve functionality');
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should handle skill without frontmatter', () => {
|
||||
const noFrontmatterContent = `# Simple Skill
|
||||
|
||||
Just some content without frontmatter.
|
||||
`;
|
||||
|
||||
const result = skillToSubagent(mockSkill, noFrontmatterContent);
|
||||
|
||||
expect(result.name).toBe('code-simplifier');
|
||||
expect(result.description).toBe('Simplifies and refines code for clarity and maintainability');
|
||||
expect(result.allowedTools).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle skill with empty allowed-tools', () => {
|
||||
const contentWithEmptyTools = `---
|
||||
name: test-skill
|
||||
description: Test
|
||||
allowed-tools:
|
||||
---
|
||||
|
||||
Content here.
|
||||
`;
|
||||
|
||||
const skill: Skill = {
|
||||
name: 'test-skill',
|
||||
description: 'Test',
|
||||
path: '/path/to/test-skill',
|
||||
location: 'project',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const result = skillToSubagent(skill, contentWithEmptyTools);
|
||||
|
||||
expect(result.allowedTools).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle skill name with multiple hyphens', () => {
|
||||
const skill: Skill = {
|
||||
name: 'my-complex-skill-name',
|
||||
description: 'A complex skill',
|
||||
path: '/path/to/skill',
|
||||
location: 'project',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const content = generateSubagentFromSkill(skill, `---
|
||||
name: my-complex-skill-name
|
||||
description: A complex skill
|
||||
---
|
||||
|
||||
Content.
|
||||
`);
|
||||
|
||||
expect(content).toContain('# My Complex Skill Name');
|
||||
});
|
||||
|
||||
it('should handle space-separated allowed-tools format', () => {
|
||||
const contentWithSpaceSeparated = `---
|
||||
name: test-skill
|
||||
description: Test
|
||||
allowed-tools: Bash(git:*) Read Write Edit
|
||||
---
|
||||
|
||||
Content here.
|
||||
`;
|
||||
|
||||
const skill: Skill = {
|
||||
name: 'test-skill',
|
||||
description: 'Test',
|
||||
path: '/path/to/test-skill',
|
||||
location: 'project',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const result = skillToSubagent(skill, contentWithSpaceSeparated);
|
||||
|
||||
expect(result.allowedTools).toEqual(['Bash(git:*)', 'Read', 'Write', 'Edit']);
|
||||
});
|
||||
|
||||
it('should handle YAML array format for allowed-tools', () => {
|
||||
const contentWithArrayTools = `---
|
||||
name: test-skill
|
||||
description: Test
|
||||
allowed-tools:
|
||||
- Read
|
||||
- Write
|
||||
- Bash(npm:*)
|
||||
---
|
||||
|
||||
Content here.
|
||||
`;
|
||||
|
||||
const skill: Skill = {
|
||||
name: 'test-skill',
|
||||
description: 'Test',
|
||||
path: '/path/to/test-skill',
|
||||
location: 'project',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const result = skillToSubagent(skill, contentWithArrayTools);
|
||||
|
||||
expect(result.allowedTools).toEqual(['Read', 'Write', 'Bash(npm:*)']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -60,3 +60,11 @@ export {
|
||||
getAgentTargetDirectory,
|
||||
isAgentCompatible,
|
||||
} from './translator.js';
|
||||
|
||||
// Skill Converter
|
||||
export {
|
||||
skillToSubagent,
|
||||
generateSubagentFromSkill,
|
||||
loadAndConvertSkill,
|
||||
type SkillToSubagentOptions,
|
||||
} from './skill-converter.js';
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Skill to Subagent Converter
|
||||
*
|
||||
* Converts SkillKit skills into Claude Code native subagent format (.md files).
|
||||
* Supports both reference mode (skills: [skill-name]) and inline mode (embedded content).
|
||||
*/
|
||||
|
||||
import type { Skill, SkillFrontmatter } from '../types.js';
|
||||
import type { CanonicalAgent, AgentPermissionMode } from './types.js';
|
||||
import { extractFrontmatter, readSkillContent } from '../skills.js';
|
||||
|
||||
/**
|
||||
* Options for skill-to-subagent conversion
|
||||
*/
|
||||
export interface SkillToSubagentOptions {
|
||||
/** Embed full skill content in system prompt (default: false - use skills reference) */
|
||||
inline?: boolean;
|
||||
/** Model to use (sonnet, opus, haiku, inherit) */
|
||||
model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
|
||||
/** Permission mode for the agent */
|
||||
permissionMode?: AgentPermissionMode;
|
||||
/** Tools the agent is allowed to use */
|
||||
tools?: string[];
|
||||
/** Tools the agent cannot use */
|
||||
disallowedTools?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a skill to a CanonicalAgent representation
|
||||
*/
|
||||
export function skillToSubagent(
|
||||
skill: Skill,
|
||||
skillContent: string,
|
||||
options?: SkillToSubagentOptions
|
||||
): CanonicalAgent {
|
||||
const frontmatter = extractFrontmatter(skillContent) as Partial<SkillFrontmatter> | null;
|
||||
const inline = options?.inline ?? false;
|
||||
|
||||
const allowedTools = parseAllowedTools(frontmatter, options?.tools);
|
||||
const content = inline
|
||||
? generateInlineContent(skill, skillContent)
|
||||
: generateReferenceContent(skill, frontmatter);
|
||||
|
||||
return {
|
||||
name: skill.name,
|
||||
description: skill.description,
|
||||
model: options?.model === 'inherit' ? undefined : options?.model,
|
||||
permissionMode: options?.permissionMode,
|
||||
disallowedTools: options?.disallowedTools,
|
||||
allowedTools,
|
||||
skills: inline ? undefined : [skill.name],
|
||||
content,
|
||||
sourceFormat: 'claude-agent',
|
||||
sourceAgent: 'claude-code',
|
||||
version: frontmatter?.version,
|
||||
author: frontmatter?.author,
|
||||
tags: frontmatter?.tags,
|
||||
userInvocable: true,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the markdown content for a Claude Code subagent from a skill
|
||||
*/
|
||||
export function generateSubagentFromSkill(
|
||||
skill: Skill,
|
||||
skillContent: string,
|
||||
options?: SkillToSubagentOptions
|
||||
): string {
|
||||
const canonical = skillToSubagent(skill, skillContent, options);
|
||||
return generateSubagentMarkdown(canonical, options?.inline ?? false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse allowed-tools from skill frontmatter
|
||||
* Handles both string (comma or space-separated) and array formats
|
||||
*/
|
||||
function parseAllowedTools(
|
||||
frontmatter: Partial<SkillFrontmatter> | null,
|
||||
optionTools?: string[]
|
||||
): string[] | undefined {
|
||||
if (optionTools && optionTools.length > 0) {
|
||||
return optionTools;
|
||||
}
|
||||
|
||||
const allowedTools = frontmatter?.['allowed-tools'];
|
||||
if (!allowedTools) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (Array.isArray(allowedTools)) {
|
||||
const result = allowedTools
|
||||
.map(t => (typeof t === 'string' ? t.trim() : ''))
|
||||
.filter(Boolean);
|
||||
return result.length > 0 ? result : undefined;
|
||||
}
|
||||
|
||||
if (typeof allowedTools === 'string') {
|
||||
const result = allowedTools
|
||||
.split(/[,\s]+/)
|
||||
.map(t => t.trim())
|
||||
.filter(Boolean);
|
||||
return result.length > 0 ? result : undefined;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate inline content (full skill embedded)
|
||||
*/
|
||||
function generateInlineContent(skill: Skill, skillContent: string): string {
|
||||
const bodyContent = extractBodyContent(skillContent);
|
||||
|
||||
const lines: string[] = [];
|
||||
lines.push(`# ${formatAgentName(skill.name)}`);
|
||||
lines.push('');
|
||||
lines.push('You are a specialized assistant powered by the following skill.');
|
||||
lines.push('');
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
lines.push(bodyContent.trim());
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate reference content (skill referenced by name)
|
||||
*/
|
||||
function generateReferenceContent(
|
||||
skill: Skill,
|
||||
frontmatter: Partial<SkillFrontmatter> | null
|
||||
): string {
|
||||
const lines: string[] = [];
|
||||
lines.push(`# ${formatAgentName(skill.name)}`);
|
||||
lines.push('');
|
||||
lines.push(`You are a specialized assistant that uses the "${skill.name}" skill.`);
|
||||
lines.push('');
|
||||
lines.push('## Skill Description');
|
||||
lines.push('');
|
||||
lines.push(skill.description);
|
||||
lines.push('');
|
||||
lines.push('## Usage');
|
||||
lines.push('');
|
||||
lines.push(`This agent automatically loads the "${skill.name}" skill.`);
|
||||
lines.push('Follow the skill instructions to complete tasks effectively.');
|
||||
|
||||
if (frontmatter?.tags && frontmatter.tags.length > 0) {
|
||||
lines.push('');
|
||||
lines.push('## Related Topics');
|
||||
lines.push('');
|
||||
lines.push(frontmatter.tags.map(t => `- ${t}`).join('\n'));
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate full subagent markdown file content
|
||||
*/
|
||||
function generateSubagentMarkdown(
|
||||
canonical: CanonicalAgent,
|
||||
isInline: boolean
|
||||
): string {
|
||||
const lines: string[] = ['---'];
|
||||
|
||||
lines.push(`name: ${canonical.name}`);
|
||||
lines.push(`description: ${escapeYamlString(canonical.description)}`);
|
||||
|
||||
if (canonical.model) {
|
||||
lines.push(`model: ${canonical.model}`);
|
||||
}
|
||||
if (canonical.permissionMode) {
|
||||
lines.push(`permissionMode: ${canonical.permissionMode}`);
|
||||
}
|
||||
|
||||
appendYamlList(lines, 'tools', canonical.allowedTools);
|
||||
appendYamlList(lines, 'disallowedTools', canonical.disallowedTools);
|
||||
|
||||
if (!isInline) {
|
||||
appendYamlList(lines, 'skills', canonical.skills);
|
||||
}
|
||||
|
||||
if (canonical.version) {
|
||||
lines.push(`version: "${canonical.version}"`);
|
||||
}
|
||||
if (canonical.author) {
|
||||
lines.push(`author: ${canonical.author}`);
|
||||
}
|
||||
if (canonical.tags && canonical.tags.length > 0) {
|
||||
lines.push(`tags: [${canonical.tags.join(', ')}]`);
|
||||
}
|
||||
if (canonical.userInvocable !== undefined) {
|
||||
lines.push(`user-invocable: ${canonical.userInvocable}`);
|
||||
}
|
||||
|
||||
lines.push('---', '', canonical.content);
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function appendYamlList(lines: string[], key: string, items?: string[]): void {
|
||||
if (!items || items.length === 0) return;
|
||||
lines.push(`${key}:`);
|
||||
for (const item of items) {
|
||||
lines.push(` - ${item}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract body content from skill markdown (without frontmatter)
|
||||
*/
|
||||
function extractBodyContent(content: string): string {
|
||||
const match = content.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)$/);
|
||||
if (match) {
|
||||
return match[1];
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format agent name for display (kebab-case to Title Case)
|
||||
*/
|
||||
function formatAgentName(name: string): string {
|
||||
return name
|
||||
.split('-')
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape special characters in YAML strings
|
||||
*/
|
||||
function escapeYamlString(str: string): string {
|
||||
if (/[:\{\}\[\],&*#?|\-<>=!%@`]/.test(str) || str.includes('\n')) {
|
||||
return `"${str.replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a skill and generate subagent content
|
||||
* Convenience function that reads skill content and generates subagent markdown
|
||||
*/
|
||||
export function loadAndConvertSkill(
|
||||
skill: Skill,
|
||||
options?: SkillToSubagentOptions
|
||||
): { success: boolean; content?: string; error?: string } {
|
||||
const skillContent = readSkillContent(skill.path);
|
||||
|
||||
if (!skillContent) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Could not read skill content from: ${skill.path}`,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const content = generateSubagentFromSkill(skill, skillContent, options);
|
||||
return { success: true, content };
|
||||
} catch (err) {
|
||||
return {
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : 'Unknown error',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,12 @@ export const AgentFrontmatter = z.object({
|
||||
/** Allowed tools for this agent */
|
||||
allowedTools: z.union([
|
||||
z.array(z.string()),
|
||||
z.string(), // YAML-style list in frontmatter
|
||||
z.string(),
|
||||
]).optional(),
|
||||
/** Tools (Claude Code native format alias for allowedTools) */
|
||||
tools: z.union([
|
||||
z.array(z.string()),
|
||||
z.string(),
|
||||
]).optional(),
|
||||
/** Agent-scoped hooks */
|
||||
hooks: z.array(AgentHook).optional(),
|
||||
|
||||
Reference in New Issue
Block a user