Compare commits

..
7 Commits
Author SHA1 Message Date
Rohit Ghumare 570ae26cd5 chore: bump version to 1.6.4 2026-01-25 14:15:03 +00:00
Rohit Ghumare 413519d486 feat: update agent adapters for 2026 compatibility (#10)
* feat: update agent adapters for 2026 compatibility

- Add new skill-translator module for cross-agent skill translation
- Update Cursor adapter to use .cursor/rules/*.mdc format with YAML frontmatter
- Update Windsurf adapter to use .windsurf/rules/*.md with mode field
- Update GitHub Copilot to use .github/copilot-instructions.md
- Update Trae to use .trae/rules/project_rules.md with YAML frontmatter
- Update OpenCode global path to ~/.config/opencode/
- Add new discovery paths for Cursor, Kilo, Roo, Windsurf, GitHub Copilot
- Improve agent detection with additional config file checks

BREAKING CHANGE: Config file paths have changed for Cursor, Windsurf, Trae, and GitHub Copilot adapters to match their 2026 specifications.

* feat: add e2e tests for skill-translator and fix translation issues

- Add comprehensive e2e tests for skill translator (86 tests)
- Fix translateSkillToAll to include all 17 agents
- Fix writeTranslatedSkill to check for failed translations
- Update vitest config to resolve workspace packages
- Remove unnecessary 2026 comments from agent adapters and skill-translator

* fix: improve agent detection and add overwrite option to translator

Agent detection fixes:
- github-copilot: Remove overly broad .github dir check, only detect
  Copilot-specific artifacts (copilot-instructions.md, instructions, ~/.copilot)
- kilo: Fix modes path from .kilocodemodes to .kilocode/modes
- roo: Fix modes path from .roomodes to .roo/modes

Translator improvements:
- Add overwrite option to writeTranslatedSkill() to prevent accidental overwrites
- Return skipped flag when file exists and overwrite=false

Refactoring:
- Centralize agent config in packages/core/src/agent-config.ts
- Update all agent adapters to use shared AGENT_CONFIG
- Re-export utility functions for backwards compatibility

* fix: update clawdbot test and use workspace dependency

- Update clawdbot test to expect new standardized skillsDir (.clawdbot/skills)
- Change @skillkit/core dependency to workspace:* for proper monorepo linking

* fix: address CodeRabbit and Devin review suggestions

- Remove AGENTS.md from detection in Kilo, Roo, Trae adapters (prevents false positives)
- Fix AmpAdapter detection path (check .amp instead of .agents)
- Fix regex pattern in parseConfig for markdown adapters to match any skill name format
- Add hooks and permissionMode to specialFields for proper extraction
- Add path traversal protection in writeTranslatedSkill
- Fix boolean field preservation using 'in' check instead of truthy checks
- Add mode field preservation for Windsurf
- Add permissionMode support for Roo adapter
2026-01-25 14:09:47 +00:00
Rohit Ghumare eadbaff07e feat: add recursive agent translation support
- Add --recursive flag to scan nested directories for agents
- Add --source flag to specify custom source directory
- New functions: discoverAgentsRecursive, discoverAgentsFromPath
- Add 13 new tests for recursive discovery
- Update README with agent commands documentation
- Bump version to 1.6.3
2026-01-25 12:07:52 +00:00
Rohit Ghumare 10e8c389e3 fix: correct fallback skills source from non-existent repo to built-in
The fallback sample skills were referencing 'skillkit/samples' which
is a non-existent GitHub repository. Changed to 'built-in' to clearly
indicate these are bundled sample skills.

Fixes #9
2026-01-25 11:50:21 +00:00
Rohit Ghumare 94c77707c4 chore: bump version to 1.6.2 2026-01-25 01:17:41 +00:00
Rohit Ghumare 821fd1b495 feat: add custom AI sub-agents support (Phase 19) (#8)
* feat: add custom AI sub-agents support (Phase 19)

Add full support for custom AI sub-agents (.claude/agents/*.md):

Core module (packages/core/src/agents/):
- types.ts: Agent types, schemas, AGENT_DISCOVERY_PATHS for 17 AI agents
- parser.ts: Parse agent markdown with YAML frontmatter
- discovery.ts: Discover agents across all supported agent directories
- translator.ts: Translate agents between Claude, Cursor, and universal formats
- index.ts: Export all agent functionality

CLI commands (skillkit agent):
- list: List all installed agents (project + global)
- show: Show agent details
- create: Create a new agent from template
- translate: Translate agents between formats
- sync: Sync agents to target AI coding agent
- validate: Validate agent definitions

Features:
- Agent discovery across 17 AI coding agents
- Frontmatter support: name, description, model, permissionMode,
  disallowedTools, allowedTools, hooks, skills, context, tags, author, version
- Translation between claude-agent, cursor-agent, and universal formats
- 36 new tests (706 total passing)

Closes #5

* fix: use workspace:* for internal dependencies

pnpm automatically converts workspace:* to actual versions when publishing,
but uses local workspace packages during development and CI.

* fix: replace require() with ESM imports and add name validation

- parser.ts: Import statSync instead of using require('node:fs')
- translator.ts: Add ESM imports for extractAgentFrontmatter, extractAgentContent, AgentFrontmatter
- agent.ts: Add validation for agent name format (lowercase alphanumeric with hyphens)

Addresses review comments from Devin.
2026-01-25 00:23:07 +00:00
Rohit Ghumare 288427d9b3 docs: improve README tagline and value proposition
- Change tagline from "One CLI. 17 AI Agents. Zero Lock-in." to
  "Supercharge Every AI Coding Agent"
- Add "What are AI Agent Skills?" callout explaining skills to newcomers
- Move problem/solution section higher for immediate visibility
- Update npm package description for better discoverability
- Update GitHub repo description
- Remove redundant "Why SkillKit Exists" section at bottom
- Relocate "What's New in v1.6" after comparison table
2026-01-24 21:52:51 +00:00
47 changed files with 5739 additions and 2113 deletions
+39 -27
View File
@@ -5,32 +5,23 @@
[![CI](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml/badge.svg)](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
## One CLI. 17 AI Agents. Zero Lock-in.
## Supercharge Every AI Coding Agent
**Write skills once, use everywhere.** SkillKit is the universal platform that lets your AI coding skills work across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more agents.
**Give your AI agents new abilities with portable, reusable skills.** Install from a curated marketplace, create your own, and use them across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more agents.
> **What are AI Agent Skills?** Skills are instruction files that teach AI coding agents how to handle specific tasks - like processing PDFs, following React best practices, or enforcing security patterns. Think of them as plugins for your AI assistant.
```bash
npm install -g skillkit
```
## What's New in v1.6.0
## Why SkillKit?
- **Methodology Framework**: 5 ready-to-use development frameworks (Agile, TDD, DevOps, Security-First, Documentation-First) with 13 specialized skills
- **Hooks System**: Event-driven skill triggers - auto-activate on git commits, file changes, builds, tests, deployments
- **Agent Orchestration**: Multi-agent team coordination with leader/teammate roles and task assignment
- **Plan System**: Structured plan creation with validation and execution - parse, validate, and execute development plans
- **Slash Commands**: Generate agent-native commands from natural language for all 17 AI agents
- **Enhanced TUI**: New Methodology (o) and Plan (n) screens with improved navigation
**The problem:** You've built amazing skills for Claude Code. Now you want to try Cursor. Or your team uses different agents. Each agent has different formats and directories. Without SkillKit, you either rewrite everything, lock yourself into one agent, or give up on skills entirely.
## The Problem
**The solution:** SkillKit translates skills between all 17 agents automatically. Write once, use everywhere.
You've built amazing skills for Claude Code. Now you want to try Cursor. Or your team uses different agents. Your options:
1. **Rewrite everything** - each agent has different formats, directories, and conventions
2. **Pick one agent** - lock yourself in, miss out on innovations
3. **Give up on skills** - lose the productivity gains
## The Solution
## See It In Action
```bash
# Install a skill for ALL your agents at once
@@ -60,6 +51,16 @@ skillkit recommend
| **Session Memory** | Knowledge dies with each session | Persistent learning across agents |
| **Skill Testing** | Hope it works | Test framework with assertions |
## What's New in v1.6
- **Recursive Agent Translation**: Batch translate entire directories of agents with `--recursive` flag
- **Custom AI Sub-Agents**: Create, translate, sync, and validate custom AI sub-agents across 17 coding agents
- **Methodology Framework**: 5 ready-to-use frameworks (Agile, TDD, DevOps, Security-First, Documentation-First)
- **Hooks System**: Event-driven skill triggers - auto-activate on commits, file changes, builds
- **Agent Orchestration**: Multi-agent team coordination with leader/teammate roles
- **Plan System**: Parse, validate, and execute structured development plans
- **Slash Commands**: Generate agent-native `/commands` from natural language
## 5-Minute Quick Start
```bash
@@ -96,6 +97,12 @@ skillkit translate --all --to windsurf
# Preview translation without writing
skillkit translate my-skill --to codex --dry-run
# Batch translate from a custom source directory
skillkit agent translate --source ./my-skills --to cursor
# Recursively translate nested agent directories
skillkit agent translate --source ./kubernetes-skills --to cursor --recursive
```
**Supported Agents:** Claude Code, Cursor, Codex, Gemini CLI, OpenCode, Antigravity, Amp, Clawdbot, Droid, GitHub Copilot, Goose, Kilo, Kiro, Roo, Trae, Windsurf, Universal
@@ -273,6 +280,21 @@ skillkit context init # Initialize project context
skillkit context sync # Sync context to agents
```
### Custom AI Sub-Agents
```bash
skillkit agent list # List all installed agents
skillkit agent show <name> # Show agent details
skillkit agent create <name> # Create a new agent
skillkit agent translate # Translate agents between formats
--source ./path # Source directory or file
--to cursor # Target agent format
--recursive # Scan subdirectories recursively
--dry-run # Preview without writing
skillkit agent sync # Sync agents to target AI agent
skillkit agent validate # Validate agent definitions
```
### Memory System
```bash
@@ -421,16 +443,6 @@ disabledSkills:
- deprecated-skill
```
## Why SkillKit Exists
AI coding agents are amazing, but the ecosystem is fragmented:
- **Skills don't transfer** between agents
- **Knowledge dies** when sessions end
- **No standard** for skill quality or testing
- **Manual discovery** of useful skills
SkillKit solves these problems with a universal platform that works across all major AI coding agents.
## License
Apache License 2.0 - see [LICENSE](LICENSE) for details.
+6 -6
View File
@@ -1,7 +1,7 @@
{
"name": "skillkit",
"version": "1.6.1",
"description": "Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more",
"version": "1.6.4",
"description": "Supercharge AI coding agents with portable skills. Install, translate, and share skills across Claude Code, Cursor, Codex, Copilot & 13 more",
"type": "module",
"bin": {
"skillkit": "./dist/cli.js",
@@ -53,10 +53,10 @@
"node": ">=18.0.0"
},
"dependencies": {
"@skillkit/core": "^1.6.0",
"@skillkit/agents": "^1.6.0",
"@skillkit/cli": "^1.6.0",
"@skillkit/tui": "^1.6.0",
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"@skillkit/cli": "workspace:*",
"@skillkit/tui": "workspace:*",
"clipanion": "^4.0.0-rc.4"
},
"devDependencies": {
+14
View File
@@ -39,6 +39,13 @@ import {
CommandCmd,
AICommand,
AuditCommand,
AgentCommand,
AgentListCommand,
AgentShowCommand,
AgentCreateCommand,
AgentTranslateCommand,
AgentSyncCommand,
AgentValidateCommand,
} from '@skillkit/cli';
const __filename = fileURLToPath(import.meta.url);
@@ -91,5 +98,12 @@ cli.register(PlanCommand);
cli.register(CommandCmd);
cli.register(AICommand);
cli.register(AuditCommand);
cli.register(AgentCommand);
cli.register(AgentListCommand);
cli.register(AgentShowCommand);
cli.register(AgentCreateCommand);
cli.register(AgentTranslateCommand);
cli.register(AgentSyncCommand);
cli.register(AgentValidateCommand);
cli.runExit(process.argv.slice(2));
+761
View File
@@ -0,0 +1,761 @@
/**
* E2E Tests: Skill Translator
*
* End-to-end tests for cross-agent skill translation.
* Tests the complete workflow of parsing, translating, and writing skills.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { join } from 'node:path';
import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
import {
createTestDir,
cleanupTestDir,
createTestSkill,
testFileExists,
readTestFile,
} from './helpers/cli-runner.js';
import {
parseSkillToCanonical,
parseSkillContentToCanonical,
translateSkillToAgent,
translateSkillToAll,
writeTranslatedSkill,
generateSkillsConfig,
getAgentSkillsDir,
getAgentConfigFile,
AGENT_SKILL_FORMATS,
type CrossAgentSkill,
} from '@skillkit/core';
// All 17 supported agents
const SUPPORTED_AGENTS = [
'claude-code',
'cursor',
'codex',
'gemini-cli',
'opencode',
'antigravity',
'amp',
'clawdbot',
'droid',
'github-copilot',
'goose',
'kilo',
'kiro-cli',
'roo',
'trae',
'windsurf',
'universal',
] as const;
describe('E2E: Skill Translator - Parsing', () => {
let testDir: string;
beforeEach(() => {
testDir = createTestDir('skillkit-translator-');
});
afterEach(() => {
cleanupTestDir(testDir);
});
describe('parseSkillToCanonical', () => {
it('should parse a complete SKILL.md with all frontmatter fields', () => {
const skillDir = join(testDir, 'complete-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `---
name: complete-skill
description: A comprehensive skill for E2E testing
version: "2.0.0"
author: SkillKit Team
tags:
- testing
- e2e
- comprehensive
allowed-tools: Read, Write, Bash(npm:*)
---
# Complete Skill
This skill tests all parsing capabilities.
## Features
- Full frontmatter parsing
- Content extraction
- Agent-specific field handling
## Usage
\`\`\`bash
skillkit read complete-skill
\`\`\`
`);
const result = parseSkillToCanonical(skillDir);
expect(result).not.toBeNull();
expect(result?.name).toBe('complete-skill');
expect(result?.description).toBe('A comprehensive skill for E2E testing');
expect(result?.version).toBe('2.0.0');
expect(result?.author).toBe('SkillKit Team');
expect(result?.tags).toEqual(['testing', 'e2e', 'comprehensive']);
expect(result?.allowedTools).toEqual(['Read', 'Write', 'Bash(npm:*)']);
expect(result?.content).toContain('# Complete Skill');
expect(result?.content).toContain('## Features');
});
it('should handle SKILL.md with minimal frontmatter', () => {
const skillDir = join(testDir, 'minimal-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `---
name: minimal-skill
description: Just the basics
---
# Minimal Skill
Simple content.
`);
const result = parseSkillToCanonical(skillDir);
expect(result).not.toBeNull();
expect(result?.name).toBe('minimal-skill');
expect(result?.description).toBe('Just the basics');
expect(result?.version).toBeUndefined();
expect(result?.author).toBeUndefined();
});
it('should extract description from content when not in frontmatter', () => {
const skillDir = join(testDir, 'no-desc-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `---
name: no-desc-skill
---
This is the first paragraph which should become the description automatically.
## More Content
Additional content here.
`);
const result = parseSkillToCanonical(skillDir);
expect(result).not.toBeNull();
expect(result?.description).toContain('This is the first paragraph');
});
it('should handle SKILL.md without any frontmatter', () => {
const skillDir = join(testDir, 'no-frontmatter');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `# No Frontmatter Skill
This skill has no YAML frontmatter at all.
## Usage
Just use it directly.
`);
const result = parseSkillToCanonical(skillDir);
expect(result).not.toBeNull();
// Name should be derived from directory
expect(result?.name).toBe('no-frontmatter');
expect(result?.content).toContain('# No Frontmatter Skill');
});
it('should return null for non-existent skill directory', () => {
const result = parseSkillToCanonical(join(testDir, 'does-not-exist'));
expect(result).toBeNull();
});
it('should return null for directory without SKILL.md', () => {
const emptyDir = join(testDir, 'empty-dir');
mkdirSync(emptyDir, { recursive: true });
writeFileSync(join(emptyDir, 'README.md'), '# Not a skill');
const result = parseSkillToCanonical(emptyDir);
expect(result).toBeNull();
});
});
describe('parseSkillContentToCanonical', () => {
it('should parse content with Claude Code specific fields', () => {
const content = `---
name: claude-specific
description: Skill with Claude Code specific fields
model: opus
context: fork
disable-model-invocation: true
---
# Claude Specific Skill
Use with Claude Code for best results.
`;
const result = parseSkillContentToCanonical(content, '/path/to/skill', 'claude-code');
expect(result?.name).toBe('claude-specific');
expect(result?.agentFields?.model).toBe('opus');
expect(result?.agentFields?.context).toBe('fork');
expect(result?.agentFields?.['disable-model-invocation']).toBe(true);
expect(result?.sourceAgent).toBe('claude-code');
});
it('should parse content with Cursor specific fields', () => {
const content = `---
name: cursor-specific
description: Skill with Cursor specific fields
globs: "**/*.ts"
alwaysApply: true
---
# Cursor Specific Skill
Optimized for Cursor.
`;
const result = parseSkillContentToCanonical(content, '/path/to/skill', 'cursor');
expect(result?.name).toBe('cursor-specific');
expect(result?.agentFields?.globs).toBe('**/*.ts');
expect(result?.agentFields?.alwaysApply).toBe(true);
expect(result?.sourceAgent).toBe('cursor');
});
});
});
describe('E2E: Skill Translator - Translation', () => {
let testDir: string;
let testSkill: CrossAgentSkill;
beforeEach(() => {
testDir = createTestDir('skillkit-translate-');
testSkill = {
name: 'translation-test',
description: 'A skill designed for testing cross-agent translation',
content: `# Translation Test Skill
This skill is used to verify that translation works correctly across all supported agents.
## Features
- Cross-agent compatibility
- Frontmatter preservation
- Content integrity
## Usage
\`\`\`bash
skillkit read translation-test
\`\`\`
`,
frontmatter: {
name: 'translation-test',
description: 'A skill designed for testing cross-agent translation',
version: '1.0.0',
author: 'SkillKit E2E Tests',
tags: ['testing', 'translation'],
},
sourcePath: join(testDir, 'translation-test'),
sourceAgent: 'claude-code',
version: '1.0.0',
author: 'SkillKit E2E Tests',
tags: ['testing', 'translation'],
allowedTools: ['Read', 'Write', 'Bash'],
};
});
afterEach(() => {
cleanupTestDir(testDir);
});
describe('translateSkillToAgent', () => {
it.each(SUPPORTED_AGENTS)('should translate skill to %s format', (agent) => {
const result = translateSkillToAgent(testSkill, agent);
expect(result.success).toBe(true);
expect(result.targetAgent).toBe(agent);
expect(result.content).toBeTruthy();
expect(result.content).toContain('translation-test');
expect(typeof result.filename).toBe('string');
});
it('should preserve skill name and description across translations', () => {
for (const agent of SUPPORTED_AGENTS) {
const result = translateSkillToAgent(testSkill, agent);
expect(result.content).toContain('translation-test');
}
});
it('should add translation metadata when requested', () => {
const result = translateSkillToAgent(testSkill, 'cursor', { addMetadata: true });
expect(result.success).toBe(true);
expect(result.content).toContain('_translated-from: claude-code');
expect(result.content).toContain('_translated-at:');
});
it('should not add metadata by default', () => {
const result = translateSkillToAgent(testSkill, 'cursor');
expect(result.success).toBe(true);
expect(result.content).not.toContain('_translated-from');
});
it('should preserve Claude Code specific fields when translating back to Claude Code', () => {
const claudeSkill: CrossAgentSkill = {
...testSkill,
agentFields: {
model: 'opus',
context: 'fork',
'disable-model-invocation': true,
},
};
const result = translateSkillToAgent(claudeSkill, 'claude-code');
expect(result.success).toBe(true);
expect(result.content).toContain('model: opus');
expect(result.content).toContain('context: fork');
expect(result.content).toContain('disable-model-invocation: true');
});
it('should report incompatible features when translating hooks to non-Claude agents', () => {
const skillWithHooks: CrossAgentSkill = {
...testSkill,
agentFields: {
hooks: [{ type: 'PreToolUse', command: 'echo test' }],
},
};
const result = translateSkillToAgent(skillWithHooks, 'cursor');
expect(result.incompatible).toContain('hooks (only supported in Claude Code)');
});
});
describe('translateSkillToAll', () => {
it('should translate skill to all agents except source', () => {
const skillDir = join(testDir, 'all-agents-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `---
name: all-agents
description: Skill for all agents testing
version: "1.0.0"
---
# All Agents Skill
Universal skill content.
`);
const results = translateSkillToAll(skillDir, 'claude-code');
// Should have translations for all agents except source
expect(results.size).toBe(SUPPORTED_AGENTS.length - 1);
expect(results.has('claude-code')).toBe(false);
for (const agent of SUPPORTED_AGENTS) {
if (agent !== 'claude-code') {
expect(results.has(agent)).toBe(true);
const result = results.get(agent);
expect(result?.success).toBe(true);
}
}
});
it('should return empty map for non-existent skill', () => {
const results = translateSkillToAll(join(testDir, 'non-existent'));
expect(results.size).toBe(0);
});
});
});
describe('E2E: Skill Translator - Writing', () => {
let testDir: string;
beforeEach(() => {
testDir = createTestDir('skillkit-write-');
});
afterEach(() => {
cleanupTestDir(testDir);
});
describe('writeTranslatedSkill', () => {
it('should write translated skill to correct location', () => {
const translationResult = {
success: true,
content: `---
name: written-skill
description: A skill that was written to disk
---
# Written Skill
Content here.
`,
filename: 'SKILL.md',
targetDir: 'written-skill',
warnings: [],
incompatible: [],
targetAgent: 'claude-code' as const,
};
const writeResult = writeTranslatedSkill(translationResult, testDir);
expect(writeResult.success).toBe(true);
expect(existsSync(writeResult.path)).toBe(true);
const writtenContent = readFileSync(writeResult.path, 'utf-8');
expect(writtenContent).toContain('name: written-skill');
expect(writtenContent).toContain('# Written Skill');
});
it('should create nested directories as needed', () => {
const translationResult = {
success: true,
content: '---\nname: nested\n---\n# Content',
filename: 'SKILL.md',
targetDir: '.cursor/skills/deeply/nested/skill',
warnings: [],
incompatible: [],
targetAgent: 'cursor' as const,
};
const writeResult = writeTranslatedSkill(translationResult, testDir);
expect(writeResult.success).toBe(true);
expect(existsSync(join(testDir, '.cursor/skills/deeply/nested/skill/SKILL.md'))).toBe(true);
});
it('should handle failed translation results gracefully', () => {
const failedResult = {
success: false,
content: '',
filename: 'SKILL.md',
targetDir: 'failed-skill',
warnings: ['Translation failed'],
incompatible: [],
targetAgent: 'cursor' as const,
};
const writeResult = writeTranslatedSkill(failedResult, testDir);
expect(writeResult.success).toBe(false);
});
});
});
describe('E2E: Skill Translator - Config Generation', () => {
const testSkills = [
{ name: 'skill-alpha', description: 'First test skill', path: '/skills/alpha', location: 'project' as const, enabled: true },
{ name: 'skill-beta', description: 'Second test skill', path: '/skills/beta', location: 'project' as const, enabled: true },
{ name: 'skill-gamma', description: 'Third test skill', path: '/skills/gamma', location: 'global' as const, enabled: true },
{ name: 'skill-disabled', description: 'Disabled skill', path: '/skills/disabled', location: 'project' as const, enabled: false },
];
describe('generateSkillsConfig', () => {
it('should generate XML config for Claude Code', () => {
const config = generateSkillsConfig(testSkills, 'claude-code');
expect(config).toContain('<skills_system');
expect(config).toContain('<name>skill-alpha</name>');
expect(config).toContain('<name>skill-beta</name>');
expect(config).toContain('<name>skill-gamma</name>');
expect(config).not.toContain('skill-disabled');
expect(config).toContain('<description>First test skill</description>');
expect(config).toContain('skillkit read');
});
it('should generate MDC config for Cursor', () => {
const config = generateSkillsConfig(testSkills, 'cursor');
expect(config).toContain('---');
expect(config).toContain('description:');
expect(config).toContain('globs:');
expect(config).toContain('alwaysApply: true');
expect(config).toContain('**skill-alpha**');
expect(config).toContain('**skill-beta**');
expect(config).not.toContain('skill-disabled');
});
it('should generate Markdown table config for Codex', () => {
const config = generateSkillsConfig(testSkills, 'codex');
expect(config).toContain('| Skill | Description | Command |');
expect(config).toContain('| skill-alpha |');
expect(config).toContain('| skill-beta |');
expect(config).toContain('First test skill');
expect(config).not.toContain('skill-disabled');
});
it('should generate JSON config for Gemini CLI', () => {
const config = generateSkillsConfig(testSkills, 'gemini-cli');
expect(config).toContain('```json');
expect(config).toContain('"name": "skill-alpha"');
expect(config).toContain('"name": "skill-beta"');
expect(config).toContain('"description": "First test skill"');
expect(config).not.toContain('skill-disabled');
});
it('should generate Markdown config for Windsurf', () => {
const config = generateSkillsConfig(testSkills, 'windsurf');
expect(config).toContain('### skill-alpha');
expect(config).toContain('### skill-beta');
expect(config).toContain('**Invoke:**');
expect(config).toContain('`skillkit read skill-alpha`');
expect(config).not.toContain('skill-disabled');
});
it('should generate XML config for Roo', () => {
const config = generateSkillsConfig(testSkills, 'roo');
expect(config).toContain('<skills_system');
expect(config).toContain('<name>skill-alpha</name>');
});
it('should generate Markdown config for Trae', () => {
const config = generateSkillsConfig(testSkills, 'trae');
expect(config).toContain('### skill-alpha');
expect(config).toContain('### skill-beta');
});
it('should generate Markdown config for GitHub Copilot', () => {
const config = generateSkillsConfig(testSkills, 'github-copilot');
expect(config).toContain('### skill-alpha');
expect(config).toContain('### skill-beta');
});
it('should return empty string when no skills are enabled', () => {
const disabledOnlySkills = [
{ name: 'disabled-1', description: 'Disabled', path: '/d1', location: 'project' as const, enabled: false },
{ name: 'disabled-2', description: 'Also disabled', path: '/d2', location: 'project' as const, enabled: false },
];
const config = generateSkillsConfig(disabledOnlySkills, 'claude-code');
expect(config).toBe('');
});
it('should exclude disabled skills from all agent configs', () => {
for (const agent of SUPPORTED_AGENTS) {
const config = generateSkillsConfig(testSkills, agent);
expect(config).not.toContain('skill-disabled');
}
});
});
});
describe('E2E: Skill Translator - Utility Functions', () => {
describe('getAgentSkillsDir', () => {
it.each(SUPPORTED_AGENTS)('should return valid skills directory for %s', (agent) => {
const dir = getAgentSkillsDir(agent);
expect(typeof dir).toBe('string');
expect(dir.length).toBeGreaterThan(0);
});
it('should return correct paths for major agents', () => {
expect(getAgentSkillsDir('claude-code')).toBe('.claude/skills');
expect(getAgentSkillsDir('cursor')).toBe('.cursor/skills');
expect(getAgentSkillsDir('windsurf')).toBe('.windsurf/skills');
expect(getAgentSkillsDir('github-copilot')).toBe('.github/skills');
expect(getAgentSkillsDir('codex')).toBe('.codex/skills');
});
});
describe('getAgentConfigFile', () => {
it.each(SUPPORTED_AGENTS)('should return valid config file for %s', (agent) => {
const file = getAgentConfigFile(agent);
expect(typeof file).toBe('string');
expect(file.length).toBeGreaterThan(0);
});
it('should return correct config files for major agents', () => {
expect(getAgentConfigFile('claude-code')).toBe('CLAUDE.md');
expect(getAgentConfigFile('cursor')).toBe('.cursor/rules/skills.mdc');
expect(getAgentConfigFile('windsurf')).toBe('.windsurf/rules/skills.md');
expect(getAgentConfigFile('github-copilot')).toBe('.github/copilot-instructions.md');
});
});
describe('AGENT_SKILL_FORMATS', () => {
it('should have configuration for all supported agents', () => {
for (const agent of SUPPORTED_AGENTS) {
expect(AGENT_SKILL_FORMATS[agent]).toBeDefined();
expect(AGENT_SKILL_FORMATS[agent].skillsDir).toBeTruthy();
expect(AGENT_SKILL_FORMATS[agent].configFile).toBeTruthy();
expect(AGENT_SKILL_FORMATS[agent].invokeCommand).toBe('skillkit read');
}
});
it('should have correct config formats for each agent', () => {
expect(AGENT_SKILL_FORMATS['claude-code'].configFormat).toBe('xml');
expect(AGENT_SKILL_FORMATS.cursor.configFormat).toBe('mdc');
expect(AGENT_SKILL_FORMATS.windsurf.configFormat).toBe('markdown');
expect(AGENT_SKILL_FORMATS.codex.configFormat).toBe('markdown-table');
expect(AGENT_SKILL_FORMATS['gemini-cli'].configFormat).toBe('json');
expect(AGENT_SKILL_FORMATS['github-copilot'].configFormat).toBe('markdown');
expect(AGENT_SKILL_FORMATS.trae.configFormat).toBe('markdown');
expect(AGENT_SKILL_FORMATS.roo.configFormat).toBe('xml');
});
});
});
describe('E2E: Skill Translator - Complete Workflow', () => {
let testDir: string;
beforeEach(() => {
testDir = createTestDir('skillkit-workflow-');
});
afterEach(() => {
cleanupTestDir(testDir);
});
it('should complete full translation workflow from Claude Code to all agents', () => {
// Create a Claude Code skill
const skillDir = join(testDir, 'workflow-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `---
name: workflow-skill
description: Complete workflow test skill
version: "1.0.0"
author: E2E Test Suite
tags:
- workflow
- testing
allowed-tools: Read, Write
---
# Workflow Test Skill
This skill tests the complete translation workflow.
## Instructions
1. Parse the SKILL.md file
2. Translate to target agent format
3. Write the translated skill
4. Generate config
## Usage
Use \`skillkit read workflow-skill\` to load this skill.
`);
// Step 1: Parse to canonical format
const canonicalSkill = parseSkillToCanonical(skillDir);
expect(canonicalSkill).not.toBeNull();
expect(canonicalSkill?.name).toBe('workflow-skill');
// Step 2: Translate to all agents
const translations = translateSkillToAll(skillDir, 'claude-code');
expect(translations.size).toBeGreaterThan(0);
// Step 3: Verify translations for key agents
const cursorTranslation = translations.get('cursor');
expect(cursorTranslation?.success).toBe(true);
expect(cursorTranslation?.content).toContain('workflow-skill');
const windsurfTranslation = translations.get('windsurf');
expect(windsurfTranslation?.success).toBe(true);
expect(windsurfTranslation?.content).toContain('workflow-skill');
const copilotTranslation = translations.get('github-copilot');
expect(copilotTranslation?.success).toBe(true);
expect(copilotTranslation?.content).toContain('workflow-skill');
// Step 4: Write a translation to disk
const outputDir = join(testDir, 'output');
mkdirSync(outputDir, { recursive: true });
if (cursorTranslation) {
const writeResult = writeTranslatedSkill(cursorTranslation, outputDir);
expect(writeResult.success).toBe(true);
expect(existsSync(writeResult.path)).toBe(true);
}
// Step 5: Generate config for installed skills
const installedSkills = [
{ name: 'workflow-skill', description: 'Complete workflow test skill', path: skillDir, location: 'project' as const, enabled: true },
];
const claudeConfig = generateSkillsConfig(installedSkills, 'claude-code');
expect(claudeConfig).toContain('<name>workflow-skill</name>');
const cursorConfig = generateSkillsConfig(installedSkills, 'cursor');
expect(cursorConfig).toContain('**workflow-skill**');
});
it('should handle skill with agent-specific features during translation', () => {
// Create a CrossAgentSkill directly with hooks in agentFields
// This is more reliable than parsing from YAML
const skillWithHooks: CrossAgentSkill = {
name: 'agent-specific',
description: 'Skill with agent-specific features',
content: '# Agent Specific Skill\n\nThis skill has Claude Code specific features.',
frontmatter: { name: 'agent-specific', description: 'Skill with agent-specific features' },
sourcePath: join(testDir, 'agent-specific'),
sourceAgent: 'claude-code',
agentFields: {
model: 'opus',
context: 'fork',
hooks: [
{ type: 'PreToolUse', command: 'echo "Before tool use"' },
{ type: 'PostToolUse', command: 'echo "After tool use"' },
],
},
};
// Translate to Claude Code (should preserve features)
const claudeResult = translateSkillToAgent(skillWithHooks, 'claude-code');
expect(claudeResult.success).toBe(true);
expect(claudeResult.incompatible).toHaveLength(0);
// Translate to Cursor (should report incompatible features)
const cursorResult = translateSkillToAgent(skillWithHooks, 'cursor');
expect(cursorResult.success).toBe(true);
// Hooks are not supported in Cursor
expect(cursorResult.incompatible.some(i => i.includes('hooks'))).toBe(true);
});
it('should maintain content integrity across multiple translations', () => {
const originalContent = `## Important Section
This content must be preserved exactly.
\`\`\`typescript
const important = "code";
console.log(important);
\`\`\`
### Subsection
- Bullet point 1
- Bullet point 2
- Bullet point 3
`;
const skillDir = join(testDir, 'content-integrity');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `---
name: content-integrity
description: Tests content preservation
---
${originalContent}`);
const canonicalSkill = parseSkillToCanonical(skillDir);
expect(canonicalSkill).not.toBeNull();
// Verify content is preserved in translations
for (const agent of ['cursor', 'windsurf', 'github-copilot', 'codex'] as const) {
const result = translateSkillToAgent(canonicalSkill!, agent);
expect(result.success).toBe(true);
expect(result.content).toContain('## Important Section');
expect(result.content).toContain('const important = "code"');
expect(result.content).toContain('- Bullet point 1');
}
});
});
+7
View File
@@ -1,4 +1,5 @@
import { defineConfig } from 'vitest/config';
import { resolve } from 'node:path';
export default defineConfig({
test: {
@@ -19,4 +20,10 @@ export default defineConfig({
},
},
},
resolve: {
alias: {
'@skillkit/core': resolve(__dirname, '../packages/core/src/index.ts'),
'@skillkit/agents': resolve(__dirname, '../packages/agents/src/index.ts'),
},
},
});
+109 -1823
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "skillkit-monorepo",
"version": "1.6.1",
"version": "1.6.4",
"private": true,
"description": "Universal skills loader for AI coding agents - Monorepo",
"type": "module",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/agents",
"version": "1.6.1",
"version": "1.6.4",
"description": "Agent adapters for SkillKit - supports 17+ AI coding agents",
"type": "module",
"main": "./dist/index.js",
@@ -21,7 +21,7 @@
"test": "vitest run"
},
"dependencies": {
"@skillkit/core": "^1.6.0",
"@skillkit/core": "workspace:*",
"minimatch": "^9.0.0"
},
"devDependencies": {
@@ -33,7 +33,7 @@ describe('ClawdbotAdapter', () => {
});
it('should have correct skillsDir', () => {
expect(adapter.skillsDir).toBe('skills');
expect(adapter.skillsDir).toBe('.clawdbot/skills');
});
it('should have correct configFile', () => {
+8 -5
View File
@@ -4,12 +4,15 @@ import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.amp;
export class AmpAdapter implements AgentAdapter {
readonly type: AgentType = 'amp';
readonly name = 'Amp';
readonly skillsDir = '.agents/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
@@ -66,9 +69,9 @@ ${skillsXml}
}
async isDetected(): Promise<boolean> {
const projectAgents = join(process.cwd(), '.agents');
const globalAgents = join(homedir(), '.config', 'agents');
const projectAmp = join(process.cwd(), '.amp');
const globalAmp = join(homedir(), '.amp');
return existsSync(projectAgents) || existsSync(globalAgents);
return existsSync(projectAmp) || existsSync(globalAmp);
}
}
+5 -2
View File
@@ -3,12 +3,15 @@ import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.antigravity;
export class AntigravityAdapter implements AgentAdapter {
readonly type: AgentType = 'antigravity';
readonly name = 'Antigravity';
readonly skillsDir = '.antigravity/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
+5 -2
View File
@@ -4,12 +4,15 @@ import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG['claude-code'];
export class ClaudeCodeAdapter implements AgentAdapter {
readonly type: AgentType = 'claude-code';
readonly name = 'Claude Code';
readonly skillsDir = '.claude/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
+5 -2
View File
@@ -4,12 +4,15 @@ import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.clawdbot;
export class ClawdbotAdapter implements AgentAdapter {
readonly type: AgentType = 'clawdbot';
readonly name = 'Clawdbot';
readonly skillsDir = 'skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
+5 -2
View File
@@ -3,12 +3,15 @@ import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.codex;
export class CodexAdapter implements AgentAdapter {
readonly type: AgentType = 'codex';
readonly name = 'OpenAI Codex CLI';
readonly skillsDir = '.codex/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
+19 -5
View File
@@ -1,14 +1,18 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.cursor;
export class CursorAdapter implements AgentAdapter {
readonly type: AgentType = 'cursor';
readonly name = 'Cursor';
readonly skillsDir = '.cursor/skills';
readonly configFile = '.cursorrules';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
@@ -23,7 +27,12 @@ export class CursorAdapter implements AgentAdapter {
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `# Skills System
return `---
description: SkillKit skills integration - provides specialized capabilities and domain knowledge
globs: "**/*"
alwaysApply: true
---
# Skills System
You have access to specialized skills that can help complete tasks. Use the skillkit CLI to load skill instructions when needed.
@@ -63,9 +72,14 @@ ${skillsXml}
}
async isDetected(): Promise<boolean> {
const cursorRules = join(process.cwd(), '.cursorrules');
const cursorDir = join(process.cwd(), '.cursor');
const cursorRulesDir = join(process.cwd(), '.cursor', 'rules');
// Legacy .cursorrules file (deprecated but still supported)
const cursorRulesFile = join(process.cwd(), '.cursorrules');
// Global Cursor config
const globalCursor = join(homedir(), '.cursor');
return existsSync(cursorRules) || existsSync(cursorDir);
return existsSync(cursorDir) || existsSync(cursorRulesDir) ||
existsSync(cursorRulesFile) || existsSync(globalCursor);
}
}
+5 -2
View File
@@ -4,12 +4,15 @@ import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.droid;
export class DroidAdapter implements AgentAdapter {
readonly type: AgentType = 'droid';
readonly name = 'Droid (Factory)';
readonly skillsDir = '.factory/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
+6 -3
View File
@@ -3,12 +3,15 @@ import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG['gemini-cli'];
export class GeminiCliAdapter implements AgentAdapter {
readonly type: AgentType = 'gemini-cli';
readonly name = 'Gemini CLI';
readonly skillsDir = '.gemini/skills';
readonly configFile = 'GEMINI.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
@@ -64,7 +67,7 @@ ${JSON.stringify(skillsJson, null, 2)}
}
if (skillNames.length === 0) {
const headerRegex = /^### ([a-z0-9-]+)$/gm;
const headerRegex = /^###\s+(.+?)\s*$/gm;
let match;
while ((match = headerRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
+27 -28
View File
@@ -2,14 +2,16 @@ import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG['github-copilot'];
export class GitHubCopilotAdapter implements AgentAdapter {
readonly type: AgentType = 'github-copilot';
readonly name = 'GitHub Copilot';
readonly skillsDir = '.github/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
@@ -18,43 +20,38 @@ export class GitHubCopilotAdapter implements AgentAdapter {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
const skillsList = enabledSkills
.map(s => `### ${s.name}\n\n${s.description}\n\n**Invoke:** \`skillkit read ${s.name}\``)
.join('\n\n');
return `<skills_system priority="1">
return `# Skills System
You have access to specialized skills that can help complete tasks.
Skills provide domain-specific knowledge and step-by-step instructions.
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
${skillsList}
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
## How to Use Skills
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
When a task matches a skill's description, load it using the terminal:
<available_skills>
\`\`\`bash
skillkit read <skill-name>
\`\`\`
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
The skill content will load with detailed instructions.
Each skill is self-contained with its own resources.
`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
const headerRegex = /^###\s+(.+?)\s*$/gm;
let match;
while ((match = skillRegex.exec(content)) !== null) {
while ((match = headerRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
@@ -66,9 +63,11 @@ ${skillsXml}
}
async isDetected(): Promise<boolean> {
const projectGithub = join(process.cwd(), '.github', 'skills');
const copilotInstructions = join(process.cwd(), '.github', 'copilot-instructions.md');
const githubInstructions = join(process.cwd(), '.github', 'instructions');
const globalCopilot = join(homedir(), '.copilot');
return existsSync(projectGithub) || existsSync(globalCopilot);
return existsSync(copilotInstructions) ||
existsSync(githubInstructions) || existsSync(globalCopilot);
}
}
+5 -2
View File
@@ -4,12 +4,15 @@ import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.goose;
export class GooseAdapter implements AgentAdapter {
readonly type: AgentType = 'goose';
readonly name = 'Goose';
readonly skillsDir = '.goose/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
+2 -7
View File
@@ -99,10 +99,5 @@ export async function detectAgent(): Promise<AgentType> {
return 'universal';
}
export function getSkillsDir(type: AgentType): string {
return adapters[type].skillsDir;
}
export function getConfigFile(type: AgentType): string {
return adapters[type].configFile;
}
// getSkillsDir and getConfigFile are now re-exported from @skillkit/core above
// This ensures a single source of truth for agent configurations
+7 -3
View File
@@ -4,12 +4,15 @@ import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.kilo;
export class KiloAdapter implements AgentAdapter {
readonly type: AgentType = 'kilo';
readonly name = 'Kilo Code';
readonly skillsDir = '.kilocode/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
@@ -68,7 +71,8 @@ ${skillsXml}
async isDetected(): Promise<boolean> {
const projectKilo = join(process.cwd(), '.kilocode');
const globalKilo = join(homedir(), '.kilocode');
const kiloModes = join(process.cwd(), '.kilocode', 'modes');
return existsSync(projectKilo) || existsSync(globalKilo);
return existsSync(projectKilo) || existsSync(globalKilo) || existsSync(kiloModes);
}
}
+5 -2
View File
@@ -4,12 +4,15 @@ import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG['kiro-cli'];
export class KiroCliAdapter implements AgentAdapter {
readonly type: AgentType = 'kiro-cli';
readonly name = 'Kiro CLI';
readonly skillsDir = '.kiro/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
+9 -4
View File
@@ -4,12 +4,15 @@ import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.opencode;
export class OpenCodeAdapter implements AgentAdapter {
readonly type: AgentType = 'opencode';
readonly name = 'OpenCode';
readonly skillsDir = '.opencode/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
@@ -60,8 +63,10 @@ This loads the skill's instructions into context.
async isDetected(): Promise<boolean> {
const opencodeDir = join(process.cwd(), '.opencode');
const globalOpencode = join(homedir(), '.opencode');
const globalOpencode = join(homedir(), '.config', 'opencode');
const opencodeJson = join(process.cwd(), 'opencode.json');
return existsSync(opencodeDir) || existsSync(globalOpencode);
return existsSync(opencodeDir) || existsSync(globalOpencode) ||
existsSync(opencodeJson);
}
}
+7 -3
View File
@@ -4,12 +4,15 @@ import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.roo;
export class RooAdapter implements AgentAdapter {
readonly type: AgentType = 'roo';
readonly name = 'Roo Code';
readonly skillsDir = '.roo/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
@@ -68,7 +71,8 @@ ${skillsXml}
async isDetected(): Promise<boolean> {
const projectRoo = join(process.cwd(), '.roo');
const globalRoo = join(homedir(), '.roo');
const rooModes = join(process.cwd(), '.roo', 'modes');
return existsSync(projectRoo) || existsSync(globalRoo);
return existsSync(projectRoo) || existsSync(globalRoo) || existsSync(rooModes);
}
}
+29 -27
View File
@@ -2,14 +2,16 @@ import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.trae;
export class TraeAdapter implements AgentAdapter {
readonly type: AgentType = 'trae';
readonly name = 'Trae';
readonly skillsDir = '.trae/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
@@ -18,43 +20,42 @@ export class TraeAdapter implements AgentAdapter {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
const skillsList = enabledSkills
.map(s => `### ${s.name}\n\n${s.description}\n\n**Invoke:** \`skillkit read ${s.name}\``)
.join('\n\n');
return `<skills_system priority="1">
return `---
alwaysApply: true
description: SkillKit skills integration for Trae
globs: ["**/*"]
---
# Skills System
You have access to specialized skills that can help complete tasks.
When a task matches a skill's description, load it using the skillkit CLI.
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
${skillsList}
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
## How to Use Skills
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
When a task matches a skill's description, load it:
<available_skills>
\`\`\`bash
skillkit read <skill-name>
\`\`\`
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
Skills provide detailed instructions for completing complex tasks.
`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
const headerRegex = /^###\s+(.+?)\s*$/gm;
let match;
while ((match = skillRegex.exec(content)) !== null) {
while ((match = headerRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
@@ -67,8 +68,9 @@ ${skillsXml}
async isDetected(): Promise<boolean> {
const projectTrae = join(process.cwd(), '.trae');
const traeRulesDir = join(process.cwd(), '.trae', 'rules');
const globalTrae = join(homedir(), '.trae');
return existsSync(projectTrae) || existsSync(globalTrae);
return existsSync(projectTrae) || existsSync(traeRulesDir) || existsSync(globalTrae);
}
}
+5 -2
View File
@@ -3,12 +3,15 @@ import { join } from 'node:path';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.universal;
export class UniversalAdapter implements AgentAdapter {
readonly type: AgentType = 'universal';
readonly name = 'Universal (Any Agent)';
readonly skillsDir = '.agent/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
+30 -27
View File
@@ -2,14 +2,16 @@ import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
import { AGENT_CONFIG } from '@skillkit/core';
const config = AGENT_CONFIG.windsurf;
export class WindsurfAdapter implements AgentAdapter {
readonly type: AgentType = 'windsurf';
readonly name = 'Windsurf';
readonly skillsDir = '.windsurf/skills';
readonly configFile = 'AGENTS.md';
readonly skillsDir = config.skillsDir;
readonly configFile = config.configFile;
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
@@ -18,43 +20,42 @@ export class WindsurfAdapter implements AgentAdapter {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
const skillsList = enabledSkills
.map(s => `### ${s.name}\n\n${s.description}\n\n**Invoke:** \`skillkit read ${s.name}\``)
.join('\n\n');
return `<skills_system priority="1">
return `---
name: "skillkit-skills"
mode: "model-decision"
---
# Skills System
You have access to specialized skills that can help complete tasks.
When a task matches a skill's description, load it using the skillkit CLI.
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
${skillsList}
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
## How to Use Skills
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
When a task matches a skill's description, load it:
<available_skills>
\`\`\`bash
skillkit read <skill-name>
\`\`\`
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
Skills provide detailed instructions for completing complex tasks.
Each skill is self-contained with its own resources.
`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
const headerRegex = /^###\s+(.+?)\s*$/gm;
let match;
while ((match = skillRegex.exec(content)) !== null) {
while ((match = headerRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
@@ -67,8 +68,10 @@ ${skillsXml}
async isDetected(): Promise<boolean> {
const projectWindsurf = join(process.cwd(), '.windsurf');
const projectRulesDir = join(process.cwd(), '.windsurf', 'rules');
const globalWindsurf = join(homedir(), '.codeium', 'windsurf');
return existsSync(projectWindsurf) || existsSync(globalWindsurf);
return existsSync(projectWindsurf) || existsSync(projectRulesDir) ||
existsSync(globalWindsurf);
}
}
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/cli",
"version": "1.6.1",
"version": "1.6.4",
"description": "CLI commands for SkillKit",
"type": "module",
"main": "./dist/index.js",
@@ -21,9 +21,9 @@
"test": "vitest run"
},
"dependencies": {
"@skillkit/core": "^1.6.0",
"@skillkit/agents": "^1.6.0",
"@skillkit/tui": "^1.6.0",
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"@skillkit/tui": "workspace:*",
"chalk": "^5.3.0",
"clipanion": "^4.0.0-rc.4",
"got": "^14.4.1",
+631
View File
@@ -0,0 +1,631 @@
/**
* Agent Command
*
* Manage custom AI sub-agents (e.g., .claude/agents/*.md)
*/
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import {
findAllAgents,
findAgent,
discoverAgents,
discoverAgentsFromPath,
validateAgent,
translateAgent,
getAgentTargetDirectory,
type CustomAgent,
type AgentType,
} from '@skillkit/core';
// Agent discovery uses root directories, not skill directories
export class AgentCommand extends Command {
static override paths = [['agent']];
static override usage = Command.Usage({
description: 'Manage custom AI sub-agents',
details: `
This command manages custom AI sub-agents that can be used with
Claude Code, Cursor, and other AI coding agents.
Agents are specialized personas (like architects, testers, reviewers)
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
`,
examples: [
['List all agents', '$0 agent list'],
['Show agent details', '$0 agent show architect'],
['Create new agent', '$0 agent create security-reviewer'],
['Translate to Cursor format', '$0 agent translate --to cursor'],
['Sync agents', '$0 agent sync --agent claude-code'],
],
});
async execute(): Promise<number> {
console.log(chalk.cyan('Agent management commands:\n'));
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 translate Translate agents between formats');
console.log(' agent sync Sync agents to target AI agent');
console.log(' agent validate [path] Validate agent definitions');
console.log();
console.log(chalk.dim('Run `skillkit agent <subcommand> --help` for more info'));
return 0;
}
}
export class AgentListCommand extends Command {
static override paths = [['agent', 'list'], ['agent', 'ls']];
static override usage = Command.Usage({
description: 'List all installed agents',
examples: [
['List all agents', '$0 agent list'],
['Show JSON output', '$0 agent list --json'],
['Show only project agents', '$0 agent list --project'],
],
});
json = Option.Boolean('--json,-j', false, {
description: 'Output as JSON',
});
project = Option.Boolean('--project,-p', false, {
description: 'Show only project agents',
});
global = Option.Boolean('--global,-g', false, {
description: 'Show only global agents',
});
async execute(): Promise<number> {
const searchDirs = [process.cwd()];
let agents = findAllAgents(searchDirs);
if (this.project) {
agents = agents.filter((a: CustomAgent) => a.location === 'project');
} else if (this.global) {
agents = agents.filter((a: CustomAgent) => a.location === 'global');
}
agents.sort((a: CustomAgent, b: CustomAgent) => {
if (a.location !== b.location) {
return a.location === 'project' ? -1 : 1;
}
return a.name.localeCompare(b.name);
});
if (this.json) {
console.log(JSON.stringify(agents.map((a: CustomAgent) => ({
name: a.name,
description: a.description,
path: a.path,
location: a.location,
enabled: a.enabled,
model: a.frontmatter.model,
permissionMode: a.frontmatter.permissionMode,
})), null, 2));
return 0;
}
if (agents.length === 0) {
console.log(chalk.yellow('No agents found'));
console.log(chalk.dim('Create an agent with: skillkit agent create <name>'));
return 0;
}
console.log(chalk.cyan(`Installed agents (${agents.length}):\n`));
const projectAgents = agents.filter((a: CustomAgent) => a.location === 'project');
const globalAgents = agents.filter((a: CustomAgent) => a.location === 'global');
if (projectAgents.length > 0) {
console.log(chalk.blue('Project agents:'));
for (const agent of projectAgents) {
printAgent(agent);
}
console.log();
}
if (globalAgents.length > 0) {
console.log(chalk.dim('Global agents:'));
for (const agent of globalAgents) {
printAgent(agent);
}
console.log();
}
console.log(
chalk.dim(`${projectAgents.length} project, ${globalAgents.length} global`)
);
return 0;
}
}
export class AgentShowCommand extends Command {
static override paths = [['agent', 'show'], ['agent', 'info']];
static override usage = Command.Usage({
description: 'Show details for a specific agent',
examples: [
['Show agent details', '$0 agent show architect'],
],
});
name = Option.String({ required: true });
async execute(): Promise<number> {
const searchDirs = [process.cwd()];
const agent = findAgent(this.name, searchDirs);
if (!agent) {
console.log(chalk.red(`Agent not found: ${this.name}`));
return 1;
}
console.log(chalk.cyan(`Agent: ${agent.name}\n`));
console.log(`${chalk.dim('Description:')} ${agent.description}`);
console.log(`${chalk.dim('Location:')} ${agent.location} (${agent.path})`);
console.log(`${chalk.dim('Enabled:')} ${agent.enabled ? chalk.green('yes') : chalk.red('no')}`);
const fm = agent.frontmatter;
if (fm.model) {
console.log(`${chalk.dim('Model:')} ${fm.model}`);
}
if (fm.permissionMode) {
console.log(`${chalk.dim('Permission Mode:')} ${fm.permissionMode}`);
}
if (fm.context) {
console.log(`${chalk.dim('Context:')} ${fm.context}`);
}
if (fm.disallowedTools && fm.disallowedTools.length > 0) {
console.log(`${chalk.dim('Disallowed Tools:')} ${fm.disallowedTools.join(', ')}`);
}
if (fm.skills && fm.skills.length > 0) {
console.log(`${chalk.dim('Skills:')} ${fm.skills.join(', ')}`);
}
if (fm.hooks && fm.hooks.length > 0) {
console.log(`${chalk.dim('Hooks:')} ${fm.hooks.length} defined`);
}
if (fm.tags && fm.tags.length > 0) {
console.log(`${chalk.dim('Tags:')} ${fm.tags.join(', ')}`);
}
if (fm.author) {
console.log(`${chalk.dim('Author:')} ${fm.author}`);
}
if (fm.version) {
console.log(`${chalk.dim('Version:')} ${fm.version}`);
}
console.log();
console.log(chalk.dim('Content preview:'));
console.log(chalk.dim('─'.repeat(40)));
const preview = agent.content.slice(0, 500);
console.log(preview + (agent.content.length > 500 ? '\n...' : ''));
return 0;
}
}
export class AgentCreateCommand extends Command {
static override paths = [['agent', 'create'], ['agent', 'new']];
static override usage = Command.Usage({
description: 'Create a new agent',
examples: [
['Create an agent', '$0 agent create security-reviewer'],
['Create with model', '$0 agent create architect --model opus'],
['Create globally', '$0 agent create my-agent --global'],
],
});
name = Option.String({ required: true });
model = Option.String('--model,-m', {
description: 'Model to use (opus, sonnet, haiku)',
});
description = Option.String('--description,-d', {
description: 'Agent description',
});
global = Option.Boolean('--global,-g', false, {
description: 'Create in global agents directory',
});
async execute(): Promise<number> {
// Validate agent name format
const namePattern = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (!namePattern.test(this.name)) {
console.log(chalk.red('Invalid agent name: must be lowercase alphanumeric with hyphens'));
console.log(chalk.dim('Examples: my-agent, code-reviewer, security-expert'));
return 1;
}
// Determine target directory
let targetDir: string;
if (this.global) {
targetDir = join(homedir(), '.claude', 'agents');
} else {
targetDir = join(process.cwd(), '.claude', 'agents');
}
// Create directory if needed
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
// Check if agent already exists
const agentPath = join(targetDir, `${this.name}.md`);
if (existsSync(agentPath)) {
console.log(chalk.red(`Agent already exists: ${agentPath}`));
return 1;
}
// Generate content
const description = this.description || `${this.name} agent`;
const content = generateAgentTemplate(this.name, description, this.model);
// Write file
writeFileSync(agentPath, content);
console.log(chalk.green(`Created agent: ${agentPath}`));
console.log();
console.log(chalk.dim('Edit the file to customize the agent system prompt.'));
console.log(chalk.dim(`Invoke with: @${this.name}`));
return 0;
}
}
export class AgentTranslateCommand extends Command {
static override paths = [['agent', 'translate']];
static override usage = Command.Usage({
description: 'Translate agents between AI coding agent formats',
details: `
Translates agent definitions between different AI coding agent formats.
Supports recursive translation for directories with multiple agents.
Use --source to specify a custom source directory with agents.
Use --recursive to scan all subdirectories for agents.
`,
examples: [
['Translate all to Cursor', '$0 agent translate --to cursor'],
['Translate specific agent', '$0 agent translate architect --to cursor'],
['Translate from source directory', '$0 agent translate --source ./my-agents --to cursor'],
['Recursive translation', '$0 agent translate --source ./skills --to cursor --recursive'],
['Dry run', '$0 agent translate --to cursor --dry-run'],
],
});
name = Option.String({ required: false });
to = Option.String('--to,-t', {
description: 'Target AI agent (claude-code, cursor, codex, etc.)',
required: true,
});
source = Option.String('--source,-s', {
description: 'Source directory or file to translate from',
});
output = Option.String('--output,-o', {
description: 'Output directory',
});
dryRun = Option.Boolean('--dry-run,-n', false, {
description: 'Show what would be done without writing files',
});
all = Option.Boolean('--all,-a', false, {
description: 'Translate all agents',
});
recursive = Option.Boolean('--recursive,-r', false, {
description: 'Recursively scan directories for agents',
});
async execute(): Promise<number> {
const searchDirs = [process.cwd()];
const targetAgent = this.to as AgentType;
// Get agents to translate
let agents: CustomAgent[];
if (this.source) {
// Translate from custom source path
const sourcePath = this.source.startsWith('/')
? this.source
: join(process.cwd(), this.source);
if (!existsSync(sourcePath)) {
console.log(chalk.red(`Source path not found: ${sourcePath}`));
return 1;
}
agents = discoverAgentsFromPath(sourcePath, this.recursive);
if (agents.length === 0) {
console.log(chalk.yellow(`No agents found in: ${sourcePath}`));
if (!this.recursive) {
console.log(chalk.dim('Tip: Use --recursive to scan subdirectories'));
}
return 0;
}
} else if (this.name) {
const agent = findAgent(this.name, searchDirs);
if (!agent) {
console.log(chalk.red(`Agent not found: ${this.name}`));
return 1;
}
agents = [agent];
} else if (this.all) {
agents = findAllAgents(searchDirs);
} else {
agents = discoverAgents(process.cwd());
}
if (agents.length === 0) {
console.log(chalk.yellow('No agents found to translate'));
return 0;
}
// Determine output directory
const outputDir = this.output || getAgentTargetDirectory(process.cwd(), targetAgent);
console.log(chalk.cyan(`Translating ${agents.length} agent(s) to ${targetAgent} format...\n`));
let successCount = 0;
let errorCount = 0;
for (const agent of agents) {
try {
const result = translateAgent(agent, targetAgent, { addMetadata: true });
if (!result.success) {
console.log(chalk.red(`✗ ${agent.name}: Translation failed`));
errorCount++;
continue;
}
const outputPath = join(outputDir, result.filename);
if (this.dryRun) {
console.log(chalk.blue(`Would write: ${outputPath}`));
if (result.warnings.length > 0) {
for (const warning of result.warnings) {
console.log(chalk.yellow(` ⚠ ${warning}`));
}
}
if (result.incompatible.length > 0) {
for (const incompat of result.incompatible) {
console.log(chalk.dim(` ○ ${incompat}`));
}
}
} else {
// Create directory if needed
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
writeFileSync(outputPath, result.content);
console.log(chalk.green(`✓ ${agent.name} → ${outputPath}`));
}
successCount++;
} catch (error) {
console.log(chalk.red(`✗ ${agent.name}: ${error instanceof Error ? error.message : 'Unknown error'}`));
errorCount++;
}
}
console.log();
if (this.dryRun) {
console.log(chalk.dim(`Would translate ${successCount} agent(s)`));
} else {
console.log(chalk.dim(`Translated ${successCount} agent(s)${errorCount > 0 ? `, ${errorCount} failed` : ''}`));
}
return errorCount > 0 ? 1 : 0;
}
}
export class AgentSyncCommand extends Command {
static override paths = [['agent', 'sync']];
static override usage = Command.Usage({
description: 'Sync agents to target AI coding agent',
examples: [
['Sync to Claude Code', '$0 agent sync --agent claude-code'],
['Sync to multiple agents', '$0 agent sync --agent claude-code,cursor'],
],
});
agent = Option.String('--agent,-a', {
description: 'Target AI agent(s) (comma-separated)',
});
async execute(): Promise<number> {
const searchDirs = [process.cwd()];
const agents = findAllAgents(searchDirs);
if (agents.length === 0) {
console.log(chalk.yellow('No agents found to sync'));
return 0;
}
const targetAgents = this.agent
? this.agent.split(',').map(a => a.trim() as AgentType)
: ['claude-code' as AgentType];
console.log(chalk.cyan(`Syncing ${agents.length} agent(s)...\n`));
for (const targetAgent of targetAgents) {
const outputDir = getAgentTargetDirectory(process.cwd(), targetAgent);
console.log(chalk.blue(`→ ${targetAgent} (${outputDir})`));
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
for (const agent of agents) {
const result = translateAgent(agent, targetAgent);
if (result.success) {
const outputPath = join(outputDir, result.filename);
writeFileSync(outputPath, result.content);
console.log(chalk.green(` ✓ ${agent.name}`));
} else {
console.log(chalk.red(` ✗ ${agent.name}`));
}
}
}
console.log();
console.log(chalk.dim('Sync complete'));
return 0;
}
}
export class AgentValidateCommand extends Command {
static override paths = [['agent', 'validate']];
static override usage = Command.Usage({
description: 'Validate agent definitions',
examples: [
['Validate specific agent', '$0 agent validate ./my-agent.md'],
['Validate all agents', '$0 agent validate --all'],
],
});
agentPath = Option.String({ required: false });
all = Option.Boolean('--all,-a', false, {
description: 'Validate all discovered agents',
});
async execute(): Promise<number> {
let hasErrors = false;
if (this.agentPath) {
// Validate specific path
const result = validateAgent(this.agentPath);
printValidationResult(this.agentPath, result);
hasErrors = !result.valid;
} else if (this.all) {
// Validate all agents
const searchDirs = [process.cwd()];
const agents = findAllAgents(searchDirs);
if (agents.length === 0) {
console.log(chalk.yellow('No agents found'));
return 0;
}
console.log(chalk.cyan(`Validating ${agents.length} agent(s)...\n`));
for (const agent of agents) {
const result = validateAgent(agent.path);
printValidationResult(agent.name, result);
if (!result.valid) hasErrors = true;
}
} else {
console.log(chalk.yellow('Specify a path or use --all to validate all agents'));
return 1;
}
return hasErrors ? 1 : 0;
}
}
// Helper functions
function printAgent(agent: CustomAgent): void {
const status = agent.enabled ? chalk.green('✓') : chalk.red('○');
const name = agent.enabled ? agent.name : chalk.dim(agent.name);
const model = agent.frontmatter.model ? chalk.blue(`[${agent.frontmatter.model}]`) : '';
const desc = chalk.dim(truncate(agent.description, 40));
console.log(` ${status} ${name} ${model}`);
if (agent.description) {
console.log(` ${desc}`);
}
}
function printValidationResult(
name: string,
result: { valid: boolean; errors: string[]; warnings: string[] }
): void {
if (result.valid) {
console.log(chalk.green(`✓ ${name}`));
for (const warning of result.warnings) {
console.log(chalk.yellow(` ⚠ ${warning}`));
}
} else {
console.log(chalk.red(`✗ ${name}`));
for (const error of result.errors) {
console.log(chalk.red(` • ${error}`));
}
for (const warning of result.warnings) {
console.log(chalk.yellow(` ⚠ ${warning}`));
}
}
}
function truncate(str: string, maxLen: number): string {
if (str.length <= maxLen) return str;
return str.slice(0, maxLen - 3) + '...';
}
function generateAgentTemplate(name: string, description: string, model?: string): string {
const lines: string[] = [];
lines.push('---');
lines.push(`name: ${name}`);
lines.push(`description: ${description}`);
if (model) {
lines.push(`model: ${model}`);
}
lines.push('# permissionMode: default');
lines.push('# disallowedTools: []');
lines.push('# skills: []');
lines.push('# context: fork');
lines.push('---');
lines.push('');
lines.push(`# ${formatAgentName(name)}`);
lines.push('');
lines.push('You are a specialized AI assistant.');
lines.push('');
lines.push('## Responsibilities');
lines.push('');
lines.push('- TODO: Define what this agent is responsible for');
lines.push('- TODO: Add specific tasks and behaviors');
lines.push('');
lines.push('## Guidelines');
lines.push('');
lines.push('- TODO: Add guidelines for how this agent should behave');
lines.push('- TODO: Define any constraints or preferences');
lines.push('');
return lines.join('\n');
}
function formatAgentName(name: string): string {
return name
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
+9
View File
@@ -31,3 +31,12 @@ export { PlanCommand } from './plan.js';
export { CommandCmd } from './command.js';
export { AICommand } from './ai.js';
export { AuditCommand } from './audit.js';
export {
AgentCommand,
AgentListCommand,
AgentShowCommand,
AgentCreateCommand,
AgentTranslateCommand,
AgentSyncCommand,
AgentValidateCommand,
} from './agent.js';
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/core",
"version": "1.6.1",
"version": "1.6.4",
"description": "Core functionality for SkillKit - skill discovery, parsing, and translation",
"type": "module",
"main": "./dist/index.js",
@@ -0,0 +1,432 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import {
AGENT_SKILL_FORMATS,
parseSkillToCanonical,
parseSkillContentToCanonical,
translateSkillToAgent,
translateSkillToAll,
writeTranslatedSkill,
generateSkillsConfig,
getAgentSkillsDir,
getAgentConfigFile,
supportsAutoDiscovery,
getAllSkillsDirs,
getGlobalSkillsDir,
type CrossAgentSkill,
type SkillTranslationOptions,
} from '../skill-translator.js';
describe('Skill Translator', () => {
let tempDir: string;
beforeEach(() => {
tempDir = join(tmpdir(), `skillkit-test-${Date.now()}`);
mkdirSync(tempDir, { recursive: true });
});
afterEach(() => {
if (existsSync(tempDir)) {
rmSync(tempDir, { recursive: true, force: true });
}
});
describe('AGENT_SKILL_FORMATS', () => {
it('should have configurations for all supported agents', () => {
const expectedAgents = [
'claude-code', 'cursor', 'codex', 'gemini-cli', 'opencode',
'antigravity', 'amp', 'clawdbot', 'droid', 'github-copilot',
'goose', 'kilo', 'kiro-cli', 'roo', 'trae', 'windsurf', 'universal',
];
for (const agent of expectedAgents) {
expect(AGENT_SKILL_FORMATS[agent as keyof typeof AGENT_SKILL_FORMATS]).toBeDefined();
}
});
it('should have valid skillsDir for each agent', () => {
for (const [agent, format] of Object.entries(AGENT_SKILL_FORMATS)) {
expect(format.skillsDir).toBeTruthy();
expect(typeof format.skillsDir).toBe('string');
}
});
it('should have valid configFile for each agent', () => {
for (const [agent, format] of Object.entries(AGENT_SKILL_FORMATS)) {
expect(format.configFile).toBeTruthy();
expect(typeof format.configFile).toBe('string');
}
});
it('should have correct Cursor MDC format', () => {
const cursor = AGENT_SKILL_FORMATS.cursor;
expect(cursor.skillsDir).toBe('.cursor/skills');
expect(cursor.configFile).toBe('.cursor/rules/skills.mdc');
expect(cursor.configFormat).toBe('mdc');
});
it('should have correct Windsurf format', () => {
const windsurf = AGENT_SKILL_FORMATS.windsurf;
expect(windsurf.skillsDir).toBe('.windsurf/skills');
expect(windsurf.configFile).toBe('.windsurf/rules/skills.md');
expect(windsurf.configFormat).toBe('markdown');
expect(windsurf.globalSkillsDir).toBe('~/.codeium/windsurf/skills');
});
it('should have correct GitHub Copilot format', () => {
const copilot = AGENT_SKILL_FORMATS['github-copilot'];
expect(copilot.skillsDir).toBe('.github/skills');
expect(copilot.configFile).toBe('.github/copilot-instructions.md');
expect(copilot.configFormat).toBe('markdown');
});
});
describe('parseSkillToCanonical', () => {
it('should parse a valid SKILL.md file', () => {
const skillDir = join(tempDir, 'test-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `---
name: test-skill
description: A test skill for unit testing
version: "1.0.0"
author: Test Author
tags:
- testing
- unit-test
---
# Test Skill
This is a test skill for unit testing purposes.
## Usage
Use this skill when you need to test something.
`);
const result = parseSkillToCanonical(skillDir);
expect(result).not.toBeNull();
expect(result?.name).toBe('test-skill');
expect(result?.description).toBe('A test skill for unit testing');
expect(result?.version).toBe('1.0.0');
expect(result?.author).toBe('Test Author');
expect(result?.tags).toEqual(['testing', 'unit-test']);
expect(result?.content).toContain('# Test Skill');
});
it('should return null for non-existent skill', () => {
const result = parseSkillToCanonical(join(tempDir, 'non-existent'));
expect(result).toBeNull();
});
it('should handle SKILL.md without frontmatter', () => {
const skillDir = join(tempDir, 'no-frontmatter-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `# Simple Skill
Just some content without frontmatter.
`);
const result = parseSkillToCanonical(skillDir);
expect(result).not.toBeNull();
// Without frontmatter, name is derived from directory name
expect(result?.name).toBe('no-frontmatter-skill');
});
it('should extract allowed-tools from frontmatter', () => {
const skillDir = join(tempDir, 'tools-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `---
name: tools-skill
description: Skill with allowed tools
allowed-tools: Read, Write, Bash
---
Content here.
`);
const result = parseSkillToCanonical(skillDir);
expect(result?.allowedTools).toEqual(['Read', 'Write', 'Bash']);
});
});
describe('parseSkillContentToCanonical', () => {
it('should parse skill content with full frontmatter', () => {
const content = `---
name: content-skill
description: Parsed from content
model: opus
context: fork
disable-model-invocation: true
---
# Content Skill
Instructions here.
`;
const result = parseSkillContentToCanonical(content, '/path/to/skill', 'claude-code');
expect(result?.name).toBe('content-skill');
expect(result?.description).toBe('Parsed from content');
expect(result?.agentFields?.['model']).toBe('opus');
expect(result?.agentFields?.['context']).toBe('fork');
expect(result?.agentFields?.['disable-model-invocation']).toBe(true);
expect(result?.sourceAgent).toBe('claude-code');
});
it('should extract description from content when not in frontmatter', () => {
const content = `---
name: no-desc
---
This is a longer paragraph that should be used as the description when none is provided in frontmatter.
## More Content
`;
const result = parseSkillContentToCanonical(content, '/path/to/skill');
expect(result?.description).toContain('This is a longer paragraph');
});
});
describe('translateSkillToAgent', () => {
const testSkill: CrossAgentSkill = {
name: 'translate-test',
description: 'A skill to test translation',
content: '# Translate Test\n\nTest content for translation.',
frontmatter: { name: 'translate-test', description: 'A skill to test translation' },
sourcePath: '/test/path',
sourceAgent: 'claude-code',
version: '1.0.0',
author: 'Test',
tags: ['test'],
};
it('should translate to Claude Code format', () => {
const result = translateSkillToAgent(testSkill, 'claude-code');
expect(result.success).toBe(true);
expect(result.content).toContain('name: translate-test');
expect(result.content).toContain('description: A skill to test translation');
expect(result.targetAgent).toBe('claude-code');
});
it('should translate to Cursor format', () => {
const result = translateSkillToAgent(testSkill, 'cursor');
expect(result.success).toBe(true);
expect(result.content).toContain('name: translate-test');
expect(result.targetAgent).toBe('cursor');
});
it('should translate to Windsurf format', () => {
const result = translateSkillToAgent(testSkill, 'windsurf');
expect(result.success).toBe(true);
expect(result.targetAgent).toBe('windsurf');
});
it('should include translation metadata when requested', () => {
const options: SkillTranslationOptions = { addMetadata: true };
const result = translateSkillToAgent(testSkill, 'cursor', options);
expect(result.content).toContain('_translated-from: claude-code');
expect(result.content).toContain('_translated-at:');
});
it('should preserve agent-specific fields for Claude Code', () => {
const skillWithFields: CrossAgentSkill = {
...testSkill,
agentFields: {
model: 'opus',
context: 'fork',
'disable-model-invocation': true,
},
};
const result = translateSkillToAgent(skillWithFields, 'claude-code');
expect(result.content).toContain('model: opus');
expect(result.content).toContain('context: fork');
expect(result.content).toContain('disable-model-invocation: true');
});
it('should report incompatible features', () => {
const skillWithHooks: CrossAgentSkill = {
...testSkill,
agentFields: {
hooks: [{ type: 'PreToolUse', command: 'echo test' }],
},
};
const result = translateSkillToAgent(skillWithHooks, 'cursor');
expect(result.incompatible).toContain('hooks (only supported in Claude Code)');
});
});
describe('translateSkillToAll', () => {
it('should translate skill to all supported agents', () => {
const skillDir = join(tempDir, 'all-agents-skill');
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), `---
name: all-agents
description: Skill for all agents
---
# All Agents Skill
`);
const results = translateSkillToAll(skillDir, 'claude-code');
expect(results.size).toBeGreaterThan(0);
// Should not include source agent
expect(results.has('claude-code')).toBe(false);
// Should include other agents
expect(results.has('cursor')).toBe(true);
expect(results.has('windsurf')).toBe(true);
});
it('should return empty map for non-existent skill', () => {
const results = translateSkillToAll(join(tempDir, 'non-existent'));
expect(results.size).toBe(0);
});
});
describe('writeTranslatedSkill', () => {
it('should write translated skill to disk', () => {
const result = {
success: true,
content: '---\nname: written-skill\n---\n# Content',
filename: 'SKILL.md',
targetDir: 'test-skill',
warnings: [],
incompatible: [],
targetAgent: 'claude-code' as const,
};
const writeResult = writeTranslatedSkill(result, tempDir);
expect(writeResult.success).toBe(true);
expect(existsSync(writeResult.path)).toBe(true);
});
it('should create nested directories', () => {
const result = {
success: true,
content: '---\nname: nested\n---\n# Content',
filename: 'SKILL.md',
targetDir: '.cursor/skills/nested-skill',
warnings: [],
incompatible: [],
targetAgent: 'cursor' as const,
};
const writeResult = writeTranslatedSkill(result, tempDir);
expect(writeResult.success).toBe(true);
expect(existsSync(join(tempDir, '.cursor/skills/nested-skill/SKILL.md'))).toBe(true);
});
});
describe('generateSkillsConfig', () => {
const testSkills = [
{ name: 'skill-one', description: 'First skill', path: '/path/one', location: 'project' as const, enabled: true },
{ name: 'skill-two', description: 'Second skill', path: '/path/two', location: 'project' as const, enabled: true },
{ name: 'disabled-skill', description: 'Disabled', path: '/path/disabled', location: 'project' as const, enabled: false },
];
it('should generate XML config for Claude Code', () => {
const config = generateSkillsConfig(testSkills, 'claude-code');
expect(config).toContain('<skills_system');
expect(config).toContain('<name>skill-one</name>');
expect(config).toContain('<name>skill-two</name>');
expect(config).not.toContain('disabled-skill');
});
it('should generate MDC config for Cursor', () => {
const config = generateSkillsConfig(testSkills, 'cursor');
expect(config).toContain('---');
expect(config).toContain('description:');
expect(config).toContain('globs:');
expect(config).toContain('alwaysApply: true');
expect(config).toContain('**skill-one**');
expect(config).toContain('**skill-two**');
});
it('should generate Markdown table config for Codex', () => {
const config = generateSkillsConfig(testSkills, 'codex');
expect(config).toContain('| Skill | Description | Command |');
expect(config).toContain('| skill-one |');
expect(config).toContain('| skill-two |');
});
it('should generate JSON config for Gemini CLI', () => {
const config = generateSkillsConfig(testSkills, 'gemini-cli');
expect(config).toContain('```json');
expect(config).toContain('"name": "skill-one"');
expect(config).toContain('"name": "skill-two"');
});
it('should generate Markdown config for Windsurf', () => {
const config = generateSkillsConfig(testSkills, 'windsurf');
expect(config).toContain('### skill-one');
expect(config).toContain('### skill-two');
expect(config).toContain('**Invoke:**');
});
it('should return empty string for no enabled skills', () => {
const disabledSkills = [
{ name: 'disabled', description: 'Disabled', path: '/path', location: 'project' as const, enabled: false },
];
const config = generateSkillsConfig(disabledSkills, 'claude-code');
expect(config).toBe('');
});
});
describe('utility functions', () => {
it('getAgentSkillsDir should return correct path', () => {
expect(getAgentSkillsDir('claude-code')).toBe('.claude/skills');
expect(getAgentSkillsDir('cursor')).toBe('.cursor/skills');
expect(getAgentSkillsDir('windsurf')).toBe('.windsurf/skills');
});
it('getAgentConfigFile should return correct path', () => {
expect(getAgentConfigFile('claude-code')).toBe('CLAUDE.md');
expect(getAgentConfigFile('cursor')).toBe('.cursor/rules/skills.mdc');
expect(getAgentConfigFile('github-copilot')).toBe('.github/copilot-instructions.md');
});
it('supportsAutoDiscovery should return true for all major agents', () => {
expect(supportsAutoDiscovery('claude-code')).toBe(true);
expect(supportsAutoDiscovery('cursor')).toBe(true);
expect(supportsAutoDiscovery('windsurf')).toBe(true);
});
it('getAllSkillsDirs should include alternative directories', () => {
const cursorDirs = getAllSkillsDirs('cursor');
expect(cursorDirs).toContain('.cursor/skills');
expect(cursorDirs).toContain('.cursor/commands');
const windsurfDirs = getAllSkillsDirs('windsurf');
expect(windsurfDirs).toContain('.windsurf/skills');
expect(windsurfDirs).toContain('.windsurf/workflows');
});
it('getGlobalSkillsDir should return correct global path', () => {
expect(getGlobalSkillsDir('claude-code')).toBe('~/.claude/skills');
expect(getGlobalSkillsDir('windsurf')).toBe('~/.codeium/windsurf/skills');
expect(getGlobalSkillsDir('opencode')).toBe('~/.config/opencode/skills');
expect(getGlobalSkillsDir('roo')).toBe('~/.roo/skills');
});
});
});
describe('Agent Adapter Integration', () => {
it('should have matching config formats between AGENT_SKILL_FORMATS and expected values', () => {
// Verify that the 2026 updates are consistent
expect(AGENT_SKILL_FORMATS.cursor.configFormat).toBe('mdc');
expect(AGENT_SKILL_FORMATS.windsurf.configFormat).toBe('markdown');
expect(AGENT_SKILL_FORMATS['github-copilot'].configFormat).toBe('markdown');
expect(AGENT_SKILL_FORMATS.trae.configFormat).toBe('markdown');
expect(AGENT_SKILL_FORMATS['claude-code'].configFormat).toBe('xml');
expect(AGENT_SKILL_FORMATS.codex.configFormat).toBe('markdown-table');
expect(AGENT_SKILL_FORMATS['gemini-cli'].configFormat).toBe('json');
});
it('should have valid invoke commands', () => {
for (const format of Object.values(AGENT_SKILL_FORMATS)) {
expect(format.invokeCommand).toBe('skillkit read');
}
});
});
+269
View File
@@ -0,0 +1,269 @@
/**
* Centralized Agent Configuration
*
* Single source of truth for all AI coding agent configurations.
* All modules should import from here instead of defining their own values.
*/
import type { AgentType } from './types.js';
/**
* Agent configuration for skills and config files
*/
export interface AgentDirectoryConfig {
/** Primary skills directory path */
skillsDir: string;
/** Config file that references skills */
configFile: string;
/** Alternative skills directories */
altSkillsDirs?: string[];
/** Global skills directory */
globalSkillsDir?: string;
/** Config format: xml, markdown, mdc, json, markdown-table */
configFormat: 'xml' | 'markdown' | 'mdc' | 'json' | 'markdown-table';
/** Whether agent uses YAML frontmatter in SKILL.md */
usesFrontmatter: boolean;
/** Agent-specific frontmatter fields */
frontmatterFields?: string[];
/** Whether agent supports skill auto-discovery */
supportsAutoDiscovery: boolean;
}
/**
* Centralized agent configurations
*
* This is the ONLY source of truth for agent paths and formats.
* Do not define these values elsewhere.
*/
export const AGENT_CONFIG: Record<AgentType, AgentDirectoryConfig> = {
// Claude Code - all Claude products use the same format
'claude-code': {
skillsDir: '.claude/skills',
configFile: 'CLAUDE.md',
globalSkillsDir: '~/.claude/skills',
configFormat: 'xml',
usesFrontmatter: true,
frontmatterFields: [
'name', 'description', 'allowed-tools', 'model', 'context',
'agent', 'disable-model-invocation', 'user-invocable', 'argument-hint',
],
supportsAutoDiscovery: true,
},
// Cursor - uses MDC format in .cursor/rules/
cursor: {
skillsDir: '.cursor/skills',
configFile: '.cursor/rules/skills.mdc',
altSkillsDirs: ['.cursor/commands'],
globalSkillsDir: '~/.cursor/skills',
configFormat: 'mdc',
usesFrontmatter: true,
frontmatterFields: ['description', 'globs', 'alwaysApply'],
supportsAutoDiscovery: true,
},
// Codex (OpenAI)
codex: {
skillsDir: '.codex/skills',
configFile: 'AGENTS.md',
globalSkillsDir: '~/.codex/skills',
configFormat: 'markdown-table',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Gemini CLI
'gemini-cli': {
skillsDir: '.gemini/skills',
configFile: 'GEMINI.md',
globalSkillsDir: '~/.gemini/skills',
configFormat: 'json',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// OpenCode
opencode: {
skillsDir: '.opencode/skills',
configFile: 'AGENTS.md',
altSkillsDirs: ['.opencode/agent'],
globalSkillsDir: '~/.config/opencode/skills',
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Antigravity
antigravity: {
skillsDir: '.antigravity/skills',
configFile: 'AGENTS.md',
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Amp - uses .amp/ directory
amp: {
skillsDir: '.amp/skills',
configFile: 'AGENTS.md',
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Clawdbot
clawdbot: {
skillsDir: '.clawdbot/skills',
configFile: 'AGENTS.md',
altSkillsDirs: ['skills'],
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Droid (Factory)
droid: {
skillsDir: '.factory/skills',
configFile: 'AGENTS.md',
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// GitHub Copilot
'github-copilot': {
skillsDir: '.github/skills',
configFile: '.github/copilot-instructions.md',
altSkillsDirs: ['.github/instructions'],
configFormat: 'markdown',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Goose
goose: {
skillsDir: '.goose/skills',
configFile: 'AGENTS.md',
globalSkillsDir: '~/.goose/skills',
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Kilo
kilo: {
skillsDir: '.kilocode/skills',
configFile: 'AGENTS.md',
altSkillsDirs: ['.kilocode/modes'],
globalSkillsDir: '~/.kilocode/skills',
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Kiro CLI
'kiro-cli': {
skillsDir: '.kiro/skills',
configFile: 'AGENTS.md',
globalSkillsDir: '~/.kiro/skills',
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Roo Code
roo: {
skillsDir: '.roo/skills',
configFile: 'AGENTS.md',
altSkillsDirs: ['.roo/modes'],
globalSkillsDir: '~/.roo/skills',
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Trae
trae: {
skillsDir: '.trae/skills',
configFile: '.trae/rules/project_rules.md',
altSkillsDirs: ['.trae/agent'],
configFormat: 'markdown',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Windsurf
windsurf: {
skillsDir: '.windsurf/skills',
configFile: '.windsurf/rules/skills.md',
altSkillsDirs: ['.windsurf/workflows'],
globalSkillsDir: '~/.codeium/windsurf/skills',
configFormat: 'markdown',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
// Universal - works with any agent
universal: {
skillsDir: 'skills',
configFile: 'AGENTS.md',
altSkillsDirs: ['.agent/skills', '.agents/skills'],
configFormat: 'xml',
usesFrontmatter: true,
supportsAutoDiscovery: true,
},
};
/**
* Get agent configuration
*/
export function getAgentDirectoryConfig(agent: AgentType): AgentDirectoryConfig {
return AGENT_CONFIG[agent];
}
/**
* Get skills directory for an agent
*/
export function getSkillsDir(agent: AgentType): string {
return AGENT_CONFIG[agent].skillsDir;
}
/**
* Get config file for an agent
*/
export function getConfigFile(agent: AgentType): string {
return AGENT_CONFIG[agent].configFile;
}
/**
* Get all skills directories for an agent (including alternatives)
*/
export function getAllSkillsDirs(agent: AgentType): string[] {
const config = AGENT_CONFIG[agent];
const dirs = [config.skillsDir];
if (config.altSkillsDirs) {
dirs.push(...config.altSkillsDirs);
}
return dirs;
}
/**
* Get global skills directory for an agent
*/
export function getGlobalSkillsDir(agent: AgentType): string | undefined {
return AGENT_CONFIG[agent].globalSkillsDir;
}
/**
* Check if agent supports auto-discovery
*/
export function supportsAutoDiscovery(agent: AgentType): boolean {
return AGENT_CONFIG[agent].supportsAutoDiscovery;
}
/**
* Get config format for an agent
*/
export function getConfigFormat(agent: AgentType): AgentDirectoryConfig['configFormat'] {
return AGENT_CONFIG[agent].configFormat;
}
@@ -0,0 +1,556 @@
/**
* Agent Discovery Tests
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import {
discoverAgents,
discoverAgentsForAgent,
discoverAgentsRecursive,
discoverAgentsFromPath,
findAllAgents,
findAgent,
getAgentsDirectory,
agentExists,
getAgentStats,
} from '../discovery.js';
describe('Agent Discovery', () => {
let testDir: string;
beforeEach(() => {
// Create a temporary test directory
testDir = join(tmpdir(), `agent-test-${Date.now()}`);
mkdirSync(testDir, { recursive: true });
});
afterEach(() => {
// Clean up
if (existsSync(testDir)) {
rmSync(testDir, { recursive: true, force: true });
}
});
describe('discoverAgents', () => {
it('should discover agents in .claude/agents directory', () => {
const agentsDir = join(testDir, '.claude', 'agents');
mkdirSync(agentsDir, { recursive: true });
writeFileSync(
join(agentsDir, 'test-agent.md'),
`---
name: test-agent
description: A test agent
---
Agent content here.`
);
const agents = discoverAgents(testDir);
expect(agents).toHaveLength(1);
expect(agents[0].name).toBe('test-agent');
expect(agents[0].description).toBe('A test agent');
expect(agents[0].location).toBe('project');
});
it('should discover multiple agents', () => {
const agentsDir = join(testDir, '.claude', 'agents');
mkdirSync(agentsDir, { recursive: true });
writeFileSync(
join(agentsDir, 'agent-one.md'),
`---
name: agent-one
description: First agent
---
Content.`
);
writeFileSync(
join(agentsDir, 'agent-two.md'),
`---
name: agent-two
description: Second agent
---
Content.`
);
const agents = discoverAgents(testDir);
expect(agents).toHaveLength(2);
const names = agents.map((a) => a.name);
expect(names).toContain('agent-one');
expect(names).toContain('agent-two');
});
it('should return empty array when no agents directory exists', () => {
const agents = discoverAgents(testDir);
expect(agents).toHaveLength(0);
});
it('should discover agents in alternative directories', () => {
const agentsDir = join(testDir, 'agents');
mkdirSync(agentsDir, { recursive: true });
writeFileSync(
join(agentsDir, 'my-agent.md'),
`---
name: my-agent
description: An agent in universal location
---
Content.`
);
const agents = discoverAgents(testDir);
expect(agents).toHaveLength(1);
expect(agents[0].name).toBe('my-agent');
});
});
describe('discoverAgentsForAgent', () => {
it('should discover agents for specific AI agent type', () => {
const claudeAgentsDir = join(testDir, '.claude', 'agents');
const cursorAgentsDir = join(testDir, '.cursor', 'agents');
mkdirSync(claudeAgentsDir, { recursive: true });
mkdirSync(cursorAgentsDir, { recursive: true });
writeFileSync(
join(claudeAgentsDir, 'claude-agent.md'),
`---
name: claude-agent
description: Claude specific
---
Content.`
);
writeFileSync(
join(cursorAgentsDir, 'cursor-agent.md'),
`---
name: cursor-agent
description: Cursor specific
---
Content.`
);
const claudeAgents = discoverAgentsForAgent(testDir, 'claude-code');
expect(claudeAgents).toHaveLength(1);
expect(claudeAgents[0].name).toBe('claude-agent');
const cursorAgents = discoverAgentsForAgent(testDir, 'cursor');
expect(cursorAgents).toHaveLength(1);
expect(cursorAgents[0].name).toBe('cursor-agent');
});
});
describe('findAllAgents', () => {
it('should find agents in multiple search directories', () => {
const dir1 = join(testDir, 'project1');
const dir2 = join(testDir, 'project2');
mkdirSync(join(dir1, '.claude', 'agents'), { recursive: true });
mkdirSync(join(dir2, '.claude', 'agents'), { recursive: true });
writeFileSync(
join(dir1, '.claude', 'agents', 'agent-a.md'),
`---
name: agent-a
description: Agent A
---
Content.`
);
writeFileSync(
join(dir2, '.claude', 'agents', 'agent-b.md'),
`---
name: agent-b
description: Agent B
---
Content.`
);
const agents = findAllAgents([dir1, dir2]);
expect(agents).toHaveLength(2);
const names = agents.map((a) => a.name);
expect(names).toContain('agent-a');
expect(names).toContain('agent-b');
});
it('should deduplicate agents by name', () => {
const dir1 = join(testDir, 'project1');
const dir2 = join(testDir, 'project2');
mkdirSync(join(dir1, '.claude', 'agents'), { recursive: true });
mkdirSync(join(dir2, '.claude', 'agents'), { recursive: true });
// Same agent name in both directories
writeFileSync(
join(dir1, '.claude', 'agents', 'shared-agent.md'),
`---
name: shared-agent
description: Shared agent (dir1)
---
Content.`
);
writeFileSync(
join(dir2, '.claude', 'agents', 'shared-agent.md'),
`---
name: shared-agent
description: Shared agent (dir2)
---
Content.`
);
const agents = findAllAgents([dir1, dir2]);
expect(agents).toHaveLength(1);
expect(agents[0].name).toBe('shared-agent');
});
});
describe('findAgent', () => {
it('should find a specific agent by name', () => {
const agentsDir = join(testDir, '.claude', 'agents');
mkdirSync(agentsDir, { recursive: true });
writeFileSync(
join(agentsDir, 'target-agent.md'),
`---
name: target-agent
description: The target agent
---
Content.`
);
writeFileSync(
join(agentsDir, 'other-agent.md'),
`---
name: other-agent
description: Another agent
---
Content.`
);
const agent = findAgent('target-agent', [testDir]);
expect(agent).not.toBeNull();
expect(agent?.name).toBe('target-agent');
expect(agent?.description).toBe('The target agent');
});
it('should return null when agent not found', () => {
const agentsDir = join(testDir, '.claude', 'agents');
mkdirSync(agentsDir, { recursive: true });
const agent = findAgent('non-existent', [testDir]);
expect(agent).toBeNull();
});
});
describe('getAgentsDirectory', () => {
it('should return correct directory for different agent types', () => {
expect(getAgentsDirectory(testDir, 'claude-code')).toBe(join(testDir, '.claude', 'agents'));
expect(getAgentsDirectory(testDir, 'cursor')).toBe(join(testDir, '.cursor', 'agents'));
expect(getAgentsDirectory(testDir, 'universal')).toBe(join(testDir, 'agents'));
});
});
describe('agentExists', () => {
it('should return true when agent exists', () => {
const agentsDir = join(testDir, '.claude', 'agents');
mkdirSync(agentsDir, { recursive: true });
writeFileSync(
join(agentsDir, 'existing-agent.md'),
`---
name: existing-agent
description: Exists
---
Content.`
);
expect(agentExists('existing-agent', [testDir])).toBe(true);
});
it('should return false when agent does not exist', () => {
expect(agentExists('non-existent', [testDir])).toBe(false);
});
});
describe('getAgentStats', () => {
it('should return correct stats', () => {
const agentsDir = join(testDir, '.claude', 'agents');
mkdirSync(agentsDir, { recursive: true });
writeFileSync(
join(agentsDir, 'agent-one.md'),
`---
name: agent-one
description: First
---
Content.`
);
writeFileSync(
join(agentsDir, 'agent-two.md'),
`---
name: agent-two
description: Second
---
Content.`
);
const stats = getAgentStats([testDir]);
expect(stats.total).toBe(2);
expect(stats.project).toBe(2);
expect(stats.global).toBe(0);
expect(stats.enabled).toBe(2);
expect(stats.disabled).toBe(0);
});
});
describe('discoverAgentsRecursive', () => {
it('should discover agents in nested directories', () => {
// Create nested structure like kubernetes-skills/claude-code/k8s-autoscaling
const rootDir = join(testDir, 'skills');
mkdirSync(join(rootDir, 'k8s-autoscaling'), { recursive: true });
mkdirSync(join(rootDir, 'k8s-security'), { recursive: true });
mkdirSync(join(rootDir, 'k8s-deploy'), { recursive: true });
writeFileSync(
join(rootDir, 'k8s-autoscaling', 'AGENT.md'),
`---
name: k8s-autoscaling
description: Kubernetes autoscaling agent
---
Autoscaling content.`
);
writeFileSync(
join(rootDir, 'k8s-security', 'AGENT.md'),
`---
name: k8s-security
description: Kubernetes security agent
---
Security content.`
);
writeFileSync(
join(rootDir, 'k8s-deploy', 'AGENT.md'),
`---
name: k8s-deploy
description: Kubernetes deployment agent
---
Deploy content.`
);
const agents = discoverAgentsRecursive(rootDir);
expect(agents).toHaveLength(3);
const names = agents.map((a) => a.name);
expect(names).toContain('k8s-autoscaling');
expect(names).toContain('k8s-security');
expect(names).toContain('k8s-deploy');
});
it('should discover deeply nested agents', () => {
const rootDir = join(testDir, 'deep-skills');
mkdirSync(join(rootDir, 'category1', 'subcategory', 'agent-deep'), { recursive: true });
writeFileSync(
join(rootDir, 'category1', 'subcategory', 'agent-deep', 'AGENT.md'),
`---
name: agent-deep
description: Deeply nested agent
---
Deep content.`
);
const agents = discoverAgentsRecursive(rootDir);
expect(agents).toHaveLength(1);
expect(agents[0].name).toBe('agent-deep');
});
it('should discover agents as markdown files', () => {
const rootDir = join(testDir, 'md-skills');
mkdirSync(join(rootDir, 'subdir'), { recursive: true });
writeFileSync(
join(rootDir, 'top-level-agent.md'),
`---
name: top-level-agent
description: Top level agent
---
Content.`
);
writeFileSync(
join(rootDir, 'subdir', 'nested-agent.md'),
`---
name: nested-agent
description: Nested agent
---
Content.`
);
const agents = discoverAgentsRecursive(rootDir);
expect(agents).toHaveLength(2);
const names = agents.map((a) => a.name);
expect(names).toContain('top-level-agent');
expect(names).toContain('nested-agent');
});
it('should skip hidden directories except standard agent paths', () => {
const rootDir = join(testDir, 'hidden-test');
mkdirSync(join(rootDir, '.hidden', 'agents'), { recursive: true });
mkdirSync(join(rootDir, '.claude', 'agents'), { recursive: true });
writeFileSync(
join(rootDir, '.hidden', 'agents', 'hidden-agent.md'),
`---
name: hidden-agent
description: Should be skipped
---
Content.`
);
writeFileSync(
join(rootDir, '.claude', 'agents', 'claude-agent.md'),
`---
name: claude-agent
description: Should be found
---
Content.`
);
const agents = discoverAgentsRecursive(rootDir);
expect(agents).toHaveLength(1);
expect(agents[0].name).toBe('claude-agent');
});
it('should return empty array for non-existent directory', () => {
const agents = discoverAgentsRecursive(join(testDir, 'non-existent'));
expect(agents).toHaveLength(0);
});
});
describe('discoverAgentsFromPath', () => {
it('should discover agent from single file', () => {
mkdirSync(testDir, { recursive: true });
writeFileSync(
join(testDir, 'single-agent.md'),
`---
name: single-agent
description: A single agent file
---
Content.`
);
const agents = discoverAgentsFromPath(join(testDir, 'single-agent.md'));
expect(agents).toHaveLength(1);
expect(agents[0].name).toBe('single-agent');
});
it('should discover agents from directory without recursive flag', () => {
const rootDir = join(testDir, 'flat-dir');
mkdirSync(rootDir, { recursive: true });
writeFileSync(
join(rootDir, 'agent-a.md'),
`---
name: agent-a
description: Agent A
---
Content.`
);
writeFileSync(
join(rootDir, 'agent-b.md'),
`---
name: agent-b
description: Agent B
---
Content.`
);
const agents = discoverAgentsFromPath(rootDir, false);
expect(agents).toHaveLength(2);
});
it('should discover agents from directory with recursive flag', () => {
const rootDir = join(testDir, 'nested-dir');
mkdirSync(join(rootDir, 'subdir'), { recursive: true });
writeFileSync(
join(rootDir, 'agent-top.md'),
`---
name: agent-top
description: Top agent
---
Content.`
);
writeFileSync(
join(rootDir, 'subdir', 'agent-nested.md'),
`---
name: agent-nested
description: Nested agent
---
Content.`
);
const agentsNonRecursive = discoverAgentsFromPath(rootDir, false);
expect(agentsNonRecursive).toHaveLength(1);
expect(agentsNonRecursive[0].name).toBe('agent-top');
const agentsRecursive = discoverAgentsFromPath(rootDir, true);
expect(agentsRecursive).toHaveLength(2);
const names = agentsRecursive.map((a) => a.name);
expect(names).toContain('agent-top');
expect(names).toContain('agent-nested');
});
it('should handle agent directory with AGENT.md', () => {
const agentDir = join(testDir, 'agent-dir');
mkdirSync(agentDir, { recursive: true });
writeFileSync(
join(agentDir, 'AGENT.md'),
`---
name: agent-dir
description: Directory-based agent
---
Content.`
);
const agents = discoverAgentsFromPath(agentDir);
expect(agents).toHaveLength(1);
expect(agents[0].name).toBe('agent-dir');
});
it('should return empty array for non-existent path', () => {
const agents = discoverAgentsFromPath(join(testDir, 'non-existent'));
expect(agents).toHaveLength(0);
});
it('should return empty array for non-markdown file', () => {
writeFileSync(join(testDir, 'not-agent.txt'), 'Not an agent');
const agents = discoverAgentsFromPath(join(testDir, 'not-agent.txt'));
expect(agents).toHaveLength(0);
});
});
});
@@ -0,0 +1,201 @@
/**
* Agent Parser Tests
*/
import { describe, it, expect } from 'vitest';
import {
extractAgentFrontmatter,
extractAgentContent,
toCanonicalAgent,
fromCanonicalAgent,
validateAgent,
} from '../parser.js';
import type { CustomAgent, CanonicalAgent, AgentFrontmatter } from '../types.js';
describe('Agent Parser', () => {
describe('extractAgentFrontmatter', () => {
it('should extract valid YAML frontmatter', () => {
const content = `---
name: test-agent
description: A test agent
model: opus
---
Agent content here.`;
const frontmatter = extractAgentFrontmatter(content);
expect(frontmatter).not.toBeNull();
expect(frontmatter?.name).toBe('test-agent');
expect(frontmatter?.description).toBe('A test agent');
expect(frontmatter?.model).toBe('opus');
});
it('should return null for content without frontmatter', () => {
const content = 'Just some content without frontmatter.';
const frontmatter = extractAgentFrontmatter(content);
expect(frontmatter).toBeNull();
});
it('should return null for invalid YAML', () => {
const content = `---
name: test-agent
invalid: yaml: structure: [broken
---
Content here.`;
const frontmatter = extractAgentFrontmatter(content);
expect(frontmatter).toBeNull();
});
it('should extract complex frontmatter with arrays', () => {
const content = `---
name: security-reviewer
description: Reviews code for security issues
disallowedTools:
- Bash
- Write
skills:
- code-review
- security
---
Content here.`;
const frontmatter = extractAgentFrontmatter(content);
expect(frontmatter?.name).toBe('security-reviewer');
expect(frontmatter?.disallowedTools).toEqual(['Bash', 'Write']);
expect(frontmatter?.skills).toEqual(['code-review', 'security']);
});
});
describe('extractAgentContent', () => {
it('should extract content after frontmatter', () => {
const content = `---
name: test-agent
description: A test agent
---
# Agent Instructions
This is the main content.`;
const extracted = extractAgentContent(content);
expect(extracted).toBe('# Agent Instructions\n\nThis is the main content.');
});
it('should return full content if no frontmatter', () => {
const content = 'Just content without frontmatter.';
const extracted = extractAgentContent(content);
expect(extracted).toBe('Just content without frontmatter.');
});
it('should handle empty content after frontmatter', () => {
const content = `---
name: test-agent
description: Empty agent
---`;
const extracted = extractAgentContent(content);
expect(extracted).toBe('');
});
});
describe('toCanonicalAgent', () => {
it('should convert CustomAgent to CanonicalAgent', () => {
const agent: CustomAgent = {
name: 'test-agent',
description: 'A test agent',
path: '/path/to/agent.md',
location: 'project',
frontmatter: {
name: 'test-agent',
description: 'A test agent',
model: 'opus',
permissionMode: 'default',
disallowedTools: ['Bash'],
skills: ['testing'],
} as AgentFrontmatter,
content: 'Agent instructions here.',
enabled: true,
};
const canonical = toCanonicalAgent(agent);
expect(canonical.name).toBe('test-agent');
expect(canonical.description).toBe('A test agent');
expect(canonical.model).toBe('opus');
expect(canonical.permissionMode).toBe('default');
expect(canonical.disallowedTools).toEqual(['Bash']);
expect(canonical.skills).toEqual(['testing']);
expect(canonical.content).toBe('Agent instructions here.');
expect(canonical.sourceFormat).toBe('claude-agent');
});
it('should handle string allowedTools', () => {
const agent: CustomAgent = {
name: 'test-agent',
description: 'Test',
path: '/path',
location: 'project',
frontmatter: {
name: 'test-agent',
description: 'Test',
allowedTools: 'Read, Glob, Grep',
} as unknown as AgentFrontmatter,
content: 'Content',
enabled: true,
};
const canonical = toCanonicalAgent(agent);
expect(canonical.allowedTools).toEqual(['Read', 'Glob', 'Grep']);
});
});
describe('fromCanonicalAgent', () => {
it('should generate markdown from CanonicalAgent', () => {
const canonical: CanonicalAgent = {
name: 'test-agent',
description: 'A test agent',
model: 'opus',
content: '# Test Agent\n\nInstructions here.',
sourceFormat: 'claude-agent',
};
const markdown = fromCanonicalAgent(canonical);
expect(markdown).toContain('---');
expect(markdown).toContain('name: test-agent');
expect(markdown).toContain('description: A test agent');
expect(markdown).toContain('model: opus');
expect(markdown).toContain('# Test Agent');
});
it('should include optional fields when present', () => {
const canonical: CanonicalAgent = {
name: 'security-agent',
description: 'Security reviewer',
permissionMode: 'plan',
disallowedTools: ['Bash', 'Write'],
allowedTools: ['Read', 'Glob'],
skills: ['security', 'review'],
tags: ['security', 'code-review'],
version: '1.0.0',
author: 'test',
content: 'Content here.',
sourceFormat: 'claude-agent',
};
const markdown = fromCanonicalAgent(canonical);
expect(markdown).toContain('permissionMode: plan');
expect(markdown).toContain('disallowedTools:');
expect(markdown).toContain(' - Bash');
expect(markdown).toContain('allowed-tools:');
expect(markdown).toContain('skills:');
expect(markdown).toContain('tags: [security, code-review]');
expect(markdown).toContain('version: "1.0.0"');
expect(markdown).toContain('author: test');
});
});
});
@@ -0,0 +1,192 @@
/**
* Agent Translator Tests
*/
import { describe, it, expect } from 'vitest';
import {
translateAgent,
translateCanonicalAgent,
getAgentFilename,
getAgentTargetDirectory,
isAgentCompatible,
} from '../translator.js';
import type { CustomAgent, CanonicalAgent, AgentFrontmatter } from '../types.js';
describe('Agent Translator', () => {
describe('translateAgent', () => {
it('should translate agent to claude-code format', () => {
const agent: CustomAgent = {
name: 'test-agent',
description: 'A test agent',
path: '/path/to/agent.md',
location: 'project',
frontmatter: {
name: 'test-agent',
description: 'A test agent',
model: 'opus',
} as AgentFrontmatter,
content: 'Agent instructions here.',
enabled: true,
};
const result = translateAgent(agent, 'claude-code');
expect(result.success).toBe(true);
expect(result.targetAgent).toBe('claude-code');
expect(result.targetFormat).toBe('claude-agent');
expect(result.content).toContain('name: test-agent');
expect(result.content).toContain('model: opus');
});
it('should translate agent to cursor format', () => {
const agent: CustomAgent = {
name: 'reviewer',
description: 'Code reviewer',
path: '/path/to/agent.md',
location: 'project',
frontmatter: {
name: 'reviewer',
description: 'Code reviewer',
} as AgentFrontmatter,
content: 'Review code carefully.',
enabled: true,
};
const result = translateAgent(agent, 'cursor');
expect(result.success).toBe(true);
expect(result.targetAgent).toBe('cursor');
expect(result.targetFormat).toBe('cursor-agent');
expect(result.filename).toBe('reviewer.md');
});
it('should add warnings for hooks in cursor format', () => {
const agent: CustomAgent = {
name: 'hooked-agent',
description: 'Agent with hooks',
path: '/path/to/agent.md',
location: 'project',
frontmatter: {
name: 'hooked-agent',
description: 'Agent with hooks',
hooks: [
{ type: 'PreToolUse', command: 'echo test' },
],
} as AgentFrontmatter,
content: 'Content here.',
enabled: true,
};
const result = translateAgent(agent, 'cursor');
expect(result.success).toBe(true);
expect(result.warnings).toContain('Hooks may require manual adjustment for Cursor');
});
it('should add incompatible features for universal format', () => {
const agent: CustomAgent = {
name: 'complex-agent',
description: 'Complex agent',
path: '/path/to/agent.md',
location: 'project',
frontmatter: {
name: 'complex-agent',
description: 'Complex agent',
permissionMode: 'plan',
hooks: [
{ type: 'SessionStart', command: 'echo start' },
],
} as AgentFrontmatter,
content: 'Content here.',
enabled: true,
};
const result = translateAgent(agent, 'universal');
expect(result.success).toBe(true);
expect(result.incompatible).toContain('hooks (not supported in universal format)');
expect(result.incompatible).toContain('permissionMode (not supported in universal format)');
});
});
describe('translateCanonicalAgent', () => {
it('should translate canonical agent to different formats', () => {
const canonical: CanonicalAgent = {
name: 'test-agent',
description: 'Test agent',
model: 'sonnet',
content: 'Agent content.',
sourceFormat: 'claude-agent',
};
const claudeResult = translateCanonicalAgent(canonical, 'claude-code');
expect(claudeResult.success).toBe(true);
expect(claudeResult.content).toContain('name: test-agent');
const cursorResult = translateCanonicalAgent(canonical, 'cursor');
expect(cursorResult.success).toBe(true);
expect(cursorResult.content).toContain('name: test-agent');
const universalResult = translateCanonicalAgent(canonical, 'universal');
expect(universalResult.success).toBe(true);
expect(universalResult.content).toContain('name: test-agent');
});
it('should include metadata when option is set', () => {
const canonical: CanonicalAgent = {
name: 'test-agent',
description: 'Test agent',
content: 'Content.',
sourceFormat: 'claude-agent',
sourceAgent: 'cursor',
};
const result = translateCanonicalAgent(canonical, 'claude-code', { addMetadata: true });
expect(result.content).toContain('# Translated by SkillKit from cursor');
});
});
describe('getAgentFilename', () => {
it('should return correct filename for different agents', () => {
expect(getAgentFilename('test-agent', 'claude-code')).toBe('test-agent.md');
expect(getAgentFilename('reviewer', 'cursor')).toBe('reviewer.md');
expect(getAgentFilename('my-agent', 'universal')).toBe('my-agent.md');
});
});
describe('getAgentTargetDirectory', () => {
it('should return correct target directory', () => {
const rootDir = '/home/user/project';
expect(getAgentTargetDirectory(rootDir, 'claude-code')).toBe('/home/user/project/.claude/agents');
expect(getAgentTargetDirectory(rootDir, 'cursor')).toBe('/home/user/project/.cursor/agents');
expect(getAgentTargetDirectory(rootDir, 'universal')).toBe('/home/user/project/agents');
});
});
describe('isAgentCompatible', () => {
it('should return compatible for same format', () => {
const result = isAgentCompatible('claude-agent', 'claude-agent');
expect(result.compatible).toBe(true);
expect(result.warnings).toHaveLength(0);
});
it('should return compatible for claude-agent target', () => {
const result = isAgentCompatible('cursor-agent', 'claude-agent');
expect(result.compatible).toBe(true);
});
it('should add warnings for universal target from claude-agent', () => {
const result = isAgentCompatible('claude-agent', 'universal');
expect(result.compatible).toBe(true);
expect(result.warnings.length).toBeGreaterThan(0);
});
it('should add warnings for cursor target from claude-agent', () => {
const result = isAgentCompatible('claude-agent', 'cursor-agent');
expect(result.compatible).toBe(true);
expect(result.warnings.length).toBeGreaterThan(0);
});
});
});
+383
View File
@@ -0,0 +1,383 @@
/**
* Agent Discovery
*
* Discovers custom agent definitions across all supported locations.
*/
import { existsSync, readdirSync, statSync } from 'node:fs';
import { join, extname } from 'node:path';
import { homedir } from 'node:os';
import {
ALL_AGENT_DISCOVERY_PATHS,
AGENT_DISCOVERY_PATHS,
type CustomAgent,
type AgentLocation,
} from './types.js';
import { parseAgentFile, parseAgentDir } from './parser.js';
import type { AgentType } from '../types.js';
/**
* Discover agents in a specific directory
*/
function discoverAgentsInDir(
dir: string,
location: AgentLocation
): CustomAgent[] {
const agents: CustomAgent[] = [];
if (!existsSync(dir)) {
return agents;
}
try {
const entries = readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(dir, entry.name);
if (entry.isFile() && extname(entry.name) === '.md') {
// Parse markdown file directly
const agent = parseAgentFile(entryPath, location);
if (agent) {
agents.push(agent);
}
} else if (entry.isDirectory()) {
// Parse directory with AGENT.md inside
const agent = parseAgentDir(entryPath, location);
if (agent) {
agents.push(agent);
}
}
}
} catch {
// Ignore errors (permission denied, etc.)
}
return agents;
}
/**
* Discover all agents in a project directory
*/
export function discoverAgents(rootDir: string): CustomAgent[] {
const agents: CustomAgent[] = [];
const seen = new Set<string>();
// Search all standard paths
for (const searchPath of ALL_AGENT_DISCOVERY_PATHS) {
const fullPath = join(rootDir, searchPath);
if (existsSync(fullPath)) {
for (const agent of discoverAgentsInDir(fullPath, 'project')) {
if (!seen.has(agent.name)) {
seen.add(agent.name);
agents.push(agent);
}
}
}
}
return agents;
}
/**
* Discover agents for a specific AI coding agent
*/
export function discoverAgentsForAgent(
rootDir: string,
agentType: AgentType
): CustomAgent[] {
const agents: CustomAgent[] = [];
const seen = new Set<string>();
const paths = AGENT_DISCOVERY_PATHS[agentType] || [];
for (const searchPath of paths) {
const fullPath = join(rootDir, searchPath);
if (existsSync(fullPath)) {
for (const agent of discoverAgentsInDir(fullPath, 'project')) {
if (!seen.has(agent.name)) {
seen.add(agent.name);
agents.push(agent);
}
}
}
}
return agents;
}
/**
* Discover global agents (in ~/.claude/agents, etc.)
*/
export function discoverGlobalAgents(): CustomAgent[] {
const agents: CustomAgent[] = [];
const seen = new Set<string>();
const home = homedir();
// Global agent paths
const globalPaths = [
join(home, '.claude', 'agents'),
join(home, '.skillkit', 'agents'),
join(home, '.config', 'skillkit', 'agents'),
];
for (const searchPath of globalPaths) {
if (existsSync(searchPath)) {
for (const agent of discoverAgentsInDir(searchPath, 'global')) {
if (!seen.has(agent.name)) {
seen.add(agent.name);
agents.push(agent);
}
}
}
}
return agents;
}
/**
* Find all agents (project + global)
*/
export function findAllAgents(searchDirs: string[]): CustomAgent[] {
const agents: CustomAgent[] = [];
const seen = new Set<string>();
// Search provided directories
for (const dir of searchDirs) {
if (!existsSync(dir)) continue;
const discovered = discoverAgents(dir);
for (const agent of discovered) {
if (!seen.has(agent.name)) {
seen.add(agent.name);
agents.push(agent);
}
}
}
// Add global agents
for (const agent of discoverGlobalAgents()) {
if (!seen.has(agent.name)) {
seen.add(agent.name);
agents.push(agent);
}
}
return agents;
}
/**
* Find a specific agent by name
*/
export function findAgent(
name: string,
searchDirs: string[]
): CustomAgent | null {
// Search in provided directories first
for (const dir of searchDirs) {
if (!existsSync(dir)) continue;
// Check all discovery paths
for (const searchPath of ALL_AGENT_DISCOVERY_PATHS) {
const agentsDir = join(dir, searchPath);
if (!existsSync(agentsDir)) continue;
// Try as file
const agentFile = join(agentsDir, `${name}.md`);
if (existsSync(agentFile)) {
return parseAgentFile(agentFile, 'project');
}
// Try as directory
const agentDir = join(agentsDir, name);
if (existsSync(agentDir) && statSync(agentDir).isDirectory()) {
return parseAgentDir(agentDir, 'project');
}
}
}
// Check global agents
const home = homedir();
const globalPaths = [
join(home, '.claude', 'agents'),
join(home, '.skillkit', 'agents'),
];
for (const agentsDir of globalPaths) {
if (!existsSync(agentsDir)) continue;
const agentFile = join(agentsDir, `${name}.md`);
if (existsSync(agentFile)) {
return parseAgentFile(agentFile, 'global');
}
const agentDir = join(agentsDir, name);
if (existsSync(agentDir) && statSync(agentDir).isDirectory()) {
return parseAgentDir(agentDir, 'global');
}
}
return null;
}
/**
* Get the agents directory for a specific AI coding agent
*/
export function getAgentsDirectory(
rootDir: string,
agentType: AgentType
): string {
const paths = AGENT_DISCOVERY_PATHS[agentType];
if (paths && paths.length > 0) {
return join(rootDir, paths[0]);
}
return join(rootDir, 'agents');
}
/**
* Check if an agent exists
*/
export function agentExists(
name: string,
searchDirs: string[]
): boolean {
return findAgent(name, searchDirs) !== null;
}
/**
* Get agent count statistics
*/
export function getAgentStats(searchDirs: string[]): {
total: number;
project: number;
global: number;
enabled: number;
disabled: number;
} {
const allAgents = findAllAgents(searchDirs);
return {
total: allAgents.length,
project: allAgents.filter(a => a.location === 'project').length,
global: allAgents.filter(a => a.location === 'global').length,
enabled: allAgents.filter(a => a.enabled).length,
disabled: allAgents.filter(a => !a.enabled).length,
};
}
/**
* Recursively discover all agents in a directory tree
* This finds agents at any depth, useful for batch translation
*/
export function discoverAgentsRecursive(
rootDir: string,
location: AgentLocation = 'project'
): CustomAgent[] {
const agents: CustomAgent[] = [];
const seen = new Set<string>();
if (!existsSync(rootDir)) {
return agents;
}
function scanDirectory(dir: string): void {
try {
const entries = readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(dir, entry.name);
if (entry.isFile() && extname(entry.name) === '.md') {
// Parse markdown file directly
const agent = parseAgentFile(entryPath, location);
if (agent && !seen.has(agent.name)) {
seen.add(agent.name);
agents.push(agent);
}
} else if (entry.isDirectory()) {
// Skip hidden directories except standard agent paths
if (entry.name.startsWith('.') && !entry.name.startsWith('.claude') &&
!entry.name.startsWith('.cursor') && !entry.name.startsWith('.codex')) {
continue;
}
// Try to parse as agent directory first
const agent = parseAgentDir(entryPath, location);
if (agent && !seen.has(agent.name)) {
seen.add(agent.name);
agents.push(agent);
} else {
// If not an agent directory, recurse into it
scanDirectory(entryPath);
}
}
}
} catch {
// Ignore errors (permission denied, etc.)
}
}
scanDirectory(rootDir);
return agents;
}
/**
* Discover agents from a custom source path
* Handles both file paths and directories
*/
export function discoverAgentsFromPath(
sourcePath: string,
recursive: boolean = false,
location: AgentLocation = 'project'
): CustomAgent[] {
if (!existsSync(sourcePath)) {
return [];
}
const stats = statSync(sourcePath);
// Single file
if (stats.isFile()) {
if (extname(sourcePath) === '.md') {
const agent = parseAgentFile(sourcePath, location);
return agent ? [agent] : [];
}
return [];
}
// Directory
if (stats.isDirectory()) {
if (recursive) {
return discoverAgentsRecursive(sourcePath, location);
}
// Non-recursive: only check immediate directory
// First try as agent directory
const agent = parseAgentDir(sourcePath, location);
if (agent) {
return [agent];
}
// Otherwise scan directory contents (one level)
const agents: CustomAgent[] = [];
try {
const entries = readdirSync(sourcePath, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(sourcePath, entry.name);
if (entry.isFile() && extname(entry.name) === '.md') {
const a = parseAgentFile(entryPath, location);
if (a) agents.push(a);
} else if (entry.isDirectory()) {
const a = parseAgentDir(entryPath, location);
if (a) agents.push(a);
}
}
} catch {
// Ignore errors
}
return agents;
}
return [];
}
+62
View File
@@ -0,0 +1,62 @@
/**
* Agent Module
*
* Custom AI sub-agent management for SkillKit.
* Supports discovery, parsing, and translation of agents
* between different AI coding agent formats.
*/
// Types
export {
AgentPermissionMode,
AgentHook,
AgentFrontmatter,
AgentLocation,
AgentMetadata,
AGENT_DISCOVERY_PATHS,
ALL_AGENT_DISCOVERY_PATHS,
CUSTOM_AGENT_FORMAT_MAP,
type CustomAgent,
type CanonicalAgent,
type AgentFormatCategory,
type AgentTranslationResult,
type AgentTranslationOptions,
} from './types.js';
// Parser
export {
extractAgentFrontmatter,
extractAgentContent,
parseAgentFile,
parseAgentDir,
loadAgentMetadata,
toCanonicalAgent,
fromCanonicalAgent,
readAgentContent,
validateAgent,
} from './parser.js';
// Discovery
export {
discoverAgents,
discoverAgentsForAgent,
discoverGlobalAgents,
discoverAgentsRecursive,
discoverAgentsFromPath,
findAllAgents,
findAgent,
getAgentsDirectory,
agentExists,
getAgentStats,
} from './discovery.js';
// Translator
export {
translateAgent,
translateCanonicalAgent,
translateAgentContent,
translateAgents,
getAgentFilename,
getAgentTargetDirectory,
isAgentCompatible,
} from './translator.js';
+418
View File
@@ -0,0 +1,418 @@
/**
* Agent Parser
*
* Parses agent definition files (e.g., .claude/agents/*.md)
*/
import { existsSync, readFileSync, statSync } from 'node:fs';
import { join, basename, extname } from 'node:path';
import { parse as parseYaml } from 'yaml';
import {
AgentFrontmatter,
AgentMetadata,
type CustomAgent,
type AgentLocation,
type CanonicalAgent,
type AgentFormatCategory,
} from './types.js';
import type { AgentType } from '../types.js';
/**
* Extract YAML frontmatter from markdown content
*/
export function extractAgentFrontmatter(content: string): Record<string, unknown> | null {
const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
if (!match) {
return null;
}
try {
return parseYaml(match[1]) as Record<string, unknown>;
} catch {
return null;
}
}
/**
* Extract content after frontmatter
*/
export function extractAgentContent(content: string): string {
const withoutFrontmatter = content.replace(/^---\s*\n[\s\S]*?\n---\s*\n?/, '');
return withoutFrontmatter.trim();
}
/**
* Parse an agent file (.md)
*/
export function parseAgentFile(
filePath: string,
location: AgentLocation = 'project'
): CustomAgent | null {
if (!existsSync(filePath)) {
return null;
}
// Only parse .md files
if (extname(filePath) !== '.md') {
return null;
}
try {
const content = readFileSync(filePath, 'utf-8');
const rawFrontmatter = extractAgentFrontmatter(content);
const agentContent = extractAgentContent(content);
// If no frontmatter, use filename as name
if (!rawFrontmatter) {
const name = basename(filePath, '.md');
return {
name,
description: 'No description available',
path: filePath,
location,
frontmatter: {
name,
description: 'No description available',
},
content: agentContent,
enabled: true,
};
}
// Parse frontmatter with validation
const parsed = AgentFrontmatter.safeParse(rawFrontmatter);
if (!parsed.success) {
// Fallback to basic parsing
const name = (rawFrontmatter.name as string) || basename(filePath, '.md');
return {
name,
description: (rawFrontmatter.description as string) || 'No description available',
path: filePath,
location,
frontmatter: {
name,
description: (rawFrontmatter.description as string) || 'No description available',
...rawFrontmatter,
} as AgentFrontmatter,
content: agentContent,
enabled: true,
};
}
// Load metadata if exists
const metadataPath = filePath.replace(/\.md$/, '.skillkit-agent.json');
const metadata = loadAgentMetadata(metadataPath);
return {
name: parsed.data.name,
description: parsed.data.description,
path: filePath,
location,
frontmatter: parsed.data,
content: agentContent,
metadata: metadata ?? undefined,
enabled: metadata?.enabled ?? true,
};
} catch {
return null;
}
}
/**
* Parse an agent from a directory (containing AGENT.md)
*/
export function parseAgentDir(
dirPath: string,
location: AgentLocation = 'project'
): CustomAgent | null {
const agentMdPath = join(dirPath, 'AGENT.md');
if (existsSync(agentMdPath)) {
const agent = parseAgentFile(agentMdPath, location);
if (agent) {
// Update path to directory
agent.path = dirPath;
}
return agent;
}
// Try index.md
const indexMdPath = join(dirPath, 'index.md');
if (existsSync(indexMdPath)) {
const agent = parseAgentFile(indexMdPath, location);
if (agent) {
agent.path = dirPath;
}
return agent;
}
return null;
}
/**
* Load agent metadata from JSON file
*/
export function loadAgentMetadata(metadataPath: string): AgentMetadata | null {
if (!existsSync(metadataPath)) {
return null;
}
try {
const content = readFileSync(metadataPath, 'utf-8');
const data = JSON.parse(content);
const parsed = AgentMetadata.safeParse(data);
return parsed.success ? parsed.data : null;
} catch {
return null;
}
}
/**
* Convert parsed agent to canonical format for translation
*/
export function toCanonicalAgent(
agent: CustomAgent,
sourceAgent?: AgentType
): CanonicalAgent {
const fm = agent.frontmatter;
// Handle allowed-tools (can be string or array)
let allowedTools: string[] | undefined;
if (fm.allowedTools) {
if (typeof fm.allowedTools === 'string') {
// Parse YAML-style list
allowedTools = fm.allowedTools.split(/[,\n]/).map(t => t.trim()).filter(Boolean);
} else {
allowedTools = fm.allowedTools;
}
}
return {
name: agent.name,
description: agent.description,
model: fm.model,
permissionMode: fm.permissionMode,
disallowedTools: fm.disallowedTools,
allowedTools,
hooks: fm.hooks,
skills: fm.skills,
context: fm.context,
version: fm.version,
author: fm.author,
tags: fm.tags,
userInvocable: fm['user-invocable'],
argumentHint: fm['argument-hint'],
content: agent.content,
sourceFormat: 'claude-agent',
sourceAgent,
};
}
/**
* Generate agent markdown from canonical format
*/
export function fromCanonicalAgent(
canonical: CanonicalAgent,
_targetFormat: AgentFormatCategory = 'claude-agent'
): string {
// Note: _targetFormat reserved for format-specific output in future
const lines: string[] = [];
// Generate frontmatter
lines.push('---');
lines.push(`name: ${canonical.name}`);
lines.push(`description: ${canonical.description}`);
if (canonical.model) {
lines.push(`model: ${canonical.model}`);
}
if (canonical.permissionMode) {
lines.push(`permissionMode: ${canonical.permissionMode}`);
}
if (canonical.disallowedTools && canonical.disallowedTools.length > 0) {
lines.push('disallowedTools:');
for (const tool of canonical.disallowedTools) {
lines.push(` - ${tool}`);
}
}
if (canonical.allowedTools && canonical.allowedTools.length > 0) {
lines.push('allowed-tools:');
for (const tool of canonical.allowedTools) {
lines.push(` - ${tool}`);
}
}
if (canonical.hooks && canonical.hooks.length > 0) {
lines.push('hooks:');
for (const hook of canonical.hooks) {
lines.push(` - type: ${hook.type}`);
lines.push(` command: ${hook.command}`);
if (hook.timeout) lines.push(` timeout: ${hook.timeout}`);
if (hook.once) lines.push(` once: ${hook.once}`);
if (hook.matcher) lines.push(` matcher: ${hook.matcher}`);
}
}
if (canonical.skills && canonical.skills.length > 0) {
lines.push('skills:');
for (const skill of canonical.skills) {
lines.push(` - ${skill}`);
}
}
if (canonical.context) {
lines.push(`context: ${canonical.context}`);
}
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}`);
}
if (canonical.argumentHint) {
lines.push(`argument-hint: "${canonical.argumentHint}"`);
}
lines.push('---');
lines.push('');
// Add content
lines.push(canonical.content);
return lines.join('\n');
}
/**
* Read raw agent content
*/
export function readAgentContent(agentPath: string): string | null {
// If it's a file
if (existsSync(agentPath) && extname(agentPath) === '.md') {
try {
return readFileSync(agentPath, 'utf-8');
} catch {
return null;
}
}
// If it's a directory
const agentMdPath = join(agentPath, 'AGENT.md');
if (existsSync(agentMdPath)) {
try {
return readFileSync(agentMdPath, 'utf-8');
} catch {
return null;
}
}
// Try index.md
const indexMdPath = join(agentPath, 'index.md');
if (existsSync(indexMdPath)) {
try {
return readFileSync(indexMdPath, 'utf-8');
} catch {
return null;
}
}
return null;
}
/**
* Validate an agent file
*/
export function validateAgent(
agentPath: string
): { valid: boolean; errors: string[]; warnings: string[] } {
const errors: string[] = [];
const warnings: string[] = [];
// Check file exists
let filePath = agentPath;
if (!existsSync(agentPath)) {
errors.push(`Agent file not found: ${agentPath}`);
return { valid: false, errors, warnings };
}
// If directory, look for AGENT.md
const stats = statSync(agentPath);
if (stats.isDirectory()) {
const agentMd = join(agentPath, 'AGENT.md');
const indexMd = join(agentPath, 'index.md');
if (existsSync(agentMd)) {
filePath = agentMd;
} else if (existsSync(indexMd)) {
filePath = indexMd;
} else {
errors.push('Directory must contain AGENT.md or index.md');
return { valid: false, errors, warnings };
}
}
// Read content
let content: string;
try {
content = readFileSync(filePath, 'utf-8');
} catch {
errors.push(`Cannot read file: ${filePath}`);
return { valid: false, errors, warnings };
}
// Check frontmatter
const frontmatter = extractAgentFrontmatter(content);
if (!frontmatter) {
errors.push('Missing YAML frontmatter');
return { valid: false, errors, warnings };
}
// Validate frontmatter
const parsed = AgentFrontmatter.safeParse(frontmatter);
if (!parsed.success) {
for (const issue of parsed.error.issues) {
errors.push(`${issue.path.join('.') || 'frontmatter'}: ${issue.message}`);
}
}
// Warnings
if (parsed.success) {
const data = parsed.data;
const fileName = basename(filePath, '.md');
if (data.name !== fileName && fileName !== 'AGENT' && fileName !== 'index') {
warnings.push(`name "${data.name}" does not match filename "${fileName}"`);
}
if (data.description && data.description.length < 20) {
warnings.push('description is short; consider adding more detail');
}
if (data.permissionMode === 'full-auto' || data.permissionMode === 'bypassPermissions') {
warnings.push(`permissionMode "${data.permissionMode}" is potentially dangerous`);
}
}
// Check content
const agentContent = extractAgentContent(content);
if (agentContent.length < 50) {
warnings.push('Agent system prompt is very short');
}
return { valid: errors.length === 0, errors, warnings };
}
+431
View File
@@ -0,0 +1,431 @@
/**
* Agent Translator
*
* Translates agent definitions between different AI coding agent formats.
*/
import {
type CanonicalAgent,
type AgentFormatCategory,
type AgentTranslationResult,
type AgentTranslationOptions,
type CustomAgent,
CUSTOM_AGENT_FORMAT_MAP,
AGENT_DISCOVERY_PATHS,
AgentFrontmatter,
} from './types.js';
import {
toCanonicalAgent,
fromCanonicalAgent,
extractAgentFrontmatter,
extractAgentContent,
} from './parser.js';
import type { AgentType } from '../types.js';
import { join } from 'node:path';
/**
* Translate an agent to a target AI coding agent format
*/
export function translateAgent(
agent: CustomAgent,
targetAgent: AgentType,
options?: AgentTranslationOptions
): AgentTranslationResult {
const canonical = toCanonicalAgent(agent);
return translateCanonicalAgent(canonical, targetAgent, options);
}
/**
* Translate a canonical agent to a target format
*/
export function translateCanonicalAgent(
canonical: CanonicalAgent,
targetAgent: AgentType,
options?: AgentTranslationOptions
): AgentTranslationResult {
const targetFormat = CUSTOM_AGENT_FORMAT_MAP[targetAgent];
const warnings: string[] = [];
const incompatible: string[] = [];
// Track incompatible features
if (targetFormat === 'universal') {
// Universal format has limited support
if (canonical.hooks && canonical.hooks.length > 0) {
incompatible.push('hooks (not supported in universal format)');
}
if (canonical.permissionMode) {
incompatible.push('permissionMode (not supported in universal format)');
}
}
if (targetFormat === 'cursor-agent') {
// Cursor may have different hook syntax
if (canonical.hooks && canonical.hooks.length > 0) {
warnings.push('Hooks may require manual adjustment for Cursor');
}
}
// Generate content based on target format
let content: string;
switch (targetFormat) {
case 'claude-agent':
content = generateClaudeAgent(canonical, options);
break;
case 'cursor-agent':
content = generateCursorAgent(canonical, options);
break;
case 'universal':
content = generateUniversalAgent(canonical, options);
break;
default:
content = fromCanonicalAgent(canonical, targetFormat);
}
// Determine filename
const filename = options?.outputFilename || getAgentFilename(canonical.name, targetAgent);
return {
success: true,
content,
filename,
warnings,
incompatible,
targetFormat,
targetAgent,
};
}
/**
* Translate agent content directly
*/
export function translateAgentContent(
content: string,
_sourceAgent: AgentType,
targetAgent: AgentType,
options?: AgentTranslationOptions
): AgentTranslationResult {
// Note: _sourceAgent reserved for future format-specific parsing
const agent = parseAgentFromContent(content);
if (!agent) {
return {
success: false,
content: '',
filename: '',
warnings: ['Failed to parse agent content'],
incompatible: [],
targetFormat: CUSTOM_AGENT_FORMAT_MAP[targetAgent],
targetAgent,
};
}
return translateAgent(agent, targetAgent, options);
}
/**
* Parse agent from raw content
*/
function parseAgentFromContent(content: string): CustomAgent | null {
const rawFrontmatter = extractAgentFrontmatter(content);
const agentContent = extractAgentContent(content);
if (!rawFrontmatter) {
return null;
}
const parsed = AgentFrontmatter.safeParse(rawFrontmatter);
const frontmatter = parsed.success ? parsed.data : {
name: (rawFrontmatter.name as string) || 'unnamed-agent',
description: (rawFrontmatter.description as string) || 'No description',
...rawFrontmatter,
};
return {
name: frontmatter.name,
description: frontmatter.description,
path: '',
location: 'project',
frontmatter,
content: agentContent,
enabled: true,
};
}
/**
* Generate Claude Code agent format
*/
function generateClaudeAgent(
canonical: CanonicalAgent,
options?: AgentTranslationOptions
): string {
const lines: string[] = [];
// Frontmatter
lines.push('---');
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}`);
}
if (canonical.disallowedTools && canonical.disallowedTools.length > 0) {
lines.push('disallowedTools:');
for (const tool of canonical.disallowedTools) {
lines.push(` - ${tool}`);
}
}
if (canonical.allowedTools && canonical.allowedTools.length > 0) {
lines.push('allowed-tools:');
for (const tool of canonical.allowedTools) {
lines.push(` - ${tool}`);
}
}
if (canonical.hooks && canonical.hooks.length > 0) {
lines.push('hooks:');
for (const hook of canonical.hooks) {
lines.push(` - type: ${hook.type}`);
lines.push(` command: "${escapeYamlString(hook.command)}"`);
if (hook.timeout) lines.push(` timeout: ${hook.timeout}`);
if (hook.once) lines.push(` once: true`);
if (hook.matcher) lines.push(` matcher: "${hook.matcher}"`);
}
}
if (canonical.skills && canonical.skills.length > 0) {
lines.push('skills:');
for (const skill of canonical.skills) {
lines.push(` - ${skill}`);
}
}
if (canonical.context) {
lines.push(`context: ${canonical.context}`);
}
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}`);
}
if (canonical.argumentHint) {
lines.push(`argument-hint: "${escapeYamlString(canonical.argumentHint)}"`);
}
if (options?.addMetadata) {
lines.push(`# Translated by SkillKit from ${canonical.sourceAgent || 'unknown'}`);
}
lines.push('---');
lines.push('');
// Content
lines.push(canonical.content);
return lines.join('\n');
}
/**
* Generate Cursor agent format
*/
function generateCursorAgent(
canonical: CanonicalAgent,
options?: AgentTranslationOptions
): string {
const lines: string[] = [];
// Cursor uses .mdc format for rules, but agents might be markdown
lines.push('---');
lines.push(`name: ${canonical.name}`);
lines.push(`description: ${escapeYamlString(canonical.description)}`);
if (canonical.model) {
lines.push(`model: ${canonical.model}`);
}
// Cursor-specific: may use different permission syntax
if (canonical.allowedTools && canonical.allowedTools.length > 0) {
lines.push(`tools: [${canonical.allowedTools.join(', ')}]`);
}
if (canonical.version) {
lines.push(`version: "${canonical.version}"`);
}
if (canonical.tags && canonical.tags.length > 0) {
lines.push(`tags: [${canonical.tags.join(', ')}]`);
}
if (options?.addMetadata) {
lines.push(`# Translated by SkillKit from ${canonical.sourceAgent || 'unknown'}`);
}
lines.push('---');
lines.push('');
// Content
lines.push(canonical.content);
// Add note about incompatible features
if (canonical.hooks && canonical.hooks.length > 0) {
lines.push('');
lines.push('<!-- Note: Hooks from original agent may need manual configuration -->');
}
return lines.join('\n');
}
/**
* Generate universal agent format
*/
function generateUniversalAgent(
canonical: CanonicalAgent,
options?: AgentTranslationOptions
): string {
const lines: string[] = [];
// Universal format: simplified, portable
lines.push('---');
lines.push(`name: ${canonical.name}`);
lines.push(`description: ${escapeYamlString(canonical.description)}`);
if (canonical.model) {
lines.push(`model: ${canonical.model}`);
}
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 (options?.addMetadata) {
lines.push(`# Translated by SkillKit`);
if (canonical.sourceAgent) {
lines.push(`# Original format: ${canonical.sourceAgent}`);
}
}
lines.push('---');
lines.push('');
// Content
lines.push(`# ${canonical.name}`);
lines.push('');
lines.push(canonical.content);
return lines.join('\n');
}
/**
* Get the expected filename for an agent
*/
export function getAgentFilename(
agentName: string,
targetAgent: AgentType
): string {
const format = CUSTOM_AGENT_FORMAT_MAP[targetAgent];
switch (format) {
case 'cursor-agent':
return `${agentName}.md`; // Or .mdc if Cursor uses that for agents
default:
return `${agentName}.md`;
}
}
/**
* Get the target directory for an agent
*/
export function getAgentTargetDirectory(
rootDir: string,
targetAgent: AgentType
): string {
const paths = AGENT_DISCOVERY_PATHS[targetAgent];
if (paths && paths.length > 0) {
return join(rootDir, paths[0]);
}
return join(rootDir, 'agents');
}
/**
* 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;
}
/**
* Translate multiple agents
*/
export function translateAgents(
agents: CustomAgent[],
targetAgent: AgentType,
options?: AgentTranslationOptions
): AgentTranslationResult[] {
return agents.map(agent => translateAgent(agent, targetAgent, options));
}
/**
* Check if agent format is compatible with target
*/
export function isAgentCompatible(
sourceFormat: AgentFormatCategory,
targetFormat: AgentFormatCategory
): { compatible: boolean; warnings: string[] } {
const warnings: string[] = [];
if (sourceFormat === targetFormat) {
return { compatible: true, warnings };
}
// All formats can translate to claude-agent (most feature-rich)
if (targetFormat === 'claude-agent') {
return { compatible: true, warnings };
}
// Universal format loses some features
if (targetFormat === 'universal') {
if (sourceFormat === 'claude-agent') {
warnings.push('Hooks, permissionMode, and disallowedTools will be lost');
}
return { compatible: true, warnings };
}
// Cursor format has partial support
if (targetFormat === 'cursor-agent') {
if (sourceFormat === 'claude-agent') {
warnings.push('Some Claude-specific features may not translate perfectly');
}
return { compatible: true, warnings };
}
return { compatible: true, warnings };
}
+289
View File
@@ -0,0 +1,289 @@
/**
* Agent Types
*
* Types for custom AI sub-agents (e.g., .claude/agents/*.md)
* Based on Claude Code's agent specification.
*/
import { z } from 'zod';
import type { AgentType } from '../types.js';
/**
* Agent permission modes
*/
export const AgentPermissionMode = z.enum([
'default', // Normal permission prompts
'plan', // Plan mode - ask before executing
'auto-edit', // Auto-accept edits
'full-auto', // Auto-accept everything (dangerous)
'bypassPermissions', // Skip all permission checks
]);
export type AgentPermissionMode = z.infer<typeof AgentPermissionMode>;
/**
* Agent hook definition
*/
export const AgentHook = z.object({
/** Hook event type */
type: z.enum([
'PreToolUse',
'PostToolUse',
'Stop',
'SubagentStop',
'SessionStart',
'SessionEnd',
]),
/** Command to run */
command: z.string(),
/** Timeout in milliseconds */
timeout: z.number().optional(),
/** Run only once */
once: z.boolean().optional(),
/** Tool matcher (for PreToolUse/PostToolUse) */
matcher: z.string().optional(),
});
export type AgentHook = z.infer<typeof AgentHook>;
/**
* Agent frontmatter schema
*/
export const AgentFrontmatter = z.object({
/** Agent name (kebab-case) */
name: z.string()
.min(1)
.max(64)
.regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Agent name must be lowercase alphanumeric with hyphens'),
/** Description of what this agent does */
description: z.string().min(1).max(1024),
/** Model to use (e.g., 'opus', 'sonnet', 'haiku') */
model: z.string().optional(),
/** Permission mode for this agent */
permissionMode: AgentPermissionMode.optional(),
/** Tools this agent cannot use */
disallowedTools: z.array(z.string()).optional(),
/** Allowed tools for this agent */
allowedTools: z.union([
z.array(z.string()),
z.string(), // YAML-style list in frontmatter
]).optional(),
/** Agent-scoped hooks */
hooks: z.array(AgentHook).optional(),
/** Skills to auto-load for this agent */
skills: z.array(z.string()).optional(),
/** Run in forked sub-agent context */
context: z.enum(['fork', 'inline']).optional(),
/** Version */
version: z.string().optional(),
/** Author */
author: z.string().optional(),
/** Tags for categorization */
tags: z.array(z.string()).optional(),
/** Whether agent is user-invocable via @mention */
'user-invocable': z.boolean().optional(),
/** Argument hint for agent invocation */
'argument-hint': z.string().optional(),
});
export type AgentFrontmatter = z.infer<typeof AgentFrontmatter>;
/**
* Agent location (project or global)
*/
export const AgentLocation = z.enum(['project', 'global']);
export type AgentLocation = z.infer<typeof AgentLocation>;
/**
* Agent metadata (stored in .skillkit-agent.json)
*/
export const AgentMetadata = z.object({
name: z.string(),
description: z.string(),
source: z.string(),
sourceType: z.enum(['github', 'gitlab', 'bitbucket', 'local']),
subpath: z.string().optional(),
installedAt: z.string().datetime(),
updatedAt: z.string().datetime().optional(),
enabled: z.boolean().default(true),
version: z.string().optional(),
checksum: z.string().optional(),
});
export type AgentMetadata = z.infer<typeof AgentMetadata>;
/**
* Parsed agent definition
*/
export interface CustomAgent {
/** Agent name */
name: string;
/** Description */
description: string;
/** Path to agent directory or file */
path: string;
/** Project or global location */
location: AgentLocation;
/** Full frontmatter */
frontmatter: AgentFrontmatter;
/** Agent content (system prompt) */
content: string;
/** Metadata if installed via skillkit */
metadata?: AgentMetadata;
/** Whether agent is enabled */
enabled: boolean;
}
/**
* Canonical agent for translation
*/
export interface CanonicalAgent {
/** Agent name */
name: string;
/** Description */
description: string;
/** Model to use */
model?: string;
/** Permission mode */
permissionMode?: AgentPermissionMode;
/** Disallowed tools */
disallowedTools?: string[];
/** Allowed tools */
allowedTools?: string[];
/** Agent-scoped hooks */
hooks?: AgentHook[];
/** Skills to load */
skills?: string[];
/** Execution context */
context?: 'fork' | 'inline';
/** Version */
version?: string;
/** Author */
author?: string;
/** Tags */
tags?: string[];
/** User invocable */
userInvocable?: boolean;
/** Argument hint */
argumentHint?: string;
/** Main content (system prompt) */
content: string;
/** Source format */
sourceFormat: AgentFormatCategory;
/** Source agent type */
sourceAgent?: AgentType;
}
/**
* Agent format categories
*/
export type AgentFormatCategory =
| 'claude-agent' // Claude Code .claude/agents/*.md
| 'cursor-agent' // Cursor agent format (if different)
| 'universal'; // Universal agent format
/**
* Agent translation result
*/
export interface AgentTranslationResult {
/** Whether translation succeeded */
success: boolean;
/** Translated content */
content: string;
/** Output filename */
filename: string;
/** Warnings during translation */
warnings: string[];
/** Features that couldn't be translated */
incompatible: string[];
/** Target format */
targetFormat: AgentFormatCategory;
/** Target agent type */
targetAgent: AgentType;
}
/**
* Agent translation options
*/
export interface AgentTranslationOptions {
/** Preserve original comments */
preserveComments?: boolean;
/** Add translation metadata */
addMetadata?: boolean;
/** Custom output filename */
outputFilename?: string;
}
/**
* Agent discovery paths per AI coding agent (2026 updated)
*/
export const AGENT_DISCOVERY_PATHS: Record<AgentType, string[]> = {
'claude-code': ['.claude/agents'],
'cursor': ['.cursor/agents', '.cursor/commands'],
'codex': ['.codex/agents'],
'gemini-cli': ['.gemini/agents'],
'opencode': ['.opencode/agents', '.opencode/agent'],
'antigravity': ['.antigravity/agents'],
'amp': ['.amp/agents'],
'clawdbot': ['.clawdbot/agents', 'agents'],
'droid': ['.factory/agents'],
'github-copilot': ['.github/agents', '.github/instructions', '.github/custom-agents'],
'goose': ['.goose/agents'],
'kilo': ['.kilocode/agents', '.kilocode/modes'],
'kiro-cli': ['.kiro/agents'],
'roo': ['.roo/agents', '.roo/modes'],
'trae': ['.trae/agents', '.trae/agent'],
'windsurf': ['.windsurf/agents', '.windsurf/workflows'],
'universal': ['agents', '.agents'],
};
/**
* All agent discovery paths (union of all agent paths) - 2026 updated
*/
export const ALL_AGENT_DISCOVERY_PATHS = [
'agents',
'.agents',
'.claude/agents',
'.cursor/agents',
'.cursor/commands',
'.codex/agents',
'.gemini/agents',
'.opencode/agents',
'.opencode/agent',
'.antigravity/agents',
'.amp/agents',
'.clawdbot/agents',
'.factory/agents',
'.github/agents',
'.github/instructions',
'.github/custom-agents',
'.goose/agents',
'.kilocode/agents',
'.kilocode/modes',
'.kiro/agents',
'.roo/agents',
'.roo/modes',
'.trae/agents',
'.trae/agent',
'.windsurf/agents',
'.windsurf/workflows',
];
/**
* Agent format mapping (which agents use which format)
*/
export const CUSTOM_AGENT_FORMAT_MAP: Record<AgentType, AgentFormatCategory> = {
'claude-code': 'claude-agent',
'cursor': 'cursor-agent',
'codex': 'claude-agent',
'gemini-cli': 'claude-agent',
'opencode': 'claude-agent',
'antigravity': 'claude-agent',
'amp': 'claude-agent',
'clawdbot': 'claude-agent',
'droid': 'claude-agent',
'github-copilot': 'universal',
'goose': 'claude-agent',
'kilo': 'claude-agent',
'kiro-cli': 'claude-agent',
'roo': 'claude-agent',
'trae': 'claude-agent',
'windsurf': 'universal',
'universal': 'universal',
};
+6 -28
View File
@@ -5,6 +5,7 @@ import type { ContextSyncOptions } from './types.js';
import { ContextManager } from './manager.js';
import { translateSkillFile } from '../translator/index.js';
import { findAllSkills } from '../skills.js';
import { AGENT_CONFIG } from '../agent-config.js';
/**
* Result of a sync operation
@@ -29,29 +30,6 @@ export interface SyncReport {
results: SyncResult[];
}
/**
* Agent directory configuration
*/
const AGENT_DIRS: Record<AgentType, { skillsDir: string; configFile: string }> = {
'claude-code': { skillsDir: '.claude/skills', configFile: 'AGENTS.md' },
'cursor': { skillsDir: '.cursor/skills', configFile: '.cursorrules' },
'codex': { skillsDir: '.codex/skills', configFile: 'AGENTS.md' },
'gemini-cli': { skillsDir: '.gemini/skills', configFile: 'GEMINI.md' },
'opencode': { skillsDir: '.opencode/skills', configFile: 'AGENTS.md' },
'antigravity': { skillsDir: '.antigravity/skills', configFile: 'AGENTS.md' },
'amp': { skillsDir: '.agents/skills', configFile: 'AGENTS.md' },
'clawdbot': { skillsDir: 'skills', configFile: 'AGENTS.md' },
'droid': { skillsDir: '.factory/skills', configFile: 'AGENTS.md' },
'github-copilot': { skillsDir: '.github/skills', configFile: 'AGENTS.md' },
'goose': { skillsDir: '.goose/skills', configFile: 'AGENTS.md' },
'kilo': { skillsDir: '.kilocode/skills', configFile: 'AGENTS.md' },
'kiro-cli': { skillsDir: '.kiro/skills', configFile: 'AGENTS.md' },
'roo': { skillsDir: '.roo/skills', configFile: 'AGENTS.md' },
'trae': { skillsDir: '.trae/skills', configFile: 'AGENTS.md' },
'windsurf': { skillsDir: '.windsurf/skills', configFile: 'AGENTS.md' },
'universal': { skillsDir: '.agent/skills', configFile: 'AGENTS.md' },
};
/**
* Context Sync
*
@@ -73,7 +51,7 @@ export class ContextSync {
detectAgents(): AgentType[] {
const detected: AgentType[] = [];
for (const [agent, config] of Object.entries(AGENT_DIRS)) {
for (const [agent, config] of Object.entries(AGENT_CONFIG)) {
const skillsPath = join(this.projectPath, config.skillsDir);
const configPath = join(this.projectPath, config.configFile);
@@ -171,7 +149,7 @@ export class ContextSync {
const sourceSkills = skills || this.getSourceSkills();
// Get target directory
const agentConfig = AGENT_DIRS[agent];
const agentConfig = AGENT_CONFIG[agent];
if (!agentConfig) {
result.success = false;
result.errors.push(`Unknown agent: ${agent}`);
@@ -297,8 +275,8 @@ export class ContextSync {
// Search directories based on primary agent or common locations
const searchDirs: string[] = [];
if (primaryAgent && AGENT_DIRS[primaryAgent]) {
searchDirs.push(join(this.projectPath, AGENT_DIRS[primaryAgent].skillsDir));
if (primaryAgent && AGENT_CONFIG[primaryAgent]) {
searchDirs.push(join(this.projectPath, AGENT_CONFIG[primaryAgent].skillsDir));
}
// Add common skill locations
@@ -327,7 +305,7 @@ export class ContextSync {
checkStatus(): Record<AgentType, { hasSkills: boolean; skillCount: number; skills: string[] }> {
const status: Record<string, { hasSkills: boolean; skillCount: number; skills: string[] }> = {};
for (const [agent, config] of Object.entries(AGENT_DIRS)) {
for (const [agent, config] of Object.entries(AGENT_CONFIG)) {
const skillsPath = join(this.projectPath, config.skillsDir);
const skills: string[] = [];
+9
View File
@@ -1,6 +1,9 @@
// Types
export * from './types.js';
// Centralized Agent Configuration (single source of truth)
export * from './agent-config.js';
// Skills discovery and parsing
export * from './skills.js';
@@ -66,3 +69,9 @@ export * from './ai/index.js';
// Audit Logging (Phase 18)
export * from './audit/index.js';
// Custom Agents Support (Phase 19)
export * from './agents/index.js';
// Skill Translator (Phase 20 - Cross-Agent Skill Translation)
export * from './skill-translator.js';
+7 -7
View File
@@ -128,8 +128,8 @@ export async function buildSkillIndex(
onProgress?.('No skills fetched, using sample index...');
allSkills.push(...getSampleSkills());
sources.push({
name: 'skillkit-samples',
url: 'https://github.com/skillkit/samples',
name: 'built-in',
url: 'https://github.com/rohitg00/skillkit',
lastFetched: new Date().toISOString(),
skillCount: allSkills.length,
});
@@ -198,7 +198,7 @@ function getSampleSkills(): SkillSummary[] {
{
name: 'react-best-practices',
description: 'Modern React patterns including Server Components, hooks best practices, and performance optimization',
source: 'skillkit/samples',
source: 'built-in',
tags: ['react', 'frontend', 'typescript', 'nextjs', 'performance'],
compatibility: {
frameworks: ['react', 'nextjs'],
@@ -213,7 +213,7 @@ function getSampleSkills(): SkillSummary[] {
{
name: 'tailwind-patterns',
description: 'Tailwind CSS utility patterns, responsive design, and component styling best practices',
source: 'skillkit/samples',
source: 'built-in',
tags: ['tailwind', 'css', 'styling', 'frontend', 'responsive'],
compatibility: {
frameworks: [],
@@ -228,7 +228,7 @@ function getSampleSkills(): SkillSummary[] {
{
name: 'typescript-strict-patterns',
description: 'TypeScript strict mode patterns, type safety, and advanced type utilities',
source: 'skillkit/samples',
source: 'built-in',
tags: ['typescript', 'types', 'safety', 'patterns'],
compatibility: {
frameworks: [],
@@ -243,7 +243,7 @@ function getSampleSkills(): SkillSummary[] {
{
name: 'security-best-practices',
description: 'Security patterns for web applications including XSS prevention, CSRF, and secure headers',
source: 'skillkit/samples',
source: 'built-in',
tags: ['security', 'xss', 'csrf', 'headers', 'owasp'],
compatibility: {
frameworks: [],
@@ -258,7 +258,7 @@ function getSampleSkills(): SkillSummary[] {
{
name: 'testing-patterns',
description: 'Testing patterns with Vitest/Jest including mocking, assertions, and test organization',
source: 'skillkit/samples',
source: 'built-in',
tags: ['vitest', 'jest', 'testing', 'typescript', 'mocking', 'tdd'],
compatibility: {
frameworks: [],
+692
View File
@@ -0,0 +1,692 @@
/**
* Skill Translator
*
* Translates SKILL.md files between different AI coding agent formats.
* This is the core functionality for SkillKit's cross-agent skill ecosystem.
*/
import { readFileSync, existsSync, writeFileSync, mkdirSync } from 'node:fs';
import { join, basename, dirname, resolve, relative, isAbsolute } from 'node:path';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import type { AgentType, Skill } from './types.js';
import {
AGENT_CONFIG,
type AgentDirectoryConfig,
getSkillsDir,
getConfigFile,
getAllSkillsDirs as getAgentAllSkillsDirs,
getGlobalSkillsDir as getAgentGlobalSkillsDir,
supportsAutoDiscovery as agentSupportsAutoDiscovery,
} from './agent-config.js';
/**
* Extended skill format for translation (includes invokeCommand)
*/
export interface AgentSkillFormat extends AgentDirectoryConfig {
invokeCommand: string;
}
/**
* Agent-specific skill format configurations
* Extends AGENT_CONFIG with invokeCommand for all agents
*/
export const AGENT_SKILL_FORMATS: Record<AgentType, AgentSkillFormat> = Object.fromEntries(
Object.entries(AGENT_CONFIG).map(([agent, config]) => [
agent,
{ ...config, invokeCommand: 'skillkit read' },
])
) as Record<AgentType, AgentSkillFormat>;
/**
* Canonical skill representation for cross-agent translation
*/
export interface CrossAgentSkill {
name: string;
description: string;
content: string;
frontmatter: Record<string, unknown>;
sourcePath: string;
sourceAgent?: AgentType;
version?: string;
author?: string;
tags?: string[];
allowedTools?: string[];
/** Agent-specific fields preserved during translation */
agentFields?: Record<string, unknown>;
}
/**
* Skill translation result
*/
export interface SkillTranslationResult {
success: boolean;
content: string;
filename: string;
targetDir: string;
warnings: string[];
incompatible: string[];
targetAgent: AgentType;
}
/**
* Skill translation options
*/
export interface SkillTranslationOptions {
/** Preserve original comments and formatting */
preserveComments?: boolean;
/** Add translation metadata comment */
addMetadata?: boolean;
/** Custom output filename */
outputFilename?: string;
/** Overwrite existing files */
overwrite?: boolean;
/** Write to disk */
write?: boolean;
/** Output directory override */
outputDir?: string;
}
/**
* Parse a SKILL.md file into canonical format
*/
export function parseSkillToCanonical(
skillPath: string,
sourceAgent?: AgentType
): CrossAgentSkill | null {
const skillMdPath = skillPath.endsWith('SKILL.md')
? skillPath
: join(skillPath, 'SKILL.md');
if (!existsSync(skillMdPath)) {
return null;
}
try {
const content = readFileSync(skillMdPath, 'utf-8');
return parseSkillContentToCanonical(content, skillPath, sourceAgent);
} catch {
return null;
}
}
/**
* Parse skill content string into canonical format
*/
export function parseSkillContentToCanonical(
content: string,
sourcePath: string,
sourceAgent?: AgentType
): CrossAgentSkill | null {
const frontmatterMatch = content.match(/^---\s*\n([\s\S]*?)\n---/);
let frontmatter: Record<string, unknown> = {};
let bodyContent = content;
if (frontmatterMatch) {
try {
frontmatter = parseYaml(frontmatterMatch[1]) as Record<string, unknown>;
bodyContent = content.slice(frontmatterMatch[0].length).trim();
} catch {
// Continue without frontmatter
}
}
// If sourcePath is a directory (skill folder), use its basename
// If sourcePath is a file (SKILL.md), use the parent directory's basename
const name = (frontmatter.name as string) || basename(sourcePath.endsWith('.md') ? dirname(sourcePath) : sourcePath);
const description = (frontmatter.description as string) || extractDescriptionFromContent(bodyContent);
return {
name,
description,
content: bodyContent,
frontmatter,
sourcePath,
sourceAgent,
version: frontmatter.version as string | undefined,
author: frontmatter.author as string | undefined,
tags: frontmatter.tags as string[] | undefined,
allowedTools: parseAllowedTools(frontmatter['allowed-tools']),
agentFields: extractAgentSpecificFields(frontmatter, sourceAgent),
};
}
/**
* Extract description from markdown content if not in frontmatter
*/
function extractDescriptionFromContent(content: string): string {
// Try to find first paragraph or first heading
const lines = content.split('\n').filter(line => line.trim());
for (const line of lines) {
const trimmed = line.trim();
// Skip headings
if (trimmed.startsWith('#')) continue;
// Skip code blocks
if (trimmed.startsWith('```')) continue;
// Return first substantive line
if (trimmed.length > 10) {
return trimmed.slice(0, 200) + (trimmed.length > 200 ? '...' : '');
}
}
return 'No description available';
}
/**
* Parse allowed-tools field (can be string or array)
*/
function parseAllowedTools(value: unknown): string[] | undefined {
if (!value) return undefined;
if (Array.isArray(value)) return value;
if (typeof value === 'string') {
return value.split(',').map(t => t.trim()).filter(Boolean);
}
return undefined;
}
/**
* Extract agent-specific fields from frontmatter
*/
function extractAgentSpecificFields(
frontmatter: Record<string, unknown>,
_sourceAgent?: AgentType
): Record<string, unknown> {
const agentFields: Record<string, unknown> = {};
// Preserve special fields that might be agent-specific
const specialFields = [
'disable-model-invocation',
'user-invocable',
'argument-hint',
'model',
'context',
'agent',
'globs',
'alwaysApply',
'applyTo',
'mode',
'hooks',
'permissionMode',
];
for (const field of specialFields) {
if (field in frontmatter) {
agentFields[field] = frontmatter[field];
}
}
return agentFields;
}
/**
* Translate a cross-agent skill to target agent format
*/
export function translateSkillToAgent(
canonical: CrossAgentSkill,
targetAgent: AgentType,
options?: SkillTranslationOptions
): SkillTranslationResult {
const format = AGENT_SKILL_FORMATS[targetAgent];
const warnings: string[] = [];
const incompatible: string[] = [];
// Check for incompatible features
if (canonical.agentFields?.['hooks'] && targetAgent !== 'claude-code') {
incompatible.push('hooks (only supported in Claude Code)');
}
if (canonical.agentFields?.['permissionMode'] && !['claude-code', 'roo'].includes(targetAgent)) {
warnings.push('permissionMode may not be fully supported');
}
// Generate SKILL.md content for target agent
const content = generateSkillContent(canonical, targetAgent, format, options);
// Determine output filename and directory
const filename = options?.outputFilename || 'SKILL.md';
const targetDir = options?.outputDir || join(format.skillsDir, canonical.name);
return {
success: true,
content,
filename,
targetDir,
warnings,
incompatible,
targetAgent,
};
}
/**
* Generate SKILL.md content for target agent
*/
function generateSkillContent(
canonical: CrossAgentSkill,
targetAgent: AgentType,
format: AgentSkillFormat,
options?: SkillTranslationOptions
): string {
const lines: string[] = [];
// Build frontmatter
const frontmatter: Record<string, unknown> = {
name: canonical.name,
description: canonical.description,
};
// Add version and author if present
if (canonical.version) {
frontmatter.version = canonical.version;
}
if (canonical.author) {
frontmatter.author = canonical.author;
}
if (canonical.tags && canonical.tags.length > 0) {
frontmatter.tags = canonical.tags;
}
// Add allowed-tools if present
if (canonical.allowedTools && canonical.allowedTools.length > 0) {
frontmatter['allowed-tools'] = canonical.allowedTools.join(', ');
}
// Add agent-specific fields based on target
addAgentSpecificFields(frontmatter, canonical, targetAgent, format);
// Add translation metadata if requested
if (options?.addMetadata && canonical.sourceAgent) {
frontmatter['_translated-from'] = canonical.sourceAgent;
frontmatter['_translated-at'] = new Date().toISOString();
}
// Generate YAML frontmatter
lines.push('---');
lines.push(stringifyYaml(frontmatter).trim());
lines.push('---');
lines.push('');
// Add content
lines.push(canonical.content);
return lines.join('\n');
}
/**
* Add agent-specific fields to frontmatter
*/
function addAgentSpecificFields(
frontmatter: Record<string, unknown>,
canonical: CrossAgentSkill,
targetAgent: AgentType,
_format: AgentSkillFormat
): void {
// Claude Code specific
if (targetAgent === 'claude-code') {
if ('model' in (canonical.agentFields ?? {})) {
frontmatter.model = canonical.agentFields!['model'];
}
if ('context' in (canonical.agentFields ?? {})) {
frontmatter.context = canonical.agentFields!['context'];
}
if ('agent' in (canonical.agentFields ?? {})) {
frontmatter.agent = canonical.agentFields!['agent'];
}
if ('disable-model-invocation' in (canonical.agentFields ?? {})) {
frontmatter['disable-model-invocation'] = canonical.agentFields!['disable-model-invocation'];
}
if ('user-invocable' in (canonical.agentFields ?? {})) {
frontmatter['user-invocable'] = canonical.agentFields!['user-invocable'];
}
if ('argument-hint' in (canonical.agentFields ?? {})) {
frontmatter['argument-hint'] = canonical.agentFields!['argument-hint'];
}
if ('hooks' in (canonical.agentFields ?? {})) {
frontmatter.hooks = canonical.agentFields!['hooks'];
}
if ('permissionMode' in (canonical.agentFields ?? {})) {
frontmatter.permissionMode = canonical.agentFields!['permissionMode'];
}
}
// Cursor/Trae/Windsurf specific (MDC-style)
if (['cursor', 'trae', 'windsurf'].includes(targetAgent)) {
if ('globs' in (canonical.agentFields ?? {})) {
frontmatter.globs = canonical.agentFields!['globs'];
}
if ('alwaysApply' in (canonical.agentFields ?? {})) {
frontmatter.alwaysApply = canonical.agentFields!['alwaysApply'];
}
if (targetAgent === 'windsurf' && 'mode' in (canonical.agentFields ?? {})) {
frontmatter.mode = canonical.agentFields!['mode'];
}
}
// GitHub Copilot specific
if (targetAgent === 'github-copilot') {
if ('applyTo' in (canonical.agentFields ?? {})) {
frontmatter.applyTo = canonical.agentFields!['applyTo'];
}
}
// Roo specific
if (targetAgent === 'roo') {
if ('disable-model-invocation' in (canonical.agentFields ?? {})) {
frontmatter['disable-model-invocation'] = canonical.agentFields!['disable-model-invocation'];
}
if ('user-invocable' in (canonical.agentFields ?? {})) {
frontmatter['user-invocable'] = canonical.agentFields!['user-invocable'];
}
if ('permissionMode' in (canonical.agentFields ?? {})) {
frontmatter.permissionMode = canonical.agentFields!['permissionMode'];
}
}
}
/**
* Translate a skill file to multiple target agents
*/
export function translateSkillToAll(
skillPath: string,
sourceAgent?: AgentType,
options?: SkillTranslationOptions
): Map<AgentType, SkillTranslationResult> {
const canonical = parseSkillToCanonical(skillPath, sourceAgent);
if (!canonical) {
return new Map();
}
const results = new Map<AgentType, SkillTranslationResult>();
const agents: AgentType[] = [
'claude-code', 'cursor', 'codex', 'gemini-cli', 'opencode',
'antigravity', 'amp', 'clawdbot', 'droid', 'github-copilot',
'goose', 'kilo', 'kiro-cli', 'roo', 'trae', 'windsurf', 'universal',
];
for (const agent of agents) {
if (agent !== sourceAgent) {
results.set(agent, translateSkillToAgent(canonical, agent, options));
}
}
return results;
}
/**
* Write translated skill to disk
*/
export function writeTranslatedSkill(
result: SkillTranslationResult,
rootDir: string,
options?: { overwrite?: boolean }
): { success: boolean; path: string; error?: string; skipped?: boolean } {
// Don't write if translation failed
if (!result.success) {
return {
success: false,
path: '',
error: 'Translation failed',
};
}
try {
const rootPath = resolve(rootDir);
const filePath = resolve(rootDir, result.targetDir, result.filename);
const targetPath = dirname(filePath);
// Guard against path traversal
const relPath = relative(rootPath, filePath);
if (relPath.startsWith('..') || isAbsolute(relPath)) {
return {
success: false,
path: filePath,
error: 'Resolved output path escapes rootDir',
};
}
// Check if file exists and overwrite is disabled
if (existsSync(filePath) && options?.overwrite === false) {
return {
success: false,
path: filePath,
error: 'File exists and overwrite=false',
skipped: true,
};
}
// Create directory if needed
if (!existsSync(targetPath)) {
mkdirSync(targetPath, { recursive: true });
}
writeFileSync(filePath, result.content, 'utf-8');
return { success: true, path: filePath };
} catch (error) {
return {
success: false,
path: '',
error: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Generate config file content that references skills
* This generates the agent-specific config format (AGENTS.md, .cursorrules, etc.)
*/
export function generateSkillsConfig(
skills: Skill[],
targetAgent: AgentType
): string {
const format = AGENT_SKILL_FORMATS[targetAgent];
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
switch (format.configFormat) {
case 'xml':
return generateXmlConfig(enabledSkills, format);
case 'mdc':
return generateMdcConfig(enabledSkills, format);
case 'markdown-table':
return generateMarkdownTableConfig(enabledSkills, format);
case 'json':
return generateJsonConfig(enabledSkills, format);
case 'markdown':
return generateMarkdownConfig(enabledSkills, format);
default:
return generateMarkdownConfig(enabledSkills, format);
}
}
/**
* Generate XML-style config (Claude Code, OpenCode, etc.)
*/
function generateXmlConfig(skills: Skill[], format: AgentSkillFormat): string {
const skillsXml = skills.map(s => `<skill>
<name>${escapeXml(s.name)}</name>
<description>${escapeXml(s.description)}</description>
<location>${escapeXml(s.path)}</location>
</skill>`).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`${format.invokeCommand} <skill-name>\` or \`npx ${format.invokeCommand} <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
/**
* Generate MDC-style config (Cursor)
*/
function generateMdcConfig(skills: Skill[], format: AgentSkillFormat): string {
const skillsList = skills
.map(s => `- **${s.name}**: ${s.description}`)
.join('\n');
const skillsXml = skills.map(s => `<skill>
<name>${escapeXml(s.name)}</name>
<description>${escapeXml(s.description)}</description>
<location>${escapeXml(s.path)}</location>
</skill>`).join('\n\n');
return `---
description: SkillKit skills integration - provides specialized capabilities and domain knowledge
globs: "**/*"
alwaysApply: true
---
# Skills System
You have access to specialized skills that can help complete tasks. Use the skillkit CLI to load skill instructions when needed.
## Available Skills
${skillsList}
## How to Use Skills
When a task matches a skill's description, load it with:
\`\`\`bash
${format.invokeCommand} <skill-name>
\`\`\`
The skill will provide detailed instructions for completing the task.
<!-- SKILLS_DATA_START -->
${skillsXml}
<!-- SKILLS_DATA_END -->
`;
}
/**
* Generate Markdown table config (Codex)
*/
function generateMarkdownTableConfig(skills: Skill[], format: AgentSkillFormat): string {
const skillsList = skills
.map(s => `| ${s.name} | ${s.description} | \`${format.invokeCommand} ${s.name}\` |`)
.join('\n');
return `# Skills
You have access to specialized skills for completing complex tasks.
| Skill | Description | Command |
|-------|-------------|---------|
${skillsList}
## Usage
When a task matches a skill's capability, run the command to load detailed instructions:
\`\`\`bash
${format.invokeCommand} <skill-name>
\`\`\`
Skills are loaded on-demand to keep context clean. Only load skills when relevant to the current task.
`;
}
/**
* Generate JSON config (Gemini CLI)
*/
function generateJsonConfig(skills: Skill[], format: AgentSkillFormat): string {
const skillsJson = skills.map(s => ({
name: s.name,
description: s.description,
invoke: `${format.invokeCommand} ${s.name}`,
location: s.path,
}));
return `# Skills Configuration
You have access to specialized skills that extend your capabilities.
## Available Skills
${skills.map(s => `### ${s.name}\n${s.description}\n\nInvoke: \`${format.invokeCommand} ${s.name}\``).join('\n\n')}
## Skills Data
\`\`\`json
${JSON.stringify(skillsJson, null, 2)}
\`\`\`
## Usage Instructions
1. When a task matches a skill's description, load it using the invoke command
2. Skills provide step-by-step instructions for complex tasks
3. Each skill is self-contained with its own resources
`;
}
/**
* Generate Markdown config (Windsurf, Trae, GitHub Copilot)
*/
function generateMarkdownConfig(skills: Skill[], format: AgentSkillFormat): string {
const skillsList = skills
.map(s => `### ${s.name}\n\n${s.description}\n\n**Invoke:** \`${format.invokeCommand} ${s.name}\``)
.join('\n\n');
return `# Skills System
You have access to specialized skills that can help complete tasks.
## Available Skills
${skillsList}
## How to Use Skills
When a task matches a skill's description, load it:
\`\`\`bash
${format.invokeCommand} <skill-name>
\`\`\`
Skills provide detailed instructions for completing complex tasks.
`;
}
/**
* Escape XML special characters
*/
function escapeXml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
// Re-export utility functions from centralized config with legacy names for backwards compatibility
export const getAgentSkillsDir = getSkillsDir;
export const getAgentConfigFile = getConfigFile;
export { agentSupportsAutoDiscovery as supportsAutoDiscovery };
export { getAgentAllSkillsDirs as getAllSkillsDirs };
export { getAgentGlobalSkillsDir as getGlobalSkillsDir };
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/tui",
"version": "1.6.1",
"version": "1.6.4",
"description": "Terminal UI for SkillKit",
"type": "module",
"main": "./dist/index.js",
@@ -21,8 +21,8 @@
"test": "vitest run"
},
"dependencies": {
"@skillkit/core": "^1.6.0",
"@skillkit/agents": "^1.6.0",
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"chalk": "^5.3.0",
"ink": "^5.0.1",
"ink-select-input": "^6.0.0",
+20 -82
View File
@@ -30,17 +30,17 @@ importers:
apps/skillkit:
dependencies:
'@skillkit/agents':
specifier: ^1.6.0
version: 1.6.0
specifier: workspace:*
version: link:../../packages/agents
'@skillkit/cli':
specifier: ^1.6.0
version: 1.6.0(@types/react@18.3.27)(typanion@3.14.0)
specifier: workspace:*
version: link:../../packages/cli
'@skillkit/core':
specifier: ^1.6.0
version: 1.6.0
specifier: workspace:*
version: link:../../packages/core
'@skillkit/tui':
specifier: ^1.6.0
version: 1.6.0(@types/react@18.3.27)
specifier: workspace:*
version: link:../../packages/tui
clipanion:
specifier: ^4.0.0-rc.4
version: 4.0.0-rc.4(typanion@3.14.0)
@@ -61,8 +61,8 @@ importers:
packages/agents:
dependencies:
'@skillkit/core':
specifier: ^1.6.0
version: 1.6.0
specifier: workspace:*
version: link:../core
minimatch:
specifier: ^9.0.0
version: 9.0.5
@@ -83,14 +83,14 @@ importers:
packages/cli:
dependencies:
'@skillkit/agents':
specifier: ^1.6.0
version: 1.6.0
specifier: workspace:*
version: link:../agents
'@skillkit/core':
specifier: ^1.6.0
version: 1.6.0
specifier: workspace:*
version: link:../core
'@skillkit/tui':
specifier: ^1.6.0
version: 1.6.0(@types/react@18.3.27)
specifier: workspace:*
version: link:../tui
chalk:
specifier: ^5.3.0
version: 5.6.2
@@ -154,11 +154,11 @@ importers:
packages/tui:
dependencies:
'@skillkit/agents':
specifier: ^1.6.0
version: 1.6.0
specifier: workspace:*
version: link:../agents
'@skillkit/core':
specifier: ^1.6.0
version: 1.6.0
specifier: workspace:*
version: link:../core
chalk:
specifier: ^5.3.0
version: 5.6.2
@@ -650,22 +650,6 @@ packages:
resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==}
engines: {node: '>=18'}
'@skillkit/agents@1.6.0':
resolution: {integrity: sha512-rYq9wMqI55ucVOMxR6fyal7Pj87funV884bb8NNop7MUOAEoETtHbMPMRL6MYv9bGvBRzwaNkWRo8cszCj+zjQ==}
engines: {node: '>=18.0.0'}
'@skillkit/cli@1.6.0':
resolution: {integrity: sha512-ghmeF3kj0TIB5hfct5aoQJO8KnxVBm2+m7wFwXg9aPtewSwws1C7nEYVFMRFWnL0kHPe6+tEo4qddm+GxJ8NFQ==}
engines: {node: '>=18.0.0'}
'@skillkit/core@1.6.0':
resolution: {integrity: sha512-987hhnYir4a3qnIkB/iIxeVeJ8mNF6R8IidtnFo9Q4GamcyvJ0W692V5wVOoR2MiS1F/NSstjfrV/h2ujMydyw==}
engines: {node: '>=18.0.0'}
'@skillkit/tui@1.6.0':
resolution: {integrity: sha512-5ifBzM0G0QhiX3cJDiUNd65SSQEmoFWKJEFtYLNDe/wcP7k3WPZemliyIpSknZh2564wqnwf3w4Ua2TtO9M/WQ==}
engines: {node: '>=18.0.0'}
'@types/estree@1.0.8':
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
@@ -1907,52 +1891,6 @@ snapshots:
'@sindresorhus/is@7.2.0': {}
'@skillkit/agents@1.6.0':
dependencies:
'@skillkit/core': 1.6.0
minimatch: 9.0.5
'@skillkit/cli@1.6.0(@types/react@18.3.27)(typanion@3.14.0)':
dependencies:
'@skillkit/agents': 1.6.0
'@skillkit/core': 1.6.0
'@skillkit/tui': 1.6.0(@types/react@18.3.27)
chalk: 5.6.2
clipanion: 4.0.0-rc.4(typanion@3.14.0)
got: 14.6.6
isomorphic-git: 1.36.1
ora: 8.2.0
yaml: 2.8.2
transitivePeerDependencies:
- '@types/react'
- bufferutil
- react-devtools-core
- typanion
- utf-8-validate
'@skillkit/core@1.6.0':
dependencies:
'@types/minimatch': 6.0.0
minimatch: 10.1.1
yaml: 2.8.2
zod: 3.25.76
'@skillkit/tui@1.6.0(@types/react@18.3.27)':
dependencies:
'@skillkit/agents': 1.6.0
'@skillkit/core': 1.6.0
chalk: 5.6.2
ink: 5.2.1(@types/react@18.3.27)(react@18.3.1)
ink-select-input: 6.2.0(ink@5.2.1(@types/react@18.3.27)(react@18.3.1))(react@18.3.1)
ink-spinner: 5.0.0(ink@5.2.1(@types/react@18.3.27)(react@18.3.1))(react@18.3.1)
ink-text-input: 6.0.0(ink@5.2.1(@types/react@18.3.27)(react@18.3.1))(react@18.3.1)
react: 18.3.1
transitivePeerDependencies:
- '@types/react'
- bufferutil
- react-devtools-core
- utf-8-validate
'@types/estree@1.0.8': {}
'@types/http-cache-semantics@4.0.4': {}