mirror of
https://github.com/rohitg00/skillkit.git
synced 2026-11-20 12:23:29 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b5722a8c0 | ||
|
|
0210556634 | ||
|
|
570ae26cd5 | ||
|
|
413519d486 | ||
|
|
eadbaff07e | ||
|
|
10e8c389e3 | ||
|
|
94c77707c4 | ||
|
|
821fd1b495 | ||
|
|
288427d9b3 |
@@ -5,32 +5,23 @@
|
||||
[](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml)
|
||||
[](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.
|
||||
|
||||
@@ -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.7.0",
|
||||
"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": {
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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'),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
Generated
+109
-1823
File diff suppressed because it is too large
Load Diff
+4
-2
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"name": "skillkit-monorepo",
|
||||
"version": "1.6.1",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "Universal skills loader for AI coding agents - Monorepo",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "turbo run build",
|
||||
"dev": "turbo run dev",
|
||||
"ui": "pnpm --filter skillkit exec bun skillkit ui",
|
||||
"test": "turbo run test",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
@@ -53,5 +54,6 @@
|
||||
"turbo": "^2.3.4",
|
||||
"typescript": "^5.7.2",
|
||||
"vitest": "^2.1.8"
|
||||
}
|
||||
},
|
||||
"pnpm": {}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/agents",
|
||||
"version": "1.6.1",
|
||||
"version": "1.7.0",
|
||||
"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', () => {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/cli",
|
||||
"version": "1.6.1",
|
||||
"version": "1.7.0",
|
||||
"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",
|
||||
|
||||
@@ -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(' ');
|
||||
}
|
||||
@@ -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,10 +1,26 @@
|
||||
import { Command } from 'clipanion';
|
||||
|
||||
/**
|
||||
* UI Command - Launch the SkillKit TUI
|
||||
* Uses the unified OpenTUI-based interface
|
||||
*/
|
||||
export class UICommand extends Command {
|
||||
static override paths = [['ui'], ['tui']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Launch the interactive TUI (Terminal User Interface)',
|
||||
details: `
|
||||
Launches the SkillKit TUI with a beautiful monochromatic design.
|
||||
|
||||
Features:
|
||||
- Browse and discover skills from the marketplace
|
||||
- Manage installed skills across 17+ AI coding agents
|
||||
- Sync skills between agents
|
||||
- AI-powered recommendations
|
||||
- Team collaboration
|
||||
|
||||
Requires Bun runtime (>=1.2.0) for optimal performance.
|
||||
`,
|
||||
examples: [
|
||||
['Open interactive TUI', '$0 ui'],
|
||||
['Alias for TUI', '$0 tui'],
|
||||
@@ -12,8 +28,20 @@ export class UICommand extends Command {
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const { startTUI } = await import('@skillkit/tui');
|
||||
await startTUI();
|
||||
return 0;
|
||||
try {
|
||||
const { startTUI } = await import('@skillkit/tui');
|
||||
await startTUI();
|
||||
return 0;
|
||||
} catch (err) {
|
||||
if (err instanceof Error) {
|
||||
console.error('Error launching TUI:', err.message);
|
||||
console.error('');
|
||||
console.error('Make sure you are running with Bun (>=1.2.0):');
|
||||
console.error(' bun skillkit ui');
|
||||
console.error('');
|
||||
console.error('Install Bun from: https://bun.sh');
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/core",
|
||||
"version": "1.6.1",
|
||||
"version": "1.7.0",
|
||||
"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');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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 [];
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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',
|
||||
};
|
||||
@@ -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[] = [];
|
||||
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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: [],
|
||||
|
||||
@@ -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, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
// 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 };
|
||||
+78
-163
@@ -5,216 +5,131 @@
|
||||
|
||||
**Interactive terminal UI for SkillKit** - browse, install, translate, and manage skills visually in your terminal.
|
||||
|
||||
## Requirements
|
||||
|
||||
- **Bun runtime** (>=1.2.0) - Required for OpenTUI rendering
|
||||
- Terminal with 80x24 minimum (120x40 recommended)
|
||||
|
||||
Install Bun: https://bun.sh
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @skillkit/tui
|
||||
# or
|
||||
npm install -g skillkit # includes TUI
|
||||
npm install -g skillkit
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
skillkit ui
|
||||
# or just
|
||||
skillkit
|
||||
# Launch TUI with Bun
|
||||
bun skillkit ui
|
||||
|
||||
# Or via pnpm in monorepo
|
||||
pnpm ui
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **Browse Skills**: Explore 33+ skill repositories with search and filtering
|
||||
- **Smart Recommendations**: See project-aware skill suggestions with match scores
|
||||
- **Cross-Agent Translation**: Convert skills between any of 17 agent formats
|
||||
- **Context Management**: View detected stack and sync to all agents
|
||||
- **Multi-Agent Install**: Install skills to multiple agents at once
|
||||
- **Responsive Design**: Adapts to any terminal size
|
||||
|
||||
## Screens
|
||||
|
||||
### Home (h)
|
||||
Overview of your project and quick actions. Shows detected agents, installed skills count, and navigation hints.
|
||||
|
||||
### Marketplace (m)
|
||||
Browse curated skill marketplace:
|
||||
- Search across 33+ repositories
|
||||
- Filter by tags and categories
|
||||
- View popularity metrics
|
||||
- Install with one key
|
||||
|
||||
### Browse (b)
|
||||
Explore available skills from curated repositories:
|
||||
- Search skills with `/`
|
||||
- Filter by tags
|
||||
- View skill details
|
||||
- One-key installation
|
||||
|
||||
### Workflow (w)
|
||||
Manage and execute workflows:
|
||||
- List available workflows
|
||||
- View workflow steps
|
||||
- Execute workflows
|
||||
- Monitor progress
|
||||
|
||||
### Execute (x)
|
||||
Execute skills with checkpoints:
|
||||
- Task-based execution
|
||||
- Decision and review checkpoints
|
||||
- Dry-run mode
|
||||
- Git integration
|
||||
|
||||
### Team (a)
|
||||
Team collaboration management:
|
||||
- Create and share skill bundles
|
||||
- Import team bundles
|
||||
- Sync with remote registry
|
||||
- Manage team members
|
||||
|
||||
### Plugins (p)
|
||||
Plugin system management:
|
||||
- List installed plugins
|
||||
- Install new plugins
|
||||
- Enable/disable plugins
|
||||
- View plugin details
|
||||
|
||||
### Methodology (o)
|
||||
Development methodologies:
|
||||
- Browse 5 methodologies (Agile, TDD, DevOps, Design Thinking, Feature Flags)
|
||||
- View methodology skills
|
||||
- Apply to project
|
||||
- Track adoption
|
||||
|
||||
### Plan (n)
|
||||
Structured plan system:
|
||||
- Parse plan files
|
||||
- Validate plan structure
|
||||
- Execute plans step-by-step
|
||||
- Track progress
|
||||
|
||||
### Recommend (r)
|
||||
AI-powered skill suggestions based on your project:
|
||||
- Analyzes your package.json, configs, and file structure
|
||||
- Shows match percentage for each skill
|
||||
- Explains why skills are recommended
|
||||
- Filter by minimum score
|
||||
|
||||
### Translate (t)
|
||||
Convert skills between agent formats:
|
||||
- Select source skill
|
||||
- Choose target agent(s)
|
||||
- Preview translation
|
||||
- Apply with confirmation
|
||||
|
||||
### Context (c)
|
||||
View and manage project context:
|
||||
- Detected languages and frameworks
|
||||
- Found testing tools and databases
|
||||
- Installed agents
|
||||
- Sync context to all agents
|
||||
|
||||
### Memory (e)
|
||||
Session memory system:
|
||||
- View learnings
|
||||
- Search past sessions
|
||||
- Compress observations
|
||||
- Export as skills
|
||||
|
||||
### Installed (i)
|
||||
Manage your installed skills:
|
||||
- View all installed skills
|
||||
- Enable/disable skills
|
||||
- Remove skills
|
||||
- Update from source
|
||||
|
||||
### Sync (s)
|
||||
Sync skills across agents:
|
||||
- Select target agents
|
||||
- Preview changes
|
||||
- Apply sync
|
||||
|
||||
### Settings (,)
|
||||
Configure SkillKit:
|
||||
- Default agent
|
||||
- Auto-sync settings
|
||||
- Skill directories
|
||||
- **Monochromatic Design** - Clean B&W theme with colored accents
|
||||
- **Animated UI** - Smooth entrance animations and transitions
|
||||
- **Browse Skills** - Explore skill repositories with search and filtering
|
||||
- **Smart Recommendations** - AI-powered skill suggestions with match scores
|
||||
- **Cross-Agent Translation** - Convert skills between 17+ agent formats
|
||||
- **Team Collaboration** - Share and sync skills across teams
|
||||
- **Responsive Design** - Adapts to any terminal size
|
||||
|
||||
## Keyboard Shortcuts
|
||||
|
||||
| Key | Action |
|
||||
### Navigation
|
||||
| Key | Screen |
|
||||
|-----|--------|
|
||||
| `h` | Home screen |
|
||||
| `m` | Marketplace |
|
||||
| `h` | Home |
|
||||
| `b` | Browse skills |
|
||||
| `m` | Marketplace |
|
||||
| `r` | Recommendations |
|
||||
| `i` | Installed skills |
|
||||
| `s` | Sync settings |
|
||||
|
||||
### Actions
|
||||
| Key | Screen |
|
||||
|-----|--------|
|
||||
| `t` | Translate skills |
|
||||
| `w` | Workflows |
|
||||
| `x` | Execute |
|
||||
| `a` | Team collaboration |
|
||||
| `n` | Plan |
|
||||
| `y` | History |
|
||||
|
||||
### Team & Config
|
||||
| Key | Screen |
|
||||
|-----|--------|
|
||||
| `a` | Team |
|
||||
| `c` | Context |
|
||||
| `e` | Memory |
|
||||
| `p` | Plugins |
|
||||
| `o` | Methodology |
|
||||
| `n` | Plan system |
|
||||
| `r` | Recommendations |
|
||||
| `t` | Translate skills |
|
||||
| `c` | Context management |
|
||||
| `e` | Memory/Learnings |
|
||||
| `i` | Installed skills |
|
||||
| `s` | Sync skills |
|
||||
| `,` | Settings |
|
||||
| `↑/↓` | Navigate lists |
|
||||
| `Enter` | Select / Confirm |
|
||||
| `/` | Search |
|
||||
| `Tab` | Switch focus |
|
||||
| `Esc` | Go back |
|
||||
| `?` | Help |
|
||||
|
||||
### Global
|
||||
| Key | Action |
|
||||
|-----|--------|
|
||||
| `/` | Help screen |
|
||||
| `esc` | Go back / Home |
|
||||
| `q` | Quit |
|
||||
| `j/k` | Navigate lists |
|
||||
| `enter` | Select item |
|
||||
|
||||
## Screens Overview
|
||||
|
||||
- **Home** - Dashboard with stats, detected agents, and features
|
||||
- **Browse** - Search and explore skill repositories
|
||||
- **Marketplace** - Curated skill marketplace with popularity metrics
|
||||
- **Recommend** - AI-powered suggestions based on your project
|
||||
- **Installed** - Manage installed skills (enable/disable/remove)
|
||||
- **Sync** - Sync skills across multiple agents
|
||||
- **Translate** - Convert skills between agent formats
|
||||
- **Workflow** - Manage and execute automation workflows
|
||||
- **Execute** - Run skills with checkpoints
|
||||
- **Plan** - Structured plan creation and execution
|
||||
- **Team** - Share skills and bundles with team members
|
||||
- **Context** - View detected stack and project context
|
||||
- **Memory** - Session memory and learnings
|
||||
- **Plugins** - Plugin management
|
||||
- **Methodology** - Development methodology frameworks
|
||||
- **Settings** - Configure SkillKit preferences
|
||||
|
||||
## Programmatic Usage
|
||||
|
||||
```typescript
|
||||
import { startTUI, TUIOptions } from '@skillkit/tui';
|
||||
import { startTUI } from '@skillkit/tui';
|
||||
|
||||
// Launch with defaults
|
||||
await startTUI();
|
||||
|
||||
// Launch with options
|
||||
await startTUI({
|
||||
projectPath: './my-project',
|
||||
initialScreen: 'browse',
|
||||
theme: 'dark',
|
||||
});
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
Built with:
|
||||
- **Ink** - React for CLIs
|
||||
- **OpenTUI** - High-performance terminal UI framework
|
||||
- **React** - Component architecture
|
||||
- **@skillkit/core** - Core functionality
|
||||
|
||||
```
|
||||
src/
|
||||
├── app.tsx # Main app component
|
||||
├── index.tsx # Entry point and startTUI
|
||||
├── App.tsx # Main app component
|
||||
├── screens/ # Screen components
|
||||
│ ├── Home.tsx
|
||||
│ ├── Browse.tsx
|
||||
│ ├── Recommend.tsx
|
||||
│ ├── Translate.tsx
|
||||
│ ├── Context.tsx
|
||||
│ ├── Help.tsx
|
||||
│ └── ...
|
||||
├── components/ # Reusable UI components
|
||||
│ ├── SkillCard.tsx
|
||||
│ ├── AgentSelector.tsx
|
||||
│ ├── Sidebar.tsx
|
||||
│ ├── Splash.tsx
|
||||
│ └── ...
|
||||
└── hooks/ # React hooks
|
||||
├── useSkills.ts
|
||||
├── useContext.ts
|
||||
└── ...
|
||||
├── state/ # State types and navigation
|
||||
├── theme/ # Colors and symbols
|
||||
└── utils/ # Helper functions
|
||||
```
|
||||
|
||||
## Terminal Requirements
|
||||
|
||||
- Minimum: 80x24 characters
|
||||
- Recommended: 120x40 characters
|
||||
- Supports: True Color, 256 colors, basic ANSI
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@skillkit/tui",
|
||||
"version": "1.6.1",
|
||||
"description": "Terminal UI for SkillKit",
|
||||
"version": "2.0.0",
|
||||
"description": "Unified Terminal UI for SkillKit - Built on OpenTUI",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
@@ -21,24 +21,21 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@skillkit/core": "^1.6.0",
|
||||
"@skillkit/agents": "^1.6.0",
|
||||
"chalk": "^5.3.0",
|
||||
"ink": "^5.0.1",
|
||||
"ink-select-input": "^6.0.0",
|
||||
"ink-spinner": "^5.0.0",
|
||||
"ink-text-input": "^6.0.0",
|
||||
"react": "^18.3.1"
|
||||
"@skillkit/core": "workspace:*",
|
||||
"@skillkit/agents": "workspace:*",
|
||||
"@opentui/core": "^0.1.75",
|
||||
"@opentui/react": "^0.1.75",
|
||||
"react": "^19.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.5",
|
||||
"@types/react": "^18.3.18",
|
||||
"@types/react": "^19.0.0",
|
||||
"tsup": "^8.3.5",
|
||||
"typescript": "^5.7.2",
|
||||
"vitest": "^2.1.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
"bun": ">=1.2.0"
|
||||
},
|
||||
"license": "Apache-2.0"
|
||||
}
|
||||
|
||||
+87
-81
@@ -1,105 +1,111 @@
|
||||
import { useState } from 'react';
|
||||
import { Box, Text, useInput, useApp, useStdout } from 'ink';
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useKeyboard } from '@opentui/react';
|
||||
import { type Screen, NAV_KEYS } from './state/types.js';
|
||||
import { Sidebar } from './components/Sidebar.js';
|
||||
import { Home } from './screens/Home.js';
|
||||
import { Browse } from './screens/Browse.js';
|
||||
import { Installed } from './screens/Installed.js';
|
||||
import { Sync } from './screens/Sync.js';
|
||||
import { Settings } from './screens/Settings.js';
|
||||
import { Recommend } from './screens/Recommend.js';
|
||||
import { Translate } from './screens/Translate.js';
|
||||
import { Context } from './screens/Context.js';
|
||||
import { Workflow } from './screens/Workflow.js';
|
||||
import { Execute } from './screens/Execute.js';
|
||||
import { History } from './screens/History.js';
|
||||
import { Marketplace } from './screens/Marketplace.js';
|
||||
import { Memory } from './screens/Memory.js';
|
||||
import { Team } from './screens/Team.js';
|
||||
import { Plugins } from './screens/Plugins.js';
|
||||
import { Methodology } from './screens/Methodology.js';
|
||||
import { Plan } from './screens/Plan.js';
|
||||
import { Splash } from './components/Splash.js';
|
||||
import {
|
||||
Home, Browse, Installed, Marketplace, Settings, Recommend,
|
||||
Translate, Context, Memory, Team, Plugins, Methodology,
|
||||
Plan, Workflow, Execute, History, Sync, Help,
|
||||
} from './screens/index.js';
|
||||
|
||||
export type Screen = 'home' | 'browse' | 'installed' | 'sync' | 'settings' | 'recommend' | 'translate' | 'context' | 'workflow' | 'execute' | 'history' | 'marketplace' | 'memory' | 'team' | 'plugins' | 'methodology' | 'plan';
|
||||
interface AppProps {
|
||||
onExit?: (code?: number) => void;
|
||||
}
|
||||
|
||||
export function App() {
|
||||
export function App({ onExit }: AppProps = {}) {
|
||||
const [showSplash, setShowSplash] = useState(true);
|
||||
const [screen, setScreen] = useState<Screen>('home');
|
||||
const { exit } = useApp();
|
||||
const { stdout } = useStdout();
|
||||
const [dimensions, setDimensions] = useState({
|
||||
cols: process.stdout.columns || 80,
|
||||
rows: process.stdout.rows || 24,
|
||||
});
|
||||
|
||||
const cols = stdout?.columns || 80;
|
||||
const rows = stdout?.rows || 24;
|
||||
const showSidebar = cols >= 70;
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
setDimensions({
|
||||
cols: process.stdout.columns || 80,
|
||||
rows: process.stdout.rows || 24,
|
||||
});
|
||||
};
|
||||
process.stdout.on('resize', handleResize);
|
||||
return () => { process.stdout.off('resize', handleResize); };
|
||||
}, []);
|
||||
|
||||
const NAV_KEYS: Record<string, Screen> = {
|
||||
h: 'home',
|
||||
m: 'marketplace',
|
||||
b: 'browse',
|
||||
w: 'workflow',
|
||||
x: 'execute',
|
||||
y: 'history',
|
||||
r: 'recommend',
|
||||
t: 'translate',
|
||||
c: 'context',
|
||||
e: 'memory',
|
||||
i: 'installed',
|
||||
s: 'sync',
|
||||
a: 'team',
|
||||
p: 'plugins',
|
||||
o: 'methodology',
|
||||
n: 'plan',
|
||||
',': 'settings',
|
||||
};
|
||||
const { cols, rows } = dimensions;
|
||||
const showSidebar = cols >= 60;
|
||||
|
||||
useInput((input, key) => {
|
||||
if (input === 'q') {
|
||||
exit();
|
||||
const handleNavigate = useCallback((newScreen: Screen) => {
|
||||
setScreen(newScreen);
|
||||
}, []);
|
||||
|
||||
const handleSplashComplete = useCallback(() => {
|
||||
setShowSplash(false);
|
||||
}, []);
|
||||
|
||||
useKeyboard((key: { name?: string; ctrl?: boolean }) => {
|
||||
if (showSplash) {
|
||||
setShowSplash(false);
|
||||
return;
|
||||
}
|
||||
if (key.escape) {
|
||||
setScreen('home');
|
||||
|
||||
if (key.name === 'q' || (key.ctrl && key.name === 'c')) {
|
||||
onExit ? onExit(0) : process.exit(0);
|
||||
return;
|
||||
}
|
||||
const targetScreen = NAV_KEYS[input];
|
||||
|
||||
const targetScreen = NAV_KEYS[key.name || ''];
|
||||
if (targetScreen) {
|
||||
setScreen(targetScreen);
|
||||
}
|
||||
|
||||
if (key.name === 'escape' && screen !== 'home') {
|
||||
setScreen('home');
|
||||
}
|
||||
});
|
||||
|
||||
if (showSplash) {
|
||||
return <Splash onComplete={handleSplashComplete} duration={3000} />;
|
||||
}
|
||||
|
||||
const screenProps = {
|
||||
onNavigate: handleNavigate,
|
||||
cols: cols - (showSidebar ? 20 : 0),
|
||||
rows,
|
||||
};
|
||||
|
||||
const renderScreen = () => {
|
||||
switch (screen) {
|
||||
case 'home': return <Home onNavigate={setScreen} cols={cols} rows={rows} />;
|
||||
case 'browse': return <Browse cols={cols} rows={rows} />;
|
||||
case 'installed': return <Installed cols={cols} rows={rows} />;
|
||||
case 'sync': return <Sync cols={cols} rows={rows} />;
|
||||
case 'settings': return <Settings cols={cols} rows={rows} />;
|
||||
case 'recommend': return <Recommend cols={cols} rows={rows} />;
|
||||
case 'translate': return <Translate cols={cols} rows={rows} />;
|
||||
case 'context': return <Context cols={cols} rows={rows} />;
|
||||
case 'workflow': return <Workflow cols={cols} rows={rows} />;
|
||||
case 'execute': return <Execute cols={cols} rows={rows} />;
|
||||
case 'history': return <History cols={cols} rows={rows} />;
|
||||
case 'marketplace': return <Marketplace cols={cols} rows={rows} />;
|
||||
case 'memory': return <Memory cols={cols} rows={rows} />;
|
||||
case 'team': return <Team cols={cols} rows={rows} />;
|
||||
case 'plugins': return <Plugins cols={cols} rows={rows} />;
|
||||
case 'methodology': return <Methodology cols={cols} rows={rows} />;
|
||||
case 'plan': return <Plan cols={cols} rows={rows} />;
|
||||
case 'home': return <Home {...screenProps} />;
|
||||
case 'browse': return <Browse {...screenProps} />;
|
||||
case 'installed': return <Installed {...screenProps} />;
|
||||
case 'marketplace': return <Marketplace {...screenProps} />;
|
||||
case 'settings': return <Settings {...screenProps} />;
|
||||
case 'recommend': return <Recommend {...screenProps} />;
|
||||
case 'translate': return <Translate {...screenProps} />;
|
||||
case 'context': return <Context {...screenProps} />;
|
||||
case 'memory': return <Memory {...screenProps} />;
|
||||
case 'team': return <Team {...screenProps} />;
|
||||
case 'plugins': return <Plugins {...screenProps} />;
|
||||
case 'methodology': return <Methodology {...screenProps} />;
|
||||
case 'plan': return <Plan {...screenProps} />;
|
||||
case 'workflow': return <Workflow {...screenProps} />;
|
||||
case 'execute': return <Execute {...screenProps} />;
|
||||
case 'history': return <History {...screenProps} />;
|
||||
case 'sync': return <Sync {...screenProps} />;
|
||||
case 'help': return <Help {...screenProps} />;
|
||||
default: return <Home {...screenProps} />;
|
||||
}
|
||||
};
|
||||
|
||||
const contentHeight = rows - 2;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" height={rows}>
|
||||
<Box flexDirection="row" height={contentHeight}>
|
||||
{showSidebar && <Sidebar screen={screen} onNavigate={setScreen} />}
|
||||
<Box flexDirection="column" flexGrow={1} marginLeft={1}>
|
||||
{renderScreen()}
|
||||
</Box>
|
||||
</Box>
|
||||
<Box>
|
||||
<Text dimColor>h Home m Market b Browse w Wflow x Exec a Team p Plug o Meth n Plan r Rec t Trans c Ctx e Mem i Inst s Sync q Quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<box flexDirection="row" height={rows}>
|
||||
{showSidebar && <Sidebar screen={screen} onNavigate={handleNavigate} />}
|
||||
<box flexDirection="column" flexGrow={1} marginLeft={showSidebar ? 1 : 0} paddingRight={1}>
|
||||
{renderScreen()}
|
||||
</box>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
export { type Screen };
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
describe('TUI Components', () => {
|
||||
describe('exports', () => {
|
||||
it('should export App component', async () => {
|
||||
const { App } = await import('../App.js');
|
||||
expect(App).toBeDefined();
|
||||
expect(typeof App).toBe('function');
|
||||
});
|
||||
|
||||
it('should export theme configuration', async () => {
|
||||
const { colors, symbols } = await import('../theme.js');
|
||||
expect(colors).toBeDefined();
|
||||
expect(symbols).toBeDefined();
|
||||
});
|
||||
|
||||
it('should export all screens', async () => {
|
||||
const screens = await import('../screens/index.js');
|
||||
expect(screens.Home).toBeDefined();
|
||||
expect(screens.Browse).toBeDefined();
|
||||
expect(screens.Installed).toBeDefined();
|
||||
expect(screens.Sync).toBeDefined();
|
||||
expect(screens.Settings).toBeDefined();
|
||||
expect(screens.Recommend).toBeDefined();
|
||||
});
|
||||
|
||||
it('should export all hooks', async () => {
|
||||
const hooks = await import('../hooks/index.js');
|
||||
expect(hooks.useSkills).toBeDefined();
|
||||
expect(hooks.useMarketplace).toBeDefined();
|
||||
expect(hooks.useKeyboard).toBeDefined();
|
||||
expect(hooks.useRecommend).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
NAV_KEYS,
|
||||
SIDEBAR_NAV,
|
||||
STATUS_BAR_SHORTCUTS,
|
||||
type Screen,
|
||||
type SkillItem,
|
||||
} from '../state/types.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { symbols, AGENT_LOGOS } from '../theme/symbols.js';
|
||||
import { getVersion, getSearchDirs, getInstallDir } from '../utils/helpers.js';
|
||||
|
||||
describe('@skillkit/tui', () => {
|
||||
describe('state/types', () => {
|
||||
it('should export NAV_KEYS with all screens', () => {
|
||||
expect(NAV_KEYS).toBeDefined();
|
||||
expect(NAV_KEYS.h).toBe('home');
|
||||
expect(NAV_KEYS.b).toBe('browse');
|
||||
expect(NAV_KEYS.m).toBe('marketplace');
|
||||
expect(NAV_KEYS['/']).toBe('help');
|
||||
expect(NAV_KEYS.q).toBeUndefined(); // q is quit, not a screen
|
||||
});
|
||||
|
||||
it('should export SIDEBAR_NAV with sections', () => {
|
||||
expect(SIDEBAR_NAV).toBeDefined();
|
||||
expect(Array.isArray(SIDEBAR_NAV)).toBe(true);
|
||||
expect(SIDEBAR_NAV.length).toBeGreaterThan(0);
|
||||
|
||||
const sections = SIDEBAR_NAV.map(s => s.section);
|
||||
expect(sections).toContain('Discover');
|
||||
expect(sections).toContain('Manage');
|
||||
expect(sections).toContain('Execute');
|
||||
});
|
||||
|
||||
it('should export STATUS_BAR_SHORTCUTS', () => {
|
||||
expect(STATUS_BAR_SHORTCUTS).toBeDefined();
|
||||
expect(STATUS_BAR_SHORTCUTS).toContain('browse');
|
||||
expect(STATUS_BAR_SHORTCUTS).toContain('help');
|
||||
expect(STATUS_BAR_SHORTCUTS).toContain('quit');
|
||||
});
|
||||
});
|
||||
|
||||
describe('theme/colors', () => {
|
||||
it('should export terminalColors', () => {
|
||||
expect(terminalColors).toBeDefined();
|
||||
expect(terminalColors.text).toBeDefined();
|
||||
expect(terminalColors.textMuted).toBeDefined();
|
||||
expect(terminalColors.accent).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('theme/symbols', () => {
|
||||
it('should export symbols', () => {
|
||||
expect(symbols).toBeDefined();
|
||||
expect(symbols.brandIcon).toBeDefined();
|
||||
expect(symbols.pointer).toBeDefined();
|
||||
expect(symbols.horizontalLine).toBeDefined();
|
||||
});
|
||||
|
||||
it('should export AGENT_LOGOS', () => {
|
||||
expect(AGENT_LOGOS).toBeDefined();
|
||||
expect(AGENT_LOGOS['claude-code']).toBeDefined();
|
||||
expect(AGENT_LOGOS['claude-code'].name).toBe('Claude Code');
|
||||
});
|
||||
});
|
||||
|
||||
describe('utils/helpers', () => {
|
||||
it('should return version string', () => {
|
||||
const version = getVersion();
|
||||
expect(typeof version).toBe('string');
|
||||
expect(version.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should return search directories', () => {
|
||||
const dirs = getSearchDirs();
|
||||
expect(Array.isArray(dirs)).toBe(true);
|
||||
});
|
||||
|
||||
it('should return install directory', () => {
|
||||
const dir = getInstallDir();
|
||||
expect(typeof dir).toBe('string');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* AgentGrid Component
|
||||
* Displays monochromatic agent logos in a grid layout
|
||||
*/
|
||||
import { AGENT_LOGOS, type AgentLogo } from '../theme/symbols.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
|
||||
interface AgentGridProps {
|
||||
/** Maximum number of agents to display */
|
||||
maxVisible?: number;
|
||||
/** Show status indicators for detected agents */
|
||||
showStatus?: boolean;
|
||||
/** Agent types that are detected/active */
|
||||
detectedAgents?: string[];
|
||||
/** Number of columns in the grid */
|
||||
columns?: number;
|
||||
}
|
||||
|
||||
export function AgentGrid({
|
||||
maxVisible = 12,
|
||||
showStatus = true,
|
||||
detectedAgents = [],
|
||||
columns = 4,
|
||||
}: AgentGridProps) {
|
||||
const safeColumns = Math.max(1, columns);
|
||||
const allAgents = Object.entries(AGENT_LOGOS);
|
||||
const visibleAgents = allAgents.slice(0, maxVisible);
|
||||
const hiddenCount = allAgents.length - maxVisible;
|
||||
|
||||
const rows: [string, AgentLogo][][] = [];
|
||||
for (let i = 0; i < visibleAgents.length; i += safeColumns) {
|
||||
rows.push(visibleAgents.slice(i, i + safeColumns));
|
||||
}
|
||||
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>
|
||||
<b>Works with</b>
|
||||
</text>
|
||||
<text> </text>
|
||||
{rows.map((row, rowIndex) => (
|
||||
<box key={`row-${rowIndex}`} flexDirection="row">
|
||||
{row.map(([agentType, agent]) => {
|
||||
const isDetected = detectedAgents.includes(agentType);
|
||||
const statusIcon = showStatus ? (isDetected ? '●' : '○') : '';
|
||||
const fg = isDetected ? terminalColors.accent : terminalColors.text;
|
||||
|
||||
return (
|
||||
<box key={agentType} width={18}>
|
||||
<text fg={fg}>
|
||||
{agent.icon} {agent.name}
|
||||
{showStatus && (
|
||||
<span fg={isDetected ? terminalColors.success : terminalColors.textMuted}>
|
||||
{' '}{statusIcon}
|
||||
</span>
|
||||
)}
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
</box>
|
||||
))}
|
||||
{hiddenCount > 0 && (
|
||||
<text fg={terminalColors.textMuted}>+{hiddenCount} more agents</text>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* FeatureList Component
|
||||
* Colored feature keywords with descriptions
|
||||
*/
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
|
||||
interface Feature {
|
||||
key: string;
|
||||
label: string;
|
||||
description: string;
|
||||
color: keyof typeof terminalColors;
|
||||
}
|
||||
|
||||
const FEATURES: Feature[] = [
|
||||
{ key: 'sync', label: 'Sync', color: 'sync', description: 'share skills across all your coding agents' },
|
||||
{ key: 'browse', label: 'Browse', color: 'browse', description: 'discover skills from the marketplace' },
|
||||
{ key: 'recommend', label: 'Recommend', color: 'recommend', description: 'AI-powered skill suggestions for your project' },
|
||||
{ key: 'translate', label: 'Translate', color: 'translate', description: 'convert skills between agent formats' },
|
||||
{ key: 'workflow', label: 'Workflow', color: 'workflow', description: 'automate skill execution chains' },
|
||||
{ key: 'team', label: 'Team', color: 'team', description: 'collaborate with your development team' },
|
||||
];
|
||||
|
||||
interface FeatureListProps {
|
||||
features?: Feature[];
|
||||
}
|
||||
|
||||
export function FeatureList({ features = FEATURES }: FeatureListProps) {
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}><b>Features</b></text>
|
||||
<text> </text>
|
||||
{features.map((feat) => (
|
||||
<box key={feat.key} flexDirection="row">
|
||||
<text fg={terminalColors[feat.color]}>
|
||||
<b>{' '}{feat.label.padEnd(12)}</b>
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted}>{feat.description}</text>
|
||||
</box>
|
||||
))}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
export { FEATURES, type Feature };
|
||||
@@ -1,30 +1,35 @@
|
||||
import { Box, Text } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
/**
|
||||
* Header Component
|
||||
* Screen header with title and optional badge/count
|
||||
*/
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { symbols } from '../theme/symbols.js';
|
||||
|
||||
interface HeaderProps {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
count?: number;
|
||||
badge?: string;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export function Header({ title, subtitle, count }: HeaderProps) {
|
||||
export function Header({ title, subtitle, count, badge, icon }: HeaderProps) {
|
||||
return (
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Box justifyContent="space-between">
|
||||
<Text color={colors.primary} bold>
|
||||
{title.toUpperCase()}
|
||||
</Text>
|
||||
<box flexDirection="column" marginBottom={1}>
|
||||
<box flexDirection="row" gap={2}>
|
||||
<text fg={terminalColors.text}>
|
||||
<b>{icon && `${icon} `}{title}</b>
|
||||
</text>
|
||||
{count !== undefined && (
|
||||
<Text color={colors.secondaryDim}>
|
||||
{symbols.star} {count}
|
||||
</Text>
|
||||
<text fg={terminalColors.textMuted}>({count})</text>
|
||||
)}
|
||||
</Box>
|
||||
{badge && (
|
||||
<text fg={terminalColors.accent}>[{badge}]</text>
|
||||
)}
|
||||
</box>
|
||||
{subtitle && (
|
||||
<Text color={colors.secondaryDim} dimColor>
|
||||
{subtitle}
|
||||
</Text>
|
||||
<text fg={terminalColors.textSecondary}>{subtitle}</text>
|
||||
)}
|
||||
</Box>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* ProgressBar Component
|
||||
* Animated progress bar display
|
||||
*/
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { symbols } from '../theme/symbols.js';
|
||||
|
||||
interface ProgressBarProps {
|
||||
progress: number; // 0-100
|
||||
width?: number;
|
||||
showPercentage?: boolean;
|
||||
color?: keyof typeof terminalColors;
|
||||
}
|
||||
|
||||
export function ProgressBar({
|
||||
progress,
|
||||
width = 20,
|
||||
showPercentage = true,
|
||||
color = 'accent',
|
||||
}: ProgressBarProps) {
|
||||
const clampedProgress = Math.max(0, Math.min(100, progress));
|
||||
const filledWidth = Math.round((clampedProgress / 100) * width);
|
||||
const emptyWidth = width - filledWidth;
|
||||
|
||||
const filled = symbols.progressFilled.repeat(filledWidth);
|
||||
const empty = symbols.progressEmpty.repeat(emptyWidth);
|
||||
|
||||
return (
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text>
|
||||
<span fg={terminalColors[color]}>{filled}</span>
|
||||
<span fg={terminalColors.textMuted}>{empty}</span>
|
||||
</text>
|
||||
{showPercentage && (
|
||||
<text fg={terminalColors.textSecondary}>
|
||||
{Math.round(clampedProgress)}%
|
||||
</text>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
@@ -1,40 +1,29 @@
|
||||
import { Box, Text } from 'ink';
|
||||
import TextInput from 'ink-text-input';
|
||||
import { colors } from '../theme.js';
|
||||
/**
|
||||
* SearchInput Component
|
||||
* Rounded search input with icon
|
||||
*/
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
|
||||
interface SearchInputProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
isFocused?: boolean;
|
||||
focused?: boolean;
|
||||
onChange?: (value: string) => void;
|
||||
}
|
||||
|
||||
export function SearchInput({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = 'Search skills...',
|
||||
isFocused = false,
|
||||
placeholder = 'Search...',
|
||||
focused = false,
|
||||
}: SearchInputProps) {
|
||||
const display = value || placeholder;
|
||||
const textColor = value ? terminalColors.text : terminalColors.textMuted;
|
||||
|
||||
return (
|
||||
<Box
|
||||
borderStyle="single"
|
||||
borderColor={isFocused ? colors.primary : colors.borderDim}
|
||||
paddingX={1}
|
||||
>
|
||||
<Text color={colors.secondaryDim}>/ </Text>
|
||||
{isFocused ? (
|
||||
<TextInput
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
placeholder={placeholder}
|
||||
/>
|
||||
) : (
|
||||
<Text color={value ? colors.secondary : colors.secondaryDim}>
|
||||
{value || placeholder}
|
||||
</Text>
|
||||
)}
|
||||
<Box flexGrow={1} />
|
||||
<Text color={colors.secondaryDim}>/</Text>
|
||||
</Box>
|
||||
<box flexDirection="row" marginBottom={1}>
|
||||
<text fg={terminalColors.textMuted}>⌕ </text>
|
||||
<text fg={textColor}>{display}</text>
|
||||
{focused && <text fg={terminalColors.accent}>▏</text>}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,100 +1,44 @@
|
||||
import { Box, Text } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import type { Screen } from '../App.js';
|
||||
import { type Screen, SIDEBAR_NAV } from '../state/types.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { symbols } from '../theme/symbols.js';
|
||||
import { getVersion } from '../utils/helpers.js';
|
||||
|
||||
interface SidebarProps {
|
||||
screen: Screen;
|
||||
onNavigate: (screen: Screen) => void;
|
||||
isCompact?: boolean;
|
||||
}
|
||||
|
||||
const NAV: { id: Screen; label: string; key: string }[] = [
|
||||
// Discovery
|
||||
{ id: 'home', label: 'Home', key: 'h' },
|
||||
{ id: 'marketplace', label: 'Marketplace', key: 'm' },
|
||||
{ id: 'browse', label: 'Browse', key: 'b' },
|
||||
// Execution
|
||||
{ id: 'workflow', label: 'Workflows', key: 'w' },
|
||||
{ id: 'execute', label: 'Execute', key: 'x' },
|
||||
{ id: 'history', label: 'History', key: 'y' },
|
||||
// Collaboration
|
||||
{ id: 'team', label: 'Team', key: 'a' },
|
||||
{ id: 'plugins', label: 'Plugins', key: 'p' },
|
||||
// Methodology
|
||||
{ id: 'methodology', label: 'Methodology', key: 'o' },
|
||||
{ id: 'plan', label: 'Plans', key: 'n' },
|
||||
// Tools
|
||||
{ id: 'recommend', label: 'Recommend', key: 'r' },
|
||||
{ id: 'translate', label: 'Translate', key: 't' },
|
||||
{ id: 'context', label: 'Context', key: 'c' },
|
||||
{ id: 'memory', label: 'Memory', key: 'e' },
|
||||
// Management
|
||||
{ id: 'installed', label: 'Installed', key: 'i' },
|
||||
{ id: 'sync', label: 'Sync', key: 's' },
|
||||
{ id: 'settings', label: 'Config', key: ',' },
|
||||
];
|
||||
|
||||
export function Sidebar({ screen }: SidebarProps) {
|
||||
const version = getVersion();
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" width={14} borderStyle="single" paddingX={1}>
|
||||
<Text bold color={colors.primary}>SkillKit</Text>
|
||||
<box flexDirection="column" width={18} paddingRight={1}>
|
||||
<text fg={terminalColors.accent}>
|
||||
<b>{symbols.brandIcon} skillkit</b>
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted}>v{version}</text>
|
||||
<text> </text>
|
||||
|
||||
{/* Discovery (0-2) */}
|
||||
{NAV.slice(0, 3).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
</Text>
|
||||
{SIDEBAR_NAV.map(({ section, items }, idx) => (
|
||||
<box key={section} flexDirection="column">
|
||||
{idx > 0 && <text> </text>}
|
||||
<text fg={terminalColors.textMuted}>
|
||||
<i>{section}</i>
|
||||
</text>
|
||||
{items.map((item) => {
|
||||
const active = screen === item.screen;
|
||||
return (
|
||||
<text key={item.key} fg={active ? terminalColors.accent : terminalColors.text}>
|
||||
{active ? <b>{symbols.pointer} {item.label}</b> : <>{symbols.pointerInactive} {item.label}</>}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
</box>
|
||||
))}
|
||||
|
||||
<Text> </Text>
|
||||
|
||||
{/* Execution (3-5) */}
|
||||
{NAV.slice(3, 6).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
</Text>
|
||||
))}
|
||||
|
||||
<Text> </Text>
|
||||
|
||||
{/* Collaboration (6-7) */}
|
||||
{NAV.slice(6, 8).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
</Text>
|
||||
))}
|
||||
|
||||
<Text> </Text>
|
||||
|
||||
{/* Methodology (8-9) */}
|
||||
{NAV.slice(8, 10).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
</Text>
|
||||
))}
|
||||
|
||||
<Text> </Text>
|
||||
|
||||
{/* Tools (10-13) */}
|
||||
{NAV.slice(10, 14).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
</Text>
|
||||
))}
|
||||
|
||||
<Text> </Text>
|
||||
|
||||
{/* Management (14-16) */}
|
||||
{NAV.slice(14).map((item) => (
|
||||
<Text key={item.id} inverse={screen === item.id}>
|
||||
{screen === item.id ? symbols.bullet : ' '}{item.label}
|
||||
</Text>
|
||||
))}
|
||||
|
||||
<Box flexGrow={1} />
|
||||
|
||||
<Text dimColor>? Help</Text>
|
||||
<Text dimColor>q Quit</Text>
|
||||
</Box>
|
||||
<box flexGrow={1} />
|
||||
<text fg={terminalColors.textMuted}>{symbols.horizontalLine.repeat(14)}</text>
|
||||
<text fg={terminalColors.textMuted}>/ help q quit</text>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,103 +1,78 @@
|
||||
import { Box, Text } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
|
||||
export interface SkillItem {
|
||||
name: string;
|
||||
description?: string;
|
||||
source?: string;
|
||||
installs?: number;
|
||||
enabled?: boolean;
|
||||
}
|
||||
/**
|
||||
* SkillList Component
|
||||
* Paginated list of skills with selection
|
||||
*/
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { symbols } from '../theme/symbols.js';
|
||||
import { calculatePagination, type PaginationResult } from '../utils/list.js';
|
||||
import type { SkillItem } from '../state/types.js';
|
||||
|
||||
interface SkillListProps {
|
||||
skills: SkillItem[];
|
||||
selectedIndex: number;
|
||||
showInstalls?: boolean;
|
||||
showRank?: boolean;
|
||||
showSource?: boolean;
|
||||
maxVisible?: number;
|
||||
}
|
||||
|
||||
function formatInstalls(count: number): string {
|
||||
if (count >= 1000) {
|
||||
return `${(count / 1000).toFixed(1)}K`;
|
||||
}
|
||||
return String(count);
|
||||
onSelect?: (skill: SkillItem) => void;
|
||||
}
|
||||
|
||||
export function SkillList({
|
||||
skills,
|
||||
selectedIndex,
|
||||
showInstalls = false,
|
||||
showRank = false,
|
||||
showSource = true,
|
||||
maxVisible = 10,
|
||||
onSelect,
|
||||
}: SkillListProps) {
|
||||
if (skills.length === 0) {
|
||||
return (
|
||||
<Box>
|
||||
<Text color={colors.secondaryDim} dimColor>
|
||||
No skills found
|
||||
</Text>
|
||||
</Box>
|
||||
<text fg={terminalColors.textMuted}>No skills found</text>
|
||||
);
|
||||
}
|
||||
|
||||
const startIndex = Math.max(0, selectedIndex - Math.floor(maxVisible / 2));
|
||||
const visibleSkills = skills.slice(startIndex, startIndex + maxVisible);
|
||||
const actualStartIndex = startIndex;
|
||||
const pagination = calculatePagination(skills.length, selectedIndex, maxVisible);
|
||||
const visibleSkills = skills.slice(pagination.start, pagination.end);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
{showRank && (
|
||||
<Box marginBottom={1}>
|
||||
<Text color={colors.secondaryDim}>
|
||||
{' # SKILL'}
|
||||
{showSource && ' SOURCE'}
|
||||
{showInstalls && ' INSTALLS'}
|
||||
</Text>
|
||||
</Box>
|
||||
<box flexDirection="column">
|
||||
{/* Items above indicator */}
|
||||
{pagination.itemsAbove > 0 && (
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{symbols.arrowUp} {pagination.itemsAbove} more above
|
||||
</text>
|
||||
)}
|
||||
|
||||
{/* Skill list */}
|
||||
{visibleSkills.map((skill, idx) => {
|
||||
const realIndex = actualStartIndex + idx;
|
||||
const isSelected = realIndex === selectedIndex;
|
||||
const skillName = skill.name.padEnd(28).slice(0, 28);
|
||||
const sourceName = skill.source ? skill.source.slice(0, 25) : '';
|
||||
const actualIndex = pagination.start + idx;
|
||||
const isSelected = actualIndex === selectedIndex;
|
||||
const pointer = isSelected ? symbols.pointer : symbols.pointerInactive;
|
||||
const fg = isSelected ? terminalColors.accent : terminalColors.text;
|
||||
const statusIcon = skill.enabled ? symbols.active : symbols.pending;
|
||||
const statusColor = skill.enabled
|
||||
? terminalColors.success
|
||||
: terminalColors.textMuted;
|
||||
|
||||
return (
|
||||
<Box key={`${skill.source}-${skill.name}`}>
|
||||
<Text
|
||||
color={isSelected ? colors.primary : colors.secondary}
|
||||
bold={isSelected}
|
||||
inverse={isSelected}
|
||||
>
|
||||
{isSelected ? symbols.pointer : ' '}
|
||||
{showRank ? String(realIndex + 1).padStart(2, ' ') : ''}
|
||||
{' '}
|
||||
{skillName}
|
||||
</Text>
|
||||
{showSource && (
|
||||
<Text color={colors.secondaryDim} dimColor={!isSelected}>
|
||||
{' '}{sourceName}
|
||||
</Text>
|
||||
<box key={skill.name} flexDirection="row">
|
||||
<text fg={fg}>
|
||||
{isSelected ? <b>{pointer} {skill.name}</b> : <>{pointer} {skill.name}</>}
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{' '}{statusIcon}
|
||||
</text>
|
||||
{skill.description && (
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{' '}- {skill.description.slice(0, 40)}
|
||||
{skill.description.length > 40 ? '...' : ''}
|
||||
</text>
|
||||
)}
|
||||
{showInstalls && skill.installs !== undefined && (
|
||||
<Text color={colors.secondaryDim}>
|
||||
{formatInstalls(skill.installs).padStart(8)}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
|
||||
{skills.length > maxVisible && (
|
||||
<Box marginTop={1}>
|
||||
<Text color={colors.secondaryDim} dimColor>
|
||||
Showing {startIndex + 1}-{Math.min(startIndex + maxVisible, skills.length)} of {skills.length}
|
||||
</Text>
|
||||
</Box>
|
||||
{/* Items below indicator */}
|
||||
{pagination.itemsBelow > 0 && (
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{symbols.arrowDown} {pagination.itemsBelow} more below
|
||||
</text>
|
||||
)}
|
||||
</Box>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Spinner Component
|
||||
* Loading indicator with animated frames
|
||||
*/
|
||||
import { useState, useEffect } from 'react';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { symbols } from '../theme/symbols.js';
|
||||
|
||||
interface SpinnerProps {
|
||||
label?: string;
|
||||
color?: keyof typeof terminalColors;
|
||||
}
|
||||
|
||||
export function Spinner({ label, color = 'accent' }: SpinnerProps) {
|
||||
const [frame, setFrame] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setFrame((f) => (f + 1) % symbols.spinner.length);
|
||||
}, 80);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<box flexDirection="row" gap={1}>
|
||||
<text fg={terminalColors[color]}>{symbols.spinner[frame]}</text>
|
||||
{label && <text fg={terminalColors.text}>{label}</text>}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* Splash Component
|
||||
* Cinematic ASCII art intro with elegant animations
|
||||
* Premium terminal experience
|
||||
*/
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { getVersion } from '../utils/helpers.js';
|
||||
|
||||
// Premium ASCII art logo - clean geometric design
|
||||
const LOGO_FRAMES = [
|
||||
// Frame 1 - Dots appear
|
||||
[
|
||||
' ',
|
||||
' · · · · · · · · · · · · · · · ',
|
||||
' ',
|
||||
],
|
||||
// Frame 2 - Lines form
|
||||
[
|
||||
' ',
|
||||
' ━━━ ━ ━ ━ ━ ━ ━ ━ ━━━ ',
|
||||
' ',
|
||||
],
|
||||
// Frame 3 - Structure emerges
|
||||
[
|
||||
' ┌──┐ ┬ ┌─ ┬ ┬ ┬ ┬ ┌─ ┬ ┌─┐ ',
|
||||
' └──┐ │ │ │ │ │ │ │ │ │ ',
|
||||
' └──┘ ┴ └─ ┴ ┴─┘ ┴─┘ ┴ └─ ┴ ┴ ',
|
||||
],
|
||||
// Frame 4 - Bold letters
|
||||
[
|
||||
' ╔═╗ ╦╔═ ╦ ╦ ╦ ╦╔═ ╦╔╦╗ ',
|
||||
' ╚═╗ ╠╩╗ ║ ║ ║ ╠╩╗ ║ ║ ',
|
||||
' ╚═╝ ╩ ╩ ╩ ╩═╝ ╩═╝ ╩ ╩ ╩ ╩ ',
|
||||
],
|
||||
// Frame 5 - Final premium logo
|
||||
[
|
||||
' ███████╗██╗ ██╗██╗██╗ ██╗ ██╗ ██╗██╗████████╗',
|
||||
' ██╔════╝██║ ██╔╝██║██║ ██║ ██║ ██╔╝██║╚══██╔══╝',
|
||||
' ███████╗█████╔╝ ██║██║ ██║ █████╔╝ ██║ ██║ ',
|
||||
' ╚════██║██╔═██╗ ██║██║ ██║ ██╔═██╗ ██║ ██║ ',
|
||||
' ███████║██║ ██╗██║███████╗███████╗██║ ██╗██║ ██║ ',
|
||||
' ╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ',
|
||||
],
|
||||
];
|
||||
|
||||
// Compact logo for smaller terminals
|
||||
const LOGO_SMALL = [
|
||||
' ╔═╗╦╔═╦╦ ╦ ╦╔═╦╔╦╗ ',
|
||||
' ╚═╗╠╩╗║║ ║ ╠╩╗║ ║ ',
|
||||
' ╚═╝╩ ╩╩╩═╝╩═╝╩ ╩╩ ╩ ',
|
||||
];
|
||||
|
||||
// Elegant spinner frames
|
||||
const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
||||
|
||||
// Progress bar characters
|
||||
const PROGRESS = {
|
||||
empty: '░',
|
||||
filled: '█',
|
||||
head: '▓',
|
||||
};
|
||||
|
||||
// Loading phases with elegant messaging
|
||||
const PHASES = [
|
||||
{ message: 'Initializing', detail: 'skill engine' },
|
||||
{ message: 'Connecting', detail: 'agent network' },
|
||||
{ message: 'Loading', detail: 'skill manifests' },
|
||||
{ message: 'Syncing', detail: 'configurations' },
|
||||
{ message: 'Ready', detail: '' },
|
||||
];
|
||||
|
||||
interface SplashProps {
|
||||
onComplete: () => void;
|
||||
duration?: number;
|
||||
}
|
||||
|
||||
export function Splash({ onComplete, duration = 3500 }: SplashProps) {
|
||||
const [frame, setFrame] = useState(0);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [spinnerFrame, setSpinnerFrame] = useState(0);
|
||||
const [phase, setPhase] = useState(0);
|
||||
const [fadeIn, setFadeIn] = useState(0);
|
||||
const [particles, setParticles] = useState<string[]>([]);
|
||||
|
||||
// Cache version to avoid repeated sync file I/O on every render
|
||||
const version = useMemo(() => getVersion(), []);
|
||||
const cols = process.stdout.columns || 80;
|
||||
const rows = process.stdout.rows || 24;
|
||||
const useSmallLogo = cols < 70;
|
||||
const currentLogo = useSmallLogo ? LOGO_SMALL : (LOGO_FRAMES[Math.min(frame, 4)] || LOGO_FRAMES[4]);
|
||||
const maxWidth = Math.max(...currentLogo.map(l => l.length));
|
||||
|
||||
// Generate ambient particles - returns fresh randomized string each call
|
||||
const generateParticles = useCallback(() => {
|
||||
const chars = ['·', '∙', '•', '○', '◦', '◌', '◍', '◎'];
|
||||
return Array(cols).fill(0).map(() =>
|
||||
Math.random() > 0.97 ? chars[Math.floor(Math.random() * chars.length)] : ' '
|
||||
).join('');
|
||||
}, [cols]);
|
||||
|
||||
// Logo reveal animation
|
||||
useEffect(() => {
|
||||
if (frame >= 4) return;
|
||||
const timer = setTimeout(() => setFrame(f => f + 1), 200);
|
||||
return () => clearTimeout(timer);
|
||||
}, [frame]);
|
||||
|
||||
// Fade in effect
|
||||
useEffect(() => {
|
||||
if (fadeIn >= 10) return;
|
||||
const timer = setTimeout(() => setFadeIn(f => f + 1), 50);
|
||||
return () => clearTimeout(timer);
|
||||
}, [fadeIn]);
|
||||
|
||||
// Progress animation
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setProgress(p => {
|
||||
const newProgress = p + (Math.random() * 3 + 1);
|
||||
if (newProgress >= 100) {
|
||||
clearInterval(interval);
|
||||
return 100;
|
||||
}
|
||||
return newProgress;
|
||||
});
|
||||
}, 50);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
// Phase progression
|
||||
useEffect(() => {
|
||||
const phaseProgress = progress / 20;
|
||||
setPhase(Math.min(Math.floor(phaseProgress), PHASES.length - 1));
|
||||
}, [progress]);
|
||||
|
||||
// Spinner animation
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setSpinnerFrame(f => (f + 1) % SPINNER.length);
|
||||
}, 80);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
// Particle animation
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setParticles(prev => {
|
||||
const newParticles = [...prev];
|
||||
if (newParticles.length > 3) newParticles.shift();
|
||||
newParticles.push(generateParticles());
|
||||
return newParticles;
|
||||
});
|
||||
}, 150);
|
||||
return () => clearInterval(interval);
|
||||
}, [generateParticles]);
|
||||
|
||||
// Auto-complete
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(onComplete, duration);
|
||||
return () => clearTimeout(timer);
|
||||
}, [onComplete, duration]);
|
||||
|
||||
const pad = ' '.repeat(Math.max(0, Math.floor((cols - maxWidth) / 2)));
|
||||
const progressWidth = Math.max(1, Math.min(40, cols - 20));
|
||||
const progressPad = ' '.repeat(Math.max(0, Math.floor((cols - progressWidth) / 2)));
|
||||
|
||||
const filledWidth = Math.min(Math.floor((progress / 100) * progressWidth), progressWidth);
|
||||
const emptyWidth = Math.max(0, progressWidth - filledWidth - 1);
|
||||
const progressBar = PROGRESS.filled.repeat(filledWidth) +
|
||||
(filledWidth < progressWidth ? PROGRESS.head : '') +
|
||||
PROGRESS.empty.repeat(emptyWidth);
|
||||
|
||||
const currentPhase = PHASES[phase];
|
||||
|
||||
return (
|
||||
<box flexDirection="column" height={rows}>
|
||||
{/* Top ambient particles */}
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{particles[0] || ''}
|
||||
</text>
|
||||
|
||||
{/* Spacer */}
|
||||
<box flexGrow={1} />
|
||||
|
||||
{/* Logo */}
|
||||
<box flexDirection="column" alignItems="center">
|
||||
{currentLogo.map((line, idx) => (
|
||||
<text key={idx} fg={frame >= 4 ? terminalColors.accent : terminalColors.textMuted}>
|
||||
{frame >= 4 ? <b>{pad}{line}</b> : <>{pad}{line}</>}
|
||||
</text>
|
||||
))}
|
||||
</box>
|
||||
|
||||
{/* Tagline with fade-in */}
|
||||
<text> </text>
|
||||
{fadeIn > 3 && (
|
||||
<text fg={terminalColors.textSecondary}>
|
||||
{pad}{' '}universal skills for ai coding agents
|
||||
</text>
|
||||
)}
|
||||
|
||||
{/* Version badge */}
|
||||
{fadeIn > 5 && (
|
||||
<>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{pad}{' '}v{version}
|
||||
</text>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Spacer */}
|
||||
<text> </text>
|
||||
<text> </text>
|
||||
|
||||
{/* Progress section */}
|
||||
{fadeIn > 7 && (
|
||||
<box flexDirection="column" alignItems="center">
|
||||
{/* Status line */}
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.accent}>
|
||||
{progressPad}{SPINNER[spinnerFrame]}{' '}
|
||||
</text>
|
||||
<text fg={terminalColors.text}>
|
||||
<b>{currentPhase.message}</b>
|
||||
</text>
|
||||
{currentPhase.detail && (
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{' '}{currentPhase.detail}
|
||||
</text>
|
||||
)}
|
||||
</box>
|
||||
|
||||
{/* Progress bar */}
|
||||
<text> </text>
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.textMuted}>{progressPad}[</text>
|
||||
<text fg={terminalColors.accent}>{progressBar}</text>
|
||||
<text fg={terminalColors.textMuted}>]</text>
|
||||
<text fg={terminalColors.textSecondary}>{' '}{Math.floor(progress)}%</text>
|
||||
</box>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Spacer */}
|
||||
<box flexGrow={1} />
|
||||
|
||||
{/* Bottom hint */}
|
||||
<box flexDirection="column" alignItems="center">
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{progressPad}{' '}press any key to skip
|
||||
</text>
|
||||
<text> </text>
|
||||
{/* Bottom particles */}
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{particles[1] || ''}
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* StatsCard Component
|
||||
* OpenSync-style stats display with optional animations
|
||||
*/
|
||||
import { useState, useEffect } from 'react';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { animations } from '../theme/animations.js';
|
||||
|
||||
interface StatItem {
|
||||
label: string;
|
||||
value: number;
|
||||
color?: keyof typeof terminalColors;
|
||||
}
|
||||
|
||||
interface StatsCardProps {
|
||||
items: StatItem[];
|
||||
animated?: boolean;
|
||||
}
|
||||
|
||||
export function StatsCard({ items, animated = true }: StatsCardProps) {
|
||||
const [displayValues, setDisplayValues] = useState<number[]>(() =>
|
||||
animated ? items.map(() => 0) : items.map((item) => item.value)
|
||||
);
|
||||
const [animComplete, setAnimComplete] = useState(!animated);
|
||||
const [prevItemsLength, setPrevItemsLength] = useState(items.length);
|
||||
|
||||
useEffect(() => {
|
||||
if (items.length !== prevItemsLength) {
|
||||
setPrevItemsLength(items.length);
|
||||
setDisplayValues(animated ? items.map(() => 0) : items.map((item) => item.value));
|
||||
setAnimComplete(!animated);
|
||||
}
|
||||
}, [items, prevItemsLength, animated]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!animated || animComplete) return;
|
||||
|
||||
const duration = animations.countUp.duration;
|
||||
const startTime = Date.now();
|
||||
const targetValues = items.map((item) => item.value);
|
||||
const frameInterval = 16;
|
||||
|
||||
const intervalId = setInterval(() => {
|
||||
const elapsed = Date.now() - startTime;
|
||||
const progress = Math.min(elapsed / duration, 1);
|
||||
const eased = 1 - Math.pow(1 - progress, 4);
|
||||
|
||||
const newValues = targetValues.map((target) =>
|
||||
Math.round(target * eased)
|
||||
);
|
||||
|
||||
setDisplayValues(newValues);
|
||||
|
||||
if (progress >= 1) {
|
||||
clearInterval(intervalId);
|
||||
setAnimComplete(true);
|
||||
}
|
||||
}, frameInterval);
|
||||
|
||||
return () => clearInterval(intervalId);
|
||||
}, [animated, animComplete, items]);
|
||||
|
||||
return (
|
||||
<box flexDirection="row" gap={2}>
|
||||
{items.map((item, index) => {
|
||||
const fg = item.color
|
||||
? terminalColors[item.color]
|
||||
: terminalColors.text;
|
||||
|
||||
return (
|
||||
<box
|
||||
key={item.label}
|
||||
flexDirection="column"
|
||||
alignItems="center"
|
||||
padding={2}
|
||||
borderStyle="single"
|
||||
borderColor={terminalColors.border}
|
||||
>
|
||||
<text fg={fg}>
|
||||
<b>{String(displayValues[index])}</b>
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted}>{item.label}</text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
@@ -1,44 +1,38 @@
|
||||
import { Box, Text } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
|
||||
interface Shortcut {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
/**
|
||||
* StatusBar Component
|
||||
* Bottom status bar with keyboard shortcuts
|
||||
*/
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { STATUS_BAR_SHORTCUTS } from '../state/types.js';
|
||||
|
||||
interface StatusBarProps {
|
||||
shortcuts: Shortcut[];
|
||||
message?: string;
|
||||
messageType?: 'info' | 'success' | 'error' | 'warning';
|
||||
shortcuts?: string;
|
||||
}
|
||||
|
||||
export function StatusBar({ shortcuts, message }: StatusBarProps) {
|
||||
return (
|
||||
<Box
|
||||
borderStyle="single"
|
||||
borderColor={colors.borderDim}
|
||||
borderTop
|
||||
borderBottom={false}
|
||||
borderLeft={false}
|
||||
borderRight={false}
|
||||
paddingX={1}
|
||||
justifyContent="space-between"
|
||||
>
|
||||
<Box gap={2}>
|
||||
{shortcuts.map((shortcut, idx) => (
|
||||
<Box key={idx} gap={1}>
|
||||
<Text color={colors.primary} bold>
|
||||
{shortcut.key}
|
||||
</Text>
|
||||
<Text color={colors.secondaryDim}>{shortcut.label}</Text>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
export function StatusBar({
|
||||
message,
|
||||
messageType = 'info',
|
||||
shortcuts = STATUS_BAR_SHORTCUTS,
|
||||
}: StatusBarProps) {
|
||||
const messageColors = {
|
||||
info: terminalColors.info,
|
||||
success: terminalColors.success,
|
||||
error: terminalColors.error,
|
||||
warning: terminalColors.warning,
|
||||
};
|
||||
|
||||
{message && (
|
||||
<Text color={colors.success}>
|
||||
{symbols.check} {message}
|
||||
</Text>
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{'\u2500'.repeat(70)}
|
||||
</text>
|
||||
{message ? (
|
||||
<text fg={messageColors[messageType]}>{message}</text>
|
||||
) : (
|
||||
<text fg={terminalColors.textMuted}>{shortcuts}</text>
|
||||
)}
|
||||
</Box>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
export { Sidebar } from './Sidebar.js';
|
||||
/**
|
||||
* Components module for SkillKit TUI
|
||||
*/
|
||||
|
||||
export { AgentGrid } from './AgentGrid.js';
|
||||
export { StatsCard } from './StatsCard.js';
|
||||
export { Header } from './Header.js';
|
||||
export { SkillList, type SkillItem } from './SkillList.js';
|
||||
export { Sidebar } from './Sidebar.js';
|
||||
export { StatusBar } from './StatusBar.js';
|
||||
export { SkillList } from './SkillList.js';
|
||||
export { SearchInput } from './SearchInput.js';
|
||||
export { Spinner } from './Spinner.js';
|
||||
export { ProgressBar } from './ProgressBar.js';
|
||||
export { FeatureList, FEATURES, type Feature } from './FeatureList.js';
|
||||
export { Splash } from './Splash.js';
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
// Re-export commonly used functions with proper adapters
|
||||
import {
|
||||
loadConfig,
|
||||
getSearchDirs as coreGetSearchDirs,
|
||||
getInstallDir as coreGetInstallDir,
|
||||
saveSkillMetadata as coreSaveSkillMetadata,
|
||||
} from '@skillkit/core';
|
||||
import { getAdapter } from '@skillkit/agents';
|
||||
import type { AgentType, AgentAdapterInfo } from '@skillkit/core';
|
||||
|
||||
// Re-export for direct use
|
||||
export { coreSaveSkillMetadata as saveSkillMetadata };
|
||||
|
||||
export function getSearchDirs(agentType?: AgentType): string[] {
|
||||
const type = agentType || loadConfig().agent;
|
||||
const adapter = getAdapter(type);
|
||||
const adapterInfo: AgentAdapterInfo = {
|
||||
type: adapter.type,
|
||||
name: adapter.name,
|
||||
skillsDir: adapter.skillsDir,
|
||||
configFile: adapter.configFile,
|
||||
};
|
||||
return coreGetSearchDirs(adapterInfo);
|
||||
}
|
||||
|
||||
export function getInstallDir(global = false, agentType?: AgentType): string {
|
||||
const type = agentType || loadConfig().agent;
|
||||
const adapter = getAdapter(type);
|
||||
const adapterInfo: AgentAdapterInfo = {
|
||||
type: adapter.type,
|
||||
name: adapter.name,
|
||||
skillsDir: adapter.skillsDir,
|
||||
configFile: adapter.configFile,
|
||||
};
|
||||
return coreGetInstallDir(adapterInfo, global);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export { useSkills } from './useSkills.js';
|
||||
export { useMarketplace } from './useMarketplace.js';
|
||||
export { useKeyboard, useListNavigation } from './useKeyboard.js';
|
||||
export { useRecommend } from './useRecommend.js';
|
||||
export { useMemory } from './useMemory.js';
|
||||
@@ -1,93 +0,0 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useInput, useApp } from 'ink';
|
||||
import type { Screen } from '../App.js';
|
||||
|
||||
interface UseKeyboardOptions {
|
||||
onNavigate?: (screen: Screen) => void;
|
||||
onSelect?: () => void;
|
||||
onSearch?: () => void;
|
||||
onInstall?: () => void;
|
||||
onBack?: () => void;
|
||||
onUp?: () => void;
|
||||
onDown?: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function useKeyboard(options: UseKeyboardOptions = {}) {
|
||||
const { exit } = useApp();
|
||||
|
||||
useInput((input, key) => {
|
||||
if (options.disabled) return;
|
||||
|
||||
if (input === 'q' || (key.ctrl && input === 'c')) {
|
||||
exit();
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.escape && options.onBack) {
|
||||
options.onBack();
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.return && options.onSelect) {
|
||||
options.onSelect();
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.upArrow && options.onUp) {
|
||||
options.onUp();
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.downArrow && options.onDown) {
|
||||
options.onDown();
|
||||
return;
|
||||
}
|
||||
|
||||
if (input === '/' && options.onSearch) {
|
||||
options.onSearch();
|
||||
return;
|
||||
}
|
||||
|
||||
if (input === 'i' && options.onInstall) {
|
||||
options.onInstall();
|
||||
return;
|
||||
}
|
||||
|
||||
if (input === 'h' && options.onNavigate) {
|
||||
options.onNavigate('home');
|
||||
} else if (input === 'b' && options.onNavigate) {
|
||||
options.onNavigate('browse');
|
||||
} else if (input === 'l' && options.onNavigate) {
|
||||
options.onNavigate('installed');
|
||||
} else if (input === 's' && options.onNavigate) {
|
||||
options.onNavigate('sync');
|
||||
} else if (input === ',' && options.onNavigate) {
|
||||
options.onNavigate('settings');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function useListNavigation(listLength: number, initialIndex = 0) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(initialIndex);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedIndex >= listLength && listLength > 0) {
|
||||
setSelectedIndex(listLength - 1);
|
||||
}
|
||||
}, [listLength, selectedIndex]);
|
||||
|
||||
const moveUp = useCallback(() => {
|
||||
setSelectedIndex((prev) => Math.max(0, prev - 1));
|
||||
}, []);
|
||||
|
||||
const moveDown = useCallback(() => {
|
||||
setSelectedIndex((prev) => Math.min(listLength - 1, prev + 1));
|
||||
}, [listLength]);
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setSelectedIndex(0);
|
||||
}, []);
|
||||
|
||||
return { selectedIndex, setSelectedIndex, moveUp, moveDown, reset };
|
||||
}
|
||||
@@ -1,251 +0,0 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { detectProvider, loadConfig, extractFrontmatter } from '@skillkit/core';
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { SkillItem } from '../components/SkillList.js';
|
||||
|
||||
export interface RepoInfo {
|
||||
source: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
// Default popular repos - can be extended via config.marketplaceSources
|
||||
const DEFAULT_REPOS: RepoInfo[] = [
|
||||
{ source: 'anthropics/skills', name: 'Anthropic Official' },
|
||||
{ source: 'vercel-labs/agent-skills', name: 'Vercel Labs' },
|
||||
{ source: 'expo/skills', name: 'Expo / React Native' },
|
||||
{ source: 'remotion-dev/skills', name: 'Remotion Video' },
|
||||
{ source: 'ComposioHQ/awesome-claude-skills', name: 'Composio Awesome' },
|
||||
{ source: 'travisvn/awesome-claude-skills', name: 'Travis Awesome' },
|
||||
{ source: 'mhattingpete/claude-skills-marketplace', name: 'Skills Marketplace' },
|
||||
{ source: 'coreyhaines31/marketingskills', name: 'Marketing Skills' },
|
||||
{ source: 'obra/superpowers', name: 'Superpowers TDD' },
|
||||
{ source: 'softaworks/agent-toolkit', name: 'Softaworks Toolkit' },
|
||||
{ source: 'wshobson/agents', name: 'Dev Patterns' },
|
||||
{ source: 'langgenius/dify', name: 'Dify Frontend' },
|
||||
{ source: 'trailofbits/skills', name: 'Trail of Bits Security' },
|
||||
{ source: 'better-auth/skills', name: 'Better Auth' },
|
||||
{ source: 'onmax/nuxt-skills', name: 'Nuxt / Vue' },
|
||||
{ source: 'hyf0/vue-skills', name: 'Vue Best Practices' },
|
||||
{ source: 'jezweb/claude-skills', name: 'Cloudflare / TanStack' },
|
||||
{ source: 'elysiajs/skills', name: 'ElysiaJS / Bun' },
|
||||
{ source: 'kadajett/agent-nestjs-skills', name: 'NestJS' },
|
||||
{ source: 'callstackincubator/agent-skills', name: 'React Native' },
|
||||
{ source: 'cloudai-x/threejs-skills', name: 'Three.js' },
|
||||
{ source: 'emalorenzo/three-agent-skills', name: 'Three.js Advanced' },
|
||||
{ source: 'dimillian/skills', name: 'SwiftUI iOS' },
|
||||
{ source: 'stripe/ai', name: 'Stripe Payments' },
|
||||
{ source: 'waynesutton/convexskills', name: 'Convex Backend' },
|
||||
{ source: 'kepano/obsidian-skills', name: 'Obsidian Notes' },
|
||||
{ source: 'jimliu/baoyu-skills', name: 'Baoyu Tools' },
|
||||
{ source: 'giuseppe-trisciuoglio/developer-kit', name: 'Shadcn / Radix' },
|
||||
{ source: 'openrouterteam/agent-skills', name: 'OpenRouter SDK' },
|
||||
{ source: 'intellectronica/agent-skills', name: 'Context7' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Get marketplace repos from config or use defaults
|
||||
*/
|
||||
function getMarketplaceRepos(): RepoInfo[] {
|
||||
try {
|
||||
const config = loadConfig();
|
||||
if (config.marketplaceSources?.length) {
|
||||
// Merge config sources with defaults, config takes priority
|
||||
const configRepos: RepoInfo[] = config.marketplaceSources.map(source => ({
|
||||
source,
|
||||
name: source.split('/').pop() || source,
|
||||
}));
|
||||
// Add defaults that aren't in config
|
||||
const existingSources = new Set(configRepos.map(r => r.source));
|
||||
for (const repo of DEFAULT_REPOS) {
|
||||
if (!existingSources.has(repo.source)) {
|
||||
configRepos.push(repo);
|
||||
}
|
||||
}
|
||||
return configRepos;
|
||||
}
|
||||
} catch {
|
||||
// Config load failed, use defaults
|
||||
}
|
||||
return DEFAULT_REPOS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to read skill description from frontmatter
|
||||
*/
|
||||
function readSkillDescription(skillPath: string): string | undefined {
|
||||
const skillMdPath = join(skillPath, 'SKILL.md');
|
||||
if (!existsSync(skillMdPath)) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const content = readFileSync(skillMdPath, 'utf-8');
|
||||
const frontmatter = extractFrontmatter(content);
|
||||
if (frontmatter && typeof frontmatter.description === 'string') {
|
||||
return frontmatter.description;
|
||||
}
|
||||
} catch {
|
||||
// Failed to read, return undefined
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
interface FetchedSkill {
|
||||
name: string;
|
||||
source: string;
|
||||
repoName: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface UseMarketplaceResult {
|
||||
skills: SkillItem[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
totalCount: number;
|
||||
repos: RepoInfo[];
|
||||
currentRepo: string | null;
|
||||
failedRepos: string[];
|
||||
refresh: () => void;
|
||||
search: (query: string) => void;
|
||||
fetchRepo: (source: string) => Promise<void>;
|
||||
fetchAllRepos: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function useMarketplace(): UseMarketplaceResult {
|
||||
const [allSkills, setAllSkills] = useState<FetchedSkill[]>([]);
|
||||
const [filteredSkills, setFilteredSkills] = useState<FetchedSkill[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [currentRepo, setCurrentRepo] = useState<string | null>(null);
|
||||
const [fetchedRepos, setFetchedRepos] = useState<Set<string>>(new Set());
|
||||
const [failedRepos, setFailedRepos] = useState<string[]>([]);
|
||||
const [repos] = useState<RepoInfo[]>(() => getMarketplaceRepos());
|
||||
|
||||
const fetchRepo = useCallback(async (source: string) => {
|
||||
if (fetchedRepos.has(source)) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setCurrentRepo(source);
|
||||
|
||||
try {
|
||||
const provider = detectProvider(source);
|
||||
if (!provider) {
|
||||
throw new Error(`Could not detect provider for: ${source}`);
|
||||
}
|
||||
|
||||
const result = await provider.clone(source, '', { depth: 1 });
|
||||
|
||||
if (!result.success || !result.discoveredSkills) {
|
||||
throw new Error(result.error || 'Failed to fetch skills');
|
||||
}
|
||||
|
||||
const repoName = repos.find(r => r.source === source)?.name || source;
|
||||
const newSkills: FetchedSkill[] = result.discoveredSkills.map(skill => ({
|
||||
name: skill.name,
|
||||
source: source,
|
||||
repoName: repoName,
|
||||
// Try to read description from skill frontmatter
|
||||
description: readSkillDescription(skill.path),
|
||||
}));
|
||||
|
||||
setAllSkills(prev => {
|
||||
const updated = [...prev, ...newSkills];
|
||||
return updated.sort((a, b) => a.name.localeCompare(b.name));
|
||||
});
|
||||
|
||||
setFetchedRepos(prev => new Set([...prev, source]));
|
||||
|
||||
if (result.tempRoot) {
|
||||
const { rmSync } = await import('node:fs');
|
||||
rmSync(result.tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMsg = err instanceof Error ? err.message : 'Failed to fetch repository';
|
||||
setError(errorMsg);
|
||||
// Track failed repos for display
|
||||
setFailedRepos(prev => prev.includes(source) ? prev : [...prev, source]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setCurrentRepo(null);
|
||||
}
|
||||
}, [fetchedRepos, repos]);
|
||||
|
||||
const fetchAllRepos = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const failures: string[] = [];
|
||||
|
||||
for (const repo of repos) {
|
||||
if (!fetchedRepos.has(repo.source)) {
|
||||
setCurrentRepo(repo.source);
|
||||
try {
|
||||
await fetchRepo(repo.source);
|
||||
} catch (err) {
|
||||
// Track which repos failed
|
||||
failures.push(repo.source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update failed repos list
|
||||
if (failures.length > 0) {
|
||||
setFailedRepos(prev => {
|
||||
const combined = [...prev, ...failures];
|
||||
return [...new Set(combined)]; // deduplicate
|
||||
});
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
setCurrentRepo(null);
|
||||
}, [fetchRepo, fetchedRepos, repos]);
|
||||
|
||||
const search = useCallback((query: string) => {
|
||||
if (!query.trim()) {
|
||||
setFilteredSkills(allSkills);
|
||||
} else {
|
||||
const lowerQuery = query.toLowerCase();
|
||||
setFilteredSkills(
|
||||
allSkills.filter(
|
||||
(s) =>
|
||||
s.name.toLowerCase().includes(lowerQuery) ||
|
||||
s.source.toLowerCase().includes(lowerQuery) ||
|
||||
s.repoName.toLowerCase().includes(lowerQuery) ||
|
||||
s.description?.toLowerCase().includes(lowerQuery)
|
||||
)
|
||||
);
|
||||
}
|
||||
}, [allSkills]);
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
setFetchedRepos(new Set());
|
||||
setAllSkills([]);
|
||||
setFilteredSkills([]);
|
||||
setFailedRepos([]);
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setFilteredSkills(allSkills);
|
||||
}, [allSkills]);
|
||||
|
||||
const skills: SkillItem[] = filteredSkills.map((s) => ({
|
||||
name: s.name,
|
||||
description: s.description || s.repoName,
|
||||
source: s.source,
|
||||
}));
|
||||
|
||||
return {
|
||||
skills,
|
||||
loading,
|
||||
error,
|
||||
totalCount: allSkills.length,
|
||||
repos,
|
||||
currentRepo,
|
||||
failedRepos,
|
||||
refresh,
|
||||
search,
|
||||
fetchRepo,
|
||||
fetchAllRepos,
|
||||
};
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
LearningStore,
|
||||
ObservationStore,
|
||||
getMemoryStatus,
|
||||
createMemoryInjector,
|
||||
type Learning,
|
||||
type Observation,
|
||||
type MemoryStatus,
|
||||
} from '@skillkit/core';
|
||||
|
||||
interface UseMemoryResult {
|
||||
learnings: Learning[];
|
||||
observations: Observation[];
|
||||
status: MemoryStatus | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
isGlobal: boolean;
|
||||
setIsGlobal: (isGlobal: boolean) => void;
|
||||
refresh: () => void;
|
||||
search: (query: string) => Learning[];
|
||||
deleteLearning: (id: string) => boolean;
|
||||
deleteObservation: (id: string) => boolean;
|
||||
}
|
||||
|
||||
export function useMemory(): UseMemoryResult {
|
||||
const [learnings, setLearnings] = useState<Learning[]>([]);
|
||||
const [observations, setObservations] = useState<Observation[]>([]);
|
||||
const [status, setStatus] = useState<MemoryStatus | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isGlobal, setIsGlobal] = useState(false);
|
||||
|
||||
const projectPath = process.cwd();
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Get memory status
|
||||
const memStatus = getMemoryStatus(projectPath);
|
||||
setStatus(memStatus);
|
||||
|
||||
// Load learnings
|
||||
const learningStore = new LearningStore(
|
||||
isGlobal ? 'global' : 'project',
|
||||
isGlobal ? undefined : projectPath
|
||||
);
|
||||
setLearnings(learningStore.getAll());
|
||||
|
||||
// Load observations (project only)
|
||||
if (memStatus.hasObservations) {
|
||||
const obsStore = new ObservationStore(projectPath);
|
||||
setObservations(obsStore.getAll());
|
||||
} else {
|
||||
setObservations([]);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load memory');
|
||||
setLearnings([]);
|
||||
setObservations([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [projectPath, isGlobal]);
|
||||
|
||||
const search = useCallback(
|
||||
(query: string): Learning[] => {
|
||||
if (!query.trim()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const injector = createMemoryInjector(projectPath);
|
||||
const results = injector.search(query, {
|
||||
includeGlobal: true,
|
||||
maxLearnings: 50,
|
||||
minRelevance: 0,
|
||||
});
|
||||
return results.map((r) => r.learning);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
[projectPath]
|
||||
);
|
||||
|
||||
const deleteLearning = useCallback(
|
||||
(id: string): boolean => {
|
||||
try {
|
||||
const store = new LearningStore(
|
||||
isGlobal ? 'global' : 'project',
|
||||
isGlobal ? undefined : projectPath
|
||||
);
|
||||
const result = store.delete(id);
|
||||
if (result) {
|
||||
refresh();
|
||||
}
|
||||
return result;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[projectPath, isGlobal, refresh]
|
||||
);
|
||||
|
||||
const deleteObservation = useCallback(
|
||||
(id: string): boolean => {
|
||||
try {
|
||||
const store = new ObservationStore(projectPath);
|
||||
const result = store.delete(id);
|
||||
if (result) {
|
||||
refresh();
|
||||
}
|
||||
return result;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[projectPath, refresh]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return {
|
||||
learnings,
|
||||
observations,
|
||||
status,
|
||||
loading,
|
||||
error,
|
||||
isGlobal,
|
||||
setIsGlobal,
|
||||
refresh,
|
||||
search,
|
||||
deleteLearning,
|
||||
deleteObservation,
|
||||
};
|
||||
}
|
||||
@@ -1,196 +0,0 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import {
|
||||
RecommendationEngine,
|
||||
ContextManager,
|
||||
type ScoredSkill,
|
||||
type ProjectProfile,
|
||||
loadIndex as loadIndexFromCache,
|
||||
saveIndex,
|
||||
buildSkillIndex,
|
||||
isIndexStale,
|
||||
KNOWN_SKILL_REPOS,
|
||||
} from '@skillkit/core';
|
||||
|
||||
interface UseRecommendResult {
|
||||
recommendations: ScoredSkill[];
|
||||
profile: ProjectProfile | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
totalScanned: number;
|
||||
indexStatus: 'missing' | 'stale' | 'fresh';
|
||||
refresh: () => void;
|
||||
updateIndex: () => void;
|
||||
search: (query: string) => void;
|
||||
searchResults: ScoredSkill[];
|
||||
}
|
||||
|
||||
export function useRecommend(projectPath: string = process.cwd()): UseRecommendResult {
|
||||
const [recommendations, setRecommendations] = useState<ScoredSkill[]>([]);
|
||||
const [searchResults, setSearchResults] = useState<ScoredSkill[]>([]);
|
||||
const [profile, setProfile] = useState<ProjectProfile | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [totalScanned, setTotalScanned] = useState(0);
|
||||
const [indexStatus, setIndexStatus] = useState<'missing' | 'stale' | 'fresh'>('missing');
|
||||
const [engine] = useState(() => new RecommendationEngine());
|
||||
|
||||
const loadIndex = useCallback(() => {
|
||||
const index = loadIndexFromCache();
|
||||
|
||||
if (!index) {
|
||||
setIndexStatus('missing');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if index is stale
|
||||
if (isIndexStale(index)) {
|
||||
setIndexStatus('stale');
|
||||
} else {
|
||||
setIndexStatus('fresh');
|
||||
}
|
||||
|
||||
return index;
|
||||
}, []);
|
||||
|
||||
const getProjectProfile = useCallback((): ProjectProfile | null => {
|
||||
try {
|
||||
const manager = new ContextManager(projectPath);
|
||||
let context = manager.get();
|
||||
|
||||
if (!context) {
|
||||
context = manager.init();
|
||||
}
|
||||
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
name: context.project.name,
|
||||
type: context.project.type,
|
||||
stack: context.stack,
|
||||
patterns: context.patterns,
|
||||
installedSkills: context.skills?.installed || [],
|
||||
excludedSkills: context.skills?.excluded || [],
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, [projectPath]);
|
||||
|
||||
const loadRecommendations = useCallback(() => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Load project profile
|
||||
const projectProfile = getProjectProfile();
|
||||
if (!projectProfile) {
|
||||
setError('Failed to analyze project');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
setProfile(projectProfile);
|
||||
|
||||
// Load skill index
|
||||
const index = loadIndex();
|
||||
if (!index || index.skills.length === 0) {
|
||||
setRecommendations([]);
|
||||
setTotalScanned(0);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
engine.loadIndex(index);
|
||||
|
||||
// Get recommendations
|
||||
const result = engine.recommend(projectProfile, {
|
||||
limit: 20,
|
||||
minScore: 20,
|
||||
excludeInstalled: true,
|
||||
includeReasons: true,
|
||||
});
|
||||
|
||||
setRecommendations(result.recommendations);
|
||||
setTotalScanned(result.totalSkillsScanned);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to get recommendations');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [engine, getProjectProfile, loadIndex]);
|
||||
|
||||
const updateIndex = useCallback(() => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
// Fetch skills from known GitHub repositories
|
||||
buildSkillIndex(KNOWN_SKILL_REPOS)
|
||||
.then(({ index, errors }) => {
|
||||
if (errors.length > 0) {
|
||||
console.warn('Index update warnings:', errors);
|
||||
}
|
||||
|
||||
// Save the fetched index
|
||||
saveIndex(index);
|
||||
setIndexStatus('fresh');
|
||||
|
||||
// Reload recommendations with new index
|
||||
loadRecommendations();
|
||||
})
|
||||
.catch((err) => {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update index');
|
||||
setLoading(false);
|
||||
});
|
||||
}, [loadRecommendations]);
|
||||
|
||||
const search = useCallback((query: string) => {
|
||||
if (!query.trim()) {
|
||||
setSearchResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const results = engine.search({
|
||||
query,
|
||||
limit: 10,
|
||||
semantic: true,
|
||||
});
|
||||
|
||||
// Convert SearchResult to ScoredSkill for consistency
|
||||
const scoredResults: ScoredSkill[] = results.map(r => ({
|
||||
skill: r.skill,
|
||||
score: r.relevance,
|
||||
reasons: r.matchedTerms.map(term => ({
|
||||
category: 'tag' as const,
|
||||
description: `Matched: ${term}`,
|
||||
weight: 0,
|
||||
matched: [term],
|
||||
})),
|
||||
warnings: [],
|
||||
}));
|
||||
|
||||
setSearchResults(scoredResults);
|
||||
}, [engine]);
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
loadRecommendations();
|
||||
}, [loadRecommendations]);
|
||||
|
||||
// Initial load
|
||||
useEffect(() => {
|
||||
loadRecommendations();
|
||||
}, [loadRecommendations]);
|
||||
|
||||
return {
|
||||
recommendations,
|
||||
profile,
|
||||
loading,
|
||||
error,
|
||||
totalScanned,
|
||||
indexStatus,
|
||||
refresh,
|
||||
updateIndex,
|
||||
search,
|
||||
searchResults,
|
||||
};
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { findAllSkills } from '@skillkit/core';
|
||||
import { getSearchDirs } from '../helpers.js';
|
||||
import type { SkillItem } from '../components/SkillList.js';
|
||||
|
||||
interface UseSkillsResult {
|
||||
skills: SkillItem[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
refresh: () => void;
|
||||
remove: (name: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function useSkills(): UseSkillsResult {
|
||||
const [skills, setSkills] = useState<SkillItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const refresh = () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const searchDirs = getSearchDirs();
|
||||
const foundSkills = findAllSkills(searchDirs);
|
||||
|
||||
const skillItems: SkillItem[] = foundSkills.map((s) => ({
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
source: s.metadata?.source,
|
||||
enabled: s.enabled,
|
||||
}));
|
||||
|
||||
setSkills(skillItems);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load skills');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (name: string) => {
|
||||
const { rmSync } = await import('node:fs');
|
||||
const foundSkill = skills.find(s => s.name === name);
|
||||
if (foundSkill) {
|
||||
const searchDirs = getSearchDirs();
|
||||
const allSkills = findAllSkills(searchDirs);
|
||||
const skill = allSkills.find(s => s.name === name);
|
||||
if (skill) {
|
||||
rmSync(skill.path, { recursive: true, force: true });
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, []);
|
||||
|
||||
return { skills, loading, error, refresh, remove };
|
||||
}
|
||||
+20
-15
@@ -1,22 +1,27 @@
|
||||
import { render } from 'ink';
|
||||
import { createCliRenderer } from '@opentui/core';
|
||||
import { createRoot } from '@opentui/react';
|
||||
import { App } from './App.js';
|
||||
|
||||
export function startTUI(): Promise<void> {
|
||||
process.stdout.write('\x1B[2J\x1B[0f');
|
||||
|
||||
const { waitUntilExit, clear } = render(<App />, {
|
||||
exitOnCtrlC: true,
|
||||
});
|
||||
|
||||
return waitUntilExit().then(() => {
|
||||
clear();
|
||||
});
|
||||
export function exitTUI(code = 0): void {
|
||||
try {
|
||||
process.stdout.write('\x1b[?1049l\x1b[?25h\x1b[0m');
|
||||
} catch {
|
||||
// Ignore write errors
|
||||
}
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
// Re-export types and components for external use
|
||||
export type { Screen } from './App.js';
|
||||
export async function startTUI(): Promise<never> {
|
||||
const renderer = await createCliRenderer({ exitOnCtrlC: true });
|
||||
const root = createRoot(renderer);
|
||||
root.render(<App onExit={exitTUI} />);
|
||||
return new Promise(() => {});
|
||||
}
|
||||
|
||||
export { type Screen } from './state/types.js';
|
||||
export { App } from './App.js';
|
||||
export * from './theme/index.js';
|
||||
export * from './state/index.js';
|
||||
export * from './utils/index.js';
|
||||
export * from './components/index.js';
|
||||
export * from './screens/index.js';
|
||||
export * from './hooks/index.js';
|
||||
export * from './theme.js';
|
||||
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Type declarations for OpenTUI React JSX elements
|
||||
* Overrides React's JSX namespace to include OpenTUI elements
|
||||
*/
|
||||
import * as React from 'react';
|
||||
|
||||
declare global {
|
||||
namespace JSX {
|
||||
interface IntrinsicElements {
|
||||
box: React.PropsWithChildren<{
|
||||
flexDirection?: 'row' | 'column';
|
||||
flexGrow?: number;
|
||||
alignItems?: 'flex-start' | 'flex-end' | 'center' | 'stretch';
|
||||
justifyContent?: 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around';
|
||||
width?: number | string;
|
||||
height?: number | string;
|
||||
padding?: number;
|
||||
paddingLeft?: number;
|
||||
paddingRight?: number;
|
||||
paddingTop?: number;
|
||||
paddingBottom?: number;
|
||||
paddingX?: number;
|
||||
paddingY?: number;
|
||||
margin?: number;
|
||||
marginLeft?: number;
|
||||
marginRight?: number;
|
||||
marginTop?: number;
|
||||
marginBottom?: number;
|
||||
marginX?: number;
|
||||
marginY?: number;
|
||||
gap?: number;
|
||||
border?: boolean;
|
||||
borderStyle?: 'single' | 'double' | 'rounded';
|
||||
borderColor?: string;
|
||||
backgroundColor?: string;
|
||||
color?: string;
|
||||
bold?: boolean;
|
||||
dim?: boolean;
|
||||
title?: string;
|
||||
style?: Record<string, unknown>;
|
||||
key?: React.Key;
|
||||
}>;
|
||||
text: React.PropsWithChildren<{
|
||||
color?: string;
|
||||
bold?: boolean;
|
||||
dim?: boolean;
|
||||
attributes?: number;
|
||||
width?: number;
|
||||
key?: React.Key;
|
||||
}>;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
+161
-201
@@ -1,222 +1,182 @@
|
||||
import { useState } from 'react';
|
||||
import { existsSync, mkdirSync, cpSync, rmSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { useMarketplace } from '../hooks/useMarketplace.js';
|
||||
import { detectProvider, type AgentType, type SkillMetadata } from '@skillkit/core';
|
||||
import { detectAgent, getAdapter, getAllAdapters } from '@skillkit/agents';
|
||||
import { getInstallDir, saveSkillMetadata } from '../helpers.js';
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { useKeyboard } from '@opentui/react';
|
||||
import { type Screen, DEFAULT_REPOS } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
|
||||
type View = 'repos' | 'skills' | 'agents';
|
||||
|
||||
interface Props {
|
||||
interface BrowseProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Browse({ rows = 24 }: Props) {
|
||||
const { repos, skills, loading, currentRepo, fetchRepo, fetchAllRepos } = useMarketplace();
|
||||
const [view, setView] = useState<View>('repos');
|
||||
const [sel, setSel] = useState(0);
|
||||
const [installing, setInstalling] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [selectedSkill, setSelectedSkill] = useState<{ name: string; source: string } | null>(null);
|
||||
const [agents, setAgents] = useState<{ type: AgentType; name: string; detected: boolean }[]>([]);
|
||||
export function Browse({ onNavigate, cols = 80, rows = 24 }: BrowseProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchMode, setSearchMode] = useState(false);
|
||||
const [animPhase, setAnimPhase] = useState(0);
|
||||
|
||||
const items = view === 'repos' ? repos : view === 'skills' ? skills : agents;
|
||||
const maxVisible = Math.max(5, rows - 8);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), items.length - maxVisible));
|
||||
const visible = items.slice(start, start + maxVisible);
|
||||
const isCompact = cols < 60;
|
||||
const contentWidth = Math.max(1, Math.min(cols - 4, 60));
|
||||
|
||||
const showAgentSelection = async (skillName: string, source: string) => {
|
||||
setSelectedSkill({ name: skillName, source });
|
||||
const adapters = getAllAdapters();
|
||||
const agentList: typeof agents = [];
|
||||
for (const a of adapters) {
|
||||
agentList.push({
|
||||
type: a.type as AgentType,
|
||||
name: a.name,
|
||||
detected: await a.isDetected(),
|
||||
});
|
||||
// Entrance animation
|
||||
useEffect(() => {
|
||||
if (animPhase >= 2) return;
|
||||
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [animPhase]);
|
||||
|
||||
const repos = useMemo(() =>
|
||||
DEFAULT_REPOS.map((r) => ({
|
||||
name: r.name,
|
||||
source: r.source,
|
||||
})),
|
||||
[]
|
||||
);
|
||||
|
||||
const filteredRepos = useMemo(() =>
|
||||
searchQuery
|
||||
? repos.filter(
|
||||
(r) =>
|
||||
r.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
r.source.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
)
|
||||
: repos,
|
||||
[repos, searchQuery]
|
||||
);
|
||||
|
||||
const handleKeyNav = useCallback((delta: number) => {
|
||||
setSelectedIndex(prev => Math.max(0, Math.min(prev + delta, filteredRepos.length - 1)));
|
||||
}, [filteredRepos.length]);
|
||||
|
||||
useKeyboard((key: { name?: string; sequence?: string }) => {
|
||||
if (searchMode) {
|
||||
if (key.name === 'escape') {
|
||||
setSearchMode(false);
|
||||
} else if (key.name === 'backspace') {
|
||||
setSearchQuery(prev => prev.slice(0, -1));
|
||||
} else if (key.name === 'return') {
|
||||
setSearchMode(false);
|
||||
} else if (key.sequence && key.sequence.length === 1 && /[a-zA-Z0-9\-_.]/.test(key.sequence)) {
|
||||
setSearchQuery(prev => prev + key.sequence);
|
||||
setSelectedIndex(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
setAgents(agentList);
|
||||
setView('agents');
|
||||
setSel(0);
|
||||
};
|
||||
|
||||
const installSkill = async (skillName: string, source: string, agentType?: AgentType) => {
|
||||
setInstalling(skillName);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
const provider = detectProvider(source);
|
||||
if (!provider) {
|
||||
setMessage(`Error: Unknown provider for ${source}`);
|
||||
setInstalling(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await provider.clone(source, '', { depth: 1 });
|
||||
|
||||
if (!result.success || !result.discoveredSkills) {
|
||||
setMessage(`Error: ${result.error || 'Failed to fetch'}`);
|
||||
setInstalling(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const skill = result.discoveredSkills.find(s => s.name === skillName);
|
||||
if (!skill) {
|
||||
setMessage(`Error: Skill ${skillName} not found`);
|
||||
setInstalling(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const targetAgentType = agentType || await detectAgent();
|
||||
const adapter = getAdapter(targetAgentType);
|
||||
const installDir = getInstallDir(false, targetAgentType);
|
||||
|
||||
if (!existsSync(installDir)) {
|
||||
mkdirSync(installDir, { recursive: true });
|
||||
}
|
||||
|
||||
const targetPath = join(installDir, skillName);
|
||||
|
||||
if (existsSync(targetPath)) {
|
||||
rmSync(targetPath, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
cpSync(skill.path, targetPath, { recursive: true, dereference: true });
|
||||
|
||||
const metadata: SkillMetadata = {
|
||||
name: skillName,
|
||||
description: '',
|
||||
source: source,
|
||||
sourceType: provider.type,
|
||||
subpath: skillName,
|
||||
installedAt: new Date().toISOString(),
|
||||
enabled: true,
|
||||
};
|
||||
saveSkillMetadata(targetPath, metadata);
|
||||
|
||||
if (result.tempRoot) {
|
||||
rmSync(result.tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
setMessage(`✓ Installed ${skillName} to ${adapter.name}`);
|
||||
if (!agentType) {
|
||||
setView('skills');
|
||||
}
|
||||
} catch (err) {
|
||||
setMessage(`Error: ${err instanceof Error ? err.message : 'Unknown error'}`);
|
||||
} finally {
|
||||
setInstalling(null);
|
||||
if (agentType) {
|
||||
setSelectedSkill(null);
|
||||
if (key.name === 'j' || key.name === 'down') handleKeyNav(1);
|
||||
else if (key.name === 'k' || key.name === 'up') handleKeyNav(-1);
|
||||
else if (key.sequence === '/') setSearchMode(true);
|
||||
else if (key.name === 'return') {
|
||||
const repo = filteredRepos[selectedIndex];
|
||||
if (repo) {
|
||||
// Open/view the selected repo (navigate to installed to see skills from this repo)
|
||||
onNavigate('installed');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || installing) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(items.length - 1, i + 1));
|
||||
else if (key.return) {
|
||||
if (view === 'repos' && repos[sel]) {
|
||||
fetchRepo(repos[sel].source);
|
||||
setView('skills');
|
||||
setSel(0);
|
||||
setMessage(null);
|
||||
} else if (view === 'skills' && skills[sel]?.source) {
|
||||
installSkill(skills[sel].name, skills[sel].source);
|
||||
} else if (view === 'agents' && agents[sel]) {
|
||||
installSkill(selectedSkill!.name, selectedSkill!.source, agents[sel].type);
|
||||
}
|
||||
}
|
||||
else if (input === 'm' && view === 'skills' && skills[sel]?.source) {
|
||||
showAgentSelection(skills[sel].name, skills[sel].source!);
|
||||
}
|
||||
else if (input === 'r') {
|
||||
if (view === 'skills') {
|
||||
setView('repos');
|
||||
setSel(0);
|
||||
setMessage(null);
|
||||
} else if (view === 'agents') {
|
||||
setView('skills');
|
||||
setSel(0);
|
||||
}
|
||||
}
|
||||
else if (input === 'a' && view === 'repos') {
|
||||
fetchAllRepos();
|
||||
setView('skills');
|
||||
setSel(0);
|
||||
}
|
||||
else if (key.name === 'escape') onNavigate('home');
|
||||
});
|
||||
|
||||
if (view === 'agents') {
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>SELECT AGENT</Text>
|
||||
<Text dimColor>Install "{selectedSkill?.name}" to which agent?</Text>
|
||||
<Text dimColor>(All agents supported - directory created if needed)</Text>
|
||||
useEffect(() => {
|
||||
if (selectedIndex >= filteredRepos.length && filteredRepos.length > 0) {
|
||||
setSelectedIndex(filteredRepos.length - 1);
|
||||
}
|
||||
}, [filteredRepos.length, selectedIndex]);
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{visible.map((agent, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
const a = agent as typeof agents[0];
|
||||
const status = a.detected ? '(ready)' : '(will create)';
|
||||
return (
|
||||
<Text key={a.type} inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {a.name.padEnd(20)} <Text color={colors.secondaryDim}>{status}</Text>
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
// Calculate visible repos
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(maxVisible / 2), filteredRepos.length - maxVisible));
|
||||
const visibleRepos = filteredRepos.slice(startIdx, startIdx + maxVisible);
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=install to selected agent r=back q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const divider = useMemo(() =>
|
||||
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
|
||||
[contentWidth]
|
||||
);
|
||||
|
||||
const shortcuts = isCompact
|
||||
? 'j/k nav enter open / search esc back'
|
||||
: 'j/k navigate enter open / search esc back';
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>{view === 'repos' ? 'REPOSITORIES' : 'SKILLS'}</Text>
|
||||
{loading && <Text dimColor>Loading {currentRepo}...</Text>}
|
||||
{installing && <Text>Installing {installing}...</Text>}
|
||||
{message && <Text dimColor>{message}</Text>}
|
||||
<Text dimColor>{items.length} items</Text>
|
||||
<box flexDirection="column" padding={1}>
|
||||
{/* Header */}
|
||||
{animPhase >= 1 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
|
||||
<text fg={terminalColors.browse}>⌕ Browse</text>
|
||||
<text fg={terminalColors.textMuted}>{filteredRepos.length} repos</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}>explore skill repositories</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((item, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
const name = view === 'repos'
|
||||
? (item as typeof repos[0]).name
|
||||
: (item as typeof skills[0]).name;
|
||||
const src = view === 'repos'
|
||||
? (item as typeof repos[0]).source
|
||||
: (item as typeof skills[0]).source || '';
|
||||
return (
|
||||
<Text key={src + name} inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '}{name.padEnd(25)} <Text color={colors.secondaryDim}>{src}</Text>
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < items.length && <Text dimColor> ↓ {items.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
{/* Search */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text> </text>
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.textMuted}>/ </text>
|
||||
<text fg={searchQuery ? terminalColors.text : terminalColors.textMuted}>
|
||||
{searchQuery || 'type to filter...'}
|
||||
</text>
|
||||
</box>
|
||||
<text> </text>
|
||||
{divider}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{view === 'repos'
|
||||
? 'Enter=fetch a=all q=quit'
|
||||
: 'Enter=quick install m=choose agent r=back q=quit'}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
{/* Repository list */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>Repositories</text>
|
||||
<text> </text>
|
||||
|
||||
{filteredRepos.length === 0 ? (
|
||||
<text fg={terminalColors.textMuted}>No repositories match your search</text>
|
||||
) : (
|
||||
<box flexDirection="column">
|
||||
{visibleRepos.map((repo, idx) => {
|
||||
const actualIdx = startIdx + idx;
|
||||
const selected = actualIdx === selectedIndex;
|
||||
const indicator = selected ? '▸' : ' ';
|
||||
// Truncate source if needed - clamp to avoid negative slicing
|
||||
const available = Math.max(0, contentWidth - repo.name.length - 6);
|
||||
const safeSlice = Math.max(0, available - 3);
|
||||
const displaySource = available > 0 && repo.source.length > available
|
||||
? repo.source.slice(0, safeSlice) + '...'
|
||||
: repo.source;
|
||||
return (
|
||||
<box key={repo.source} flexDirection="row">
|
||||
<text fg={terminalColors.text}>{indicator}</text>
|
||||
<text fg={selected ? terminalColors.accent : terminalColors.text}>
|
||||
{repo.name}
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted}> · {displaySource}</text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Scroll indicator */}
|
||||
{filteredRepos.length > maxVisible && (
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{'\n'}showing {startIdx + 1}-{Math.min(startIdx + maxVisible, filteredRepos.length)} of {filteredRepos.length}
|
||||
</text>
|
||||
)}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text fg={terminalColors.textMuted}>{shortcuts}</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,276 +1,56 @@
|
||||
/**
|
||||
* Context Screen
|
||||
* Project context analysis
|
||||
*/
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import {
|
||||
loadContext,
|
||||
initContext,
|
||||
syncToAgent,
|
||||
type ProjectContext,
|
||||
type AgentType,
|
||||
} from '@skillkit/core';
|
||||
import { getAllAdapters } from '@skillkit/agents';
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { Header } from '../components/Header.js';
|
||||
import { Spinner } from '../components/Spinner.js';
|
||||
|
||||
type View = 'overview' | 'sync';
|
||||
|
||||
interface AgentItem {
|
||||
type: AgentType;
|
||||
name: string;
|
||||
detected: boolean;
|
||||
synced?: boolean;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
interface ContextProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Context({ rows = 24 }: Props) {
|
||||
const [view, setView] = useState<View>('overview');
|
||||
const [context, setContext] = useState<ProjectContext | null>(null);
|
||||
export function Context({ onNavigate, cols = 80, rows = 24 }: ContextProps) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [initializing, setInitializing] = useState(false);
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const [agents, setAgents] = useState<AgentItem[]>([]);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const projectPath = process.cwd();
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const ctx = loadContext(projectPath);
|
||||
setContext(ctx);
|
||||
const timer = setTimeout(() => setLoading(false), 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
const adapters = getAllAdapters();
|
||||
const agentList: AgentItem[] = [];
|
||||
for (const a of adapters) {
|
||||
const detected = await a.isDetected();
|
||||
agentList.push({
|
||||
type: a.type as AgentType,
|
||||
name: a.name,
|
||||
detected,
|
||||
synced: ctx?.agents?.synced?.includes(a.type),
|
||||
});
|
||||
}
|
||||
setAgents(agentList);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load context');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
load();
|
||||
}, [projectPath]);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 14);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), agents.length - maxVisible));
|
||||
const visible = agents.slice(start, start + maxVisible);
|
||||
|
||||
const handleInit = () => {
|
||||
setInitializing(true);
|
||||
setMessage(null);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const newContext = initContext(projectPath);
|
||||
setContext(newContext);
|
||||
setMessage('Context initialized successfully');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to initialize context');
|
||||
} finally {
|
||||
setInitializing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSync = async (agentType: AgentType) => {
|
||||
setSyncing(true);
|
||||
setMessage(null);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await syncToAgent(agentType, projectPath);
|
||||
|
||||
setAgents(prev =>
|
||||
prev.map(a =>
|
||||
a.type === agentType ? { ...a, synced: true } : a
|
||||
)
|
||||
);
|
||||
|
||||
setMessage(`Synced to ${agentType} successfully`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Sync failed');
|
||||
} finally {
|
||||
setSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSyncAll = async () => {
|
||||
setSyncing(true);
|
||||
setMessage(null);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const detectedAgents = agents.filter(a => a.detected);
|
||||
for (const agent of detectedAgents) {
|
||||
await syncToAgent(agent.type, projectPath);
|
||||
}
|
||||
|
||||
setAgents(prev =>
|
||||
prev.map(a =>
|
||||
a.detected ? { ...a, synced: true } : a
|
||||
)
|
||||
);
|
||||
|
||||
setMessage(`Synced to ${detectedAgents.length} agents`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Sync failed');
|
||||
} finally {
|
||||
setSyncing(false);
|
||||
}
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || initializing || syncing) return;
|
||||
|
||||
if (view === 'sync') {
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(agents.length - 1, i + 1));
|
||||
else if (key.return && agents[sel]) {
|
||||
handleSync(agents[sel].type);
|
||||
}
|
||||
else if (key.escape) {
|
||||
setView('overview');
|
||||
setSel(0);
|
||||
}
|
||||
else if (input === 'a') {
|
||||
handleSyncAll();
|
||||
}
|
||||
} else if (view === 'overview') {
|
||||
if (input === 'i') handleInit();
|
||||
else if (input === 's') {
|
||||
setView('sync');
|
||||
setSel(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>PROJECT CONTEXT</Text>
|
||||
<Text dimColor>Loading...</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (view === 'sync') {
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>SYNC TO AGENTS</Text>
|
||||
<Text dimColor>Select an agent to sync your project context</Text>
|
||||
|
||||
{message && <Text color="green">{'✓'} {message}</Text>}
|
||||
{error && <Text color="red">{'✗'} {error}</Text>}
|
||||
{syncing && <Text dimColor>Syncing...</Text>}
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((agent, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
const status = agent.synced
|
||||
? '(synced)'
|
||||
: agent.detected
|
||||
? '(ready)'
|
||||
: '(not detected)';
|
||||
const statusColor = agent.synced ? 'green' : agent.detected ? 'yellow' : 'gray';
|
||||
|
||||
return (
|
||||
<Text key={agent.type} inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {agent.name.padEnd(20)}
|
||||
<Text color={statusColor}>{status}</Text>
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < agents.length && (
|
||||
<Text dimColor> ↓ {agents.length - start - maxVisible} more</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=sync to agent a=sync all detected Esc=back q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const stack = context?.stack;
|
||||
const detectedCount = agents.filter(a => a.detected).length;
|
||||
const syncedCount = agents.filter(a => a.synced).length;
|
||||
const contextInfo = [
|
||||
{ label: 'Working Directory', value: process.cwd() },
|
||||
{ label: 'Node Version', value: process.version },
|
||||
{ label: 'Platform', value: process.platform },
|
||||
{ label: 'Architecture', value: process.arch },
|
||||
];
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>PROJECT CONTEXT</Text>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<Header
|
||||
title="Project Context"
|
||||
subtitle="Analyze your project environment"
|
||||
icon="◉"
|
||||
/>
|
||||
|
||||
{message && <Text color="green">{'✓'} {message}</Text>}
|
||||
{error && <Text color="red">{'✗'} {error}</Text>}
|
||||
{initializing && <Text dimColor>Initializing...</Text>}
|
||||
|
||||
{!context && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text color="yellow">No context found.</Text>
|
||||
<Text dimColor>Press 'i' to initialize and analyze your project.</Text>
|
||||
</Box>
|
||||
{loading ? (
|
||||
<Spinner label="Analyzing project context..." />
|
||||
) : (
|
||||
<box flexDirection="column">
|
||||
{contextInfo.map((info) => (
|
||||
<box key={info.label} flexDirection="row" marginBottom={1}>
|
||||
<text fg={terminalColors.textMuted} width={20}>
|
||||
{info.label}:
|
||||
</text>
|
||||
<text fg={terminalColors.text}>{info.value}</text>
|
||||
</box>
|
||||
))}
|
||||
</box>
|
||||
)}
|
||||
|
||||
{context && (
|
||||
<>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text bold>Project:</Text>
|
||||
<Text> Name: {context.project?.name || 'Unknown'}</Text>
|
||||
<Text> Type: {context.project?.type || 'Not detected'}</Text>
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text bold>Stack:</Text>
|
||||
{stack?.languages && stack.languages.length > 0 && (
|
||||
<Text> Languages: {stack.languages.map(l => l.name).join(', ')}</Text>
|
||||
)}
|
||||
{stack?.frameworks && stack.frameworks.length > 0 && (
|
||||
<Text> Frameworks: {stack.frameworks.map(f => f.name).join(', ')}</Text>
|
||||
)}
|
||||
{stack?.libraries && stack.libraries.length > 0 && (
|
||||
<Text> Libraries: {stack.libraries.slice(0, 5).map(l => l.name).join(', ')}{stack.libraries.length > 5 ? '...' : ''}</Text>
|
||||
)}
|
||||
{(!stack?.languages?.length && !stack?.frameworks?.length) && (
|
||||
<Text dimColor> No stack detected. Press 'i' to re-analyze.</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text bold>Agents:</Text>
|
||||
<Text> Detected: {detectedCount} agents</Text>
|
||||
<Text> Synced: {syncedCount} agents</Text>
|
||||
{detectedCount > 0 && (
|
||||
<Text dimColor> ({agents.filter(a => a.detected).map(a => a.name).join(', ')})</Text>
|
||||
)}
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text bold>Actions:</Text>
|
||||
<Text dimColor> [i] Initialize/refresh context</Text>
|
||||
<Text dimColor> [s] Sync to agents</Text>
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>i=init context s=sync to agents q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,131 +1,53 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { createSessionManager, type SessionState, type CurrentExecution } from '@skillkit/core';
|
||||
/**
|
||||
* Execute Screen
|
||||
* Live skill execution
|
||||
*/
|
||||
import { useState } from 'react';
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { Header } from '../components/Header.js';
|
||||
import { Spinner } from '../components/Spinner.js';
|
||||
import { ProgressBar } from '../components/ProgressBar.js';
|
||||
|
||||
interface Props {
|
||||
interface ExecuteProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Execute({ rows = 24 }: Props) {
|
||||
const [session, setSession] = useState<SessionState | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
|
||||
useEffect(() => {
|
||||
loadSession();
|
||||
// Poll for updates
|
||||
const interval = setInterval(loadSession, 1000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const loadSession = () => {
|
||||
try {
|
||||
const manager = createSessionManager(process.cwd());
|
||||
const state = manager.get();
|
||||
setSession(state);
|
||||
} catch {
|
||||
setSession(null);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useInput((input, _key) => {
|
||||
if (input === 'r') loadSession();
|
||||
else if (input === 'p' && session?.currentExecution?.status === 'running') {
|
||||
const manager = createSessionManager(process.cwd());
|
||||
manager.pause();
|
||||
loadSession();
|
||||
}
|
||||
else if (input === 'c' && session?.currentExecution?.status === 'paused') {
|
||||
const manager = createSessionManager(process.cwd());
|
||||
manager.resume();
|
||||
loadSession();
|
||||
}
|
||||
});
|
||||
|
||||
const renderExecution = (exec: CurrentExecution) => {
|
||||
const completedTasks = exec.tasks.filter(t => t.status === 'completed').length;
|
||||
const failedTasks = exec.tasks.filter(t => t.status === 'failed').length;
|
||||
const progress = exec.totalSteps > 0 ? Math.round((completedTasks / exec.totalSteps) * 100) : 0;
|
||||
|
||||
const statusColor = exec.status === 'running' ? 'yellow' :
|
||||
exec.status === 'completed' ? 'green' :
|
||||
exec.status === 'paused' ? 'blue' :
|
||||
exec.status === 'failed' ? 'red' : 'white';
|
||||
|
||||
const visibleTasks = exec.tasks.slice(0, maxVisible);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text bold>{exec.skillName}</Text>
|
||||
<Text>Source: <Text dimColor>{exec.skillSource}</Text></Text>
|
||||
<Text>Status: <Text color={statusColor}>{exec.status.toUpperCase()}</Text></Text>
|
||||
<Text>Progress: {completedTasks}/{exec.totalSteps} ({progress}%)</Text>
|
||||
|
||||
{/* Progress bar */}
|
||||
<Box marginY={1}>
|
||||
<Text>[</Text>
|
||||
<Text color="green">{'█'.repeat(Math.floor(progress / 5))}</Text>
|
||||
<Text dimColor>{'░'.repeat(20 - Math.floor(progress / 5))}</Text>
|
||||
<Text>]</Text>
|
||||
</Box>
|
||||
|
||||
{/* Task list */}
|
||||
<Text bold>Tasks:</Text>
|
||||
{visibleTasks.map((task, i) => {
|
||||
const icon = task.status === 'completed' ? symbols.success :
|
||||
task.status === 'failed' ? symbols.error :
|
||||
task.status === 'in_progress' ? symbols.warning :
|
||||
task.status === 'paused' ? symbols.info :
|
||||
symbols.bullet;
|
||||
const color = task.status === 'completed' ? 'green' :
|
||||
task.status === 'failed' ? 'red' :
|
||||
task.status === 'in_progress' ? 'yellow' :
|
||||
task.status === 'paused' ? 'blue' : 'white';
|
||||
return (
|
||||
<Text key={task.id || i} color={color}>
|
||||
{icon} {task.name} {task.error && <Text dimColor>({task.error})</Text>}
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
{exec.tasks.length > maxVisible && (
|
||||
<Text dimColor> ... and {exec.tasks.length - maxVisible} more</Text>
|
||||
)}
|
||||
|
||||
{failedTasks > 0 && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red">{failedTasks} task(s) failed</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
export function Execute({ onNavigate, cols = 80, rows = 24 }: ExecuteProps) {
|
||||
const [executing, setExecuting] = useState(false);
|
||||
const [progress, setProgress] = useState(0);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>EXECUTION MONITOR</Text>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<Header
|
||||
title="Execute"
|
||||
subtitle="Run skills in real-time"
|
||||
icon="▶"
|
||||
/>
|
||||
|
||||
{loading && <Text>Loading session...</Text>}
|
||||
|
||||
{!loading && !session?.currentExecution && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>No active execution.</Text>
|
||||
<Text dimColor>Run a skill with: skillkit run {'<skill>'}</Text>
|
||||
</Box>
|
||||
{executing ? (
|
||||
<box flexDirection="column">
|
||||
<Spinner label="Executing skill..." />
|
||||
<text> </text>
|
||||
<ProgressBar progress={progress} width={40} />
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>Press Esc to cancel</text>
|
||||
</box>
|
||||
) : (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>Select a skill to execute:</text>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
No skills available. Install skills first using 'b' (browse) or 'm' (marketplace).
|
||||
</text>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
Press Enter to execute, 'i' to view installed skills
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{!loading && session?.currentExecution && renderExecution(session.currentExecution)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{session?.currentExecution?.status === 'running' ? 'p=pause ' : ''}
|
||||
{session?.currentExecution?.status === 'paused' ? 'c=continue ' : ''}
|
||||
r=refresh q=quit
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { getVersion } from '../utils/helpers.js';
|
||||
|
||||
interface HelpProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
const SHORTCUTS = [
|
||||
{ section: 'Navigation', items: [
|
||||
{ key: 'h', desc: 'Home screen' },
|
||||
{ key: 'b', desc: 'Browse skills' },
|
||||
{ key: 'm', desc: 'Marketplace' },
|
||||
{ key: 'r', desc: 'Recommendations' },
|
||||
{ key: 'i', desc: 'Installed skills' },
|
||||
{ key: 's', desc: 'Sync settings' },
|
||||
]},
|
||||
{ section: 'Actions', items: [
|
||||
{ key: 't', desc: 'Translate skills' },
|
||||
{ key: 'w', desc: 'Workflows' },
|
||||
{ key: 'x', desc: 'Execute' },
|
||||
{ key: 'n', desc: 'Plan' },
|
||||
{ key: 'y', desc: 'History' },
|
||||
]},
|
||||
{ section: 'Team & Config', items: [
|
||||
{ key: 'a', desc: 'Team settings' },
|
||||
{ key: 'c', desc: 'Context' },
|
||||
{ key: 'e', desc: 'Memory' },
|
||||
{ key: 'p', desc: 'Plugins' },
|
||||
{ key: 'o', desc: 'Methodology' },
|
||||
{ key: ',', desc: 'Settings' },
|
||||
]},
|
||||
{ section: 'Global', items: [
|
||||
{ key: '/', desc: 'This help screen' },
|
||||
{ key: 'esc', desc: 'Go back / Home' },
|
||||
{ key: 'q', desc: 'Quit application' },
|
||||
{ key: 'j/k', desc: 'Navigate lists' },
|
||||
{ key: 'enter', desc: 'Select item' },
|
||||
]},
|
||||
];
|
||||
|
||||
function ShortcutSection({ section, items, isLast }: { section: string; items: { key: string; desc: string }[]; isLast: boolean }) {
|
||||
return (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>{section}</text>
|
||||
{items.map((item) => (
|
||||
<box key={item.key} flexDirection="row">
|
||||
<text fg={terminalColors.accent} width={8}> {item.key}</text>
|
||||
<text fg={terminalColors.textMuted}>{item.desc}</text>
|
||||
</box>
|
||||
))}
|
||||
{!isLast && <text> </text>}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
export function Help({ cols = 80 }: HelpProps) {
|
||||
const [animPhase, setAnimPhase] = useState(0);
|
||||
const isCompact = cols < 60;
|
||||
const rawWidth = cols - 4;
|
||||
const contentWidth = Math.max(1, Math.min(rawWidth, 60));
|
||||
const version = getVersion();
|
||||
|
||||
useEffect(() => {
|
||||
if (animPhase >= 2) return;
|
||||
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [animPhase]);
|
||||
|
||||
const divider = useMemo(() =>
|
||||
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
|
||||
[contentWidth]
|
||||
);
|
||||
|
||||
return (
|
||||
<box flexDirection="column" padding={1}>
|
||||
{animPhase >= 1 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
|
||||
<text fg={terminalColors.text}>/ Help</text>
|
||||
<text fg={terminalColors.textMuted}>skillkit v{version}</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}>keyboard shortcuts and navigation</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text> </text>
|
||||
{isCompact ? (
|
||||
SHORTCUTS.map((s, idx) => (
|
||||
<ShortcutSection key={s.section} section={s.section} items={s.items} isLast={idx === SHORTCUTS.length - 1} />
|
||||
))
|
||||
) : (
|
||||
<box flexDirection="row">
|
||||
<box flexDirection="column" width={Math.floor(contentWidth / 2)}>
|
||||
{SHORTCUTS.slice(0, 2).map((s, idx) => (
|
||||
<ShortcutSection key={s.section} section={s.section} items={s.items} isLast={idx === 1} />
|
||||
))}
|
||||
</box>
|
||||
<box flexDirection="column" width={Math.floor(contentWidth / 2)}>
|
||||
{SHORTCUTS.slice(2).map((s, idx) => (
|
||||
<ShortcutSection key={s.section} section={s.section} items={s.items} isLast={idx === 1} />
|
||||
))}
|
||||
</box>
|
||||
</box>
|
||||
)}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text fg={terminalColors.textMuted}>esc back h home q quit</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
@@ -1,127 +1,59 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { createSessionManager, type ExecutionHistory } from '@skillkit/core';
|
||||
/**
|
||||
* History Screen
|
||||
* Execution history
|
||||
*/
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { Header } from '../components/Header.js';
|
||||
|
||||
interface Props {
|
||||
interface HistoryProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function History({ rows = 24 }: Props) {
|
||||
const [history, setHistory] = useState<ExecutionHistory[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 8);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), history.length - maxVisible));
|
||||
const visible = history.slice(start, start + maxVisible);
|
||||
|
||||
useEffect(() => {
|
||||
loadHistory();
|
||||
}, []);
|
||||
|
||||
const loadHistory = () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const manager = createSessionManager(process.cwd());
|
||||
const h = manager.getHistory(50);
|
||||
setHistory(h);
|
||||
} catch {
|
||||
setHistory([]);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading) return;
|
||||
|
||||
if (key.upArrow) {
|
||||
setSel(i => Math.max(0, i - 1));
|
||||
setExpanded(false);
|
||||
}
|
||||
else if (key.downArrow) {
|
||||
setSel(i => Math.min(history.length - 1, i + 1));
|
||||
setExpanded(false);
|
||||
}
|
||||
else if (input === 'r') loadHistory();
|
||||
else if (key.return) setExpanded(e => !e);
|
||||
});
|
||||
|
||||
const formatDuration = (ms: number): string => {
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
|
||||
return `${(ms / 60000).toFixed(1)}m`;
|
||||
};
|
||||
|
||||
const formatDate = (iso: string): string => {
|
||||
const d = new Date(iso);
|
||||
const now = new Date();
|
||||
const diff = now.getTime() - d.getTime();
|
||||
|
||||
if (diff < 60000) return 'Just now';
|
||||
if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
|
||||
if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
|
||||
return d.toLocaleDateString();
|
||||
};
|
||||
export function History({ onNavigate, cols = 80, rows = 24 }: HistoryProps) {
|
||||
const history = [
|
||||
{ skill: 'tdd-workflow', time: '10:32 AM', duration: '2.3s', status: 'success' },
|
||||
{ skill: 'code-review', time: '10:15 AM', duration: '5.1s', status: 'success' },
|
||||
{ skill: 'deploy-check', time: '09:45 AM', duration: '8.7s', status: 'failed' },
|
||||
{ skill: 'lint-fix', time: '09:30 AM', duration: '1.2s', status: 'success' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>EXECUTION HISTORY</Text>
|
||||
<Text dimColor>{history.length} execution(s)</Text>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<Header
|
||||
title="History"
|
||||
subtitle="View execution history"
|
||||
count={history.length}
|
||||
icon="◷"
|
||||
/>
|
||||
|
||||
{loading && <Text>Loading history...</Text>}
|
||||
<text fg={terminalColors.text}><b>Recent Executions</b></text>
|
||||
<text> </text>
|
||||
|
||||
{!loading && history.length === 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>No execution history.</Text>
|
||||
<Text dimColor>Run a skill with: skillkit run {'<skill>'}</Text>
|
||||
</Box>
|
||||
)}
|
||||
{history.map((item, idx) => (
|
||||
<box key={`${item.skill}-${item.time}`} flexDirection="row" marginBottom={1}>
|
||||
<text
|
||||
fg={idx === 0 ? terminalColors.accent : terminalColors.text}
|
||||
width={18}
|
||||
>
|
||||
{idx === 0 ? '\u25B8 ' : ' '}{item.skill}
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted} width={12}>{item.time}</text>
|
||||
<text fg={terminalColors.textMuted} width={10}>{item.duration}</text>
|
||||
<text
|
||||
fg={item.status === 'success' ? terminalColors.success : terminalColors.error}
|
||||
>
|
||||
{item.status === 'success' ? '\u2713 success' : '\u2717 failed'}
|
||||
</text>
|
||||
</box>
|
||||
))}
|
||||
|
||||
{!loading && history.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((entry, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
const icon = entry.status === 'completed' ? symbols.success :
|
||||
entry.status === 'failed' ? symbols.error :
|
||||
symbols.warning;
|
||||
const color = entry.status === 'completed' ? 'green' :
|
||||
entry.status === 'failed' ? 'red' : 'yellow';
|
||||
|
||||
return (
|
||||
<Box key={idx} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '}<Text color={color}>{icon}</Text> {entry.skillName.padEnd(25)} {formatDate(entry.completedAt).padEnd(12)} {formatDuration(entry.durationMs)}
|
||||
</Text>
|
||||
{isSel && expanded && (
|
||||
<Box flexDirection="column" marginLeft={3}>
|
||||
<Text dimColor>Source: {entry.skillSource}</Text>
|
||||
<Text dimColor>Status: {entry.status}</Text>
|
||||
{entry.commits.length > 0 && (
|
||||
<Text dimColor>Commits: {entry.commits.join(', ')}</Text>
|
||||
)}
|
||||
{entry.filesModified.length > 0 && (
|
||||
<Text dimColor>Files: {entry.filesModified.length} modified</Text>
|
||||
)}
|
||||
{entry.error && (
|
||||
<Text color="red">Error: {entry.error}</Text>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < history.length && <Text dimColor> ↓ {history.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=expand r=refresh q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
Press Enter to view details, 'r' to re-run, 'c' to clear
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { Box, Text } from 'ink';
|
||||
import { colors, logo } from '../theme.js';
|
||||
import type { Screen } from '../App.js';
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { type Screen, loadSkills, TOTAL_AGENTS } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { symbols, AGENT_LOGOS } from '../theme/symbols.js';
|
||||
import { getVersion } from '../utils/helpers.js';
|
||||
|
||||
interface HomeProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
@@ -12,89 +10,146 @@ interface HomeProps {
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
const CHARS = '01█▓▒░╔╗╚╝║═';
|
||||
const FEATURES = [
|
||||
{ key: 'Sync', color: terminalColors.sync, desc: 'share across agents' },
|
||||
{ key: 'Browse', color: terminalColors.browse, desc: 'discover skills' },
|
||||
{ key: 'Recommend', color: terminalColors.recommend, desc: 'AI suggestions' },
|
||||
{ key: 'Translate', color: terminalColors.translate, desc: 'convert formats' },
|
||||
{ key: 'Workflow', color: terminalColors.workflow, desc: 'automate chains' },
|
||||
{ key: 'Team', color: terminalColors.text, desc: 'collaborate' },
|
||||
];
|
||||
|
||||
const logoSmall = `
|
||||
╔═╗╦╔═╦╦ ╦ ╦╔═╦╔╦╗
|
||||
╚═╗╠╩╗║║ ║ ╠╩╗║ ║
|
||||
╚═╝╩ ╩╩╩═╝╩═╝╩ ╩╩ ╩
|
||||
`.trim();
|
||||
export function Home({ cols = 80 }: HomeProps) {
|
||||
const [animPhase, setAnimPhase] = useState(0);
|
||||
const [stats, setStats] = useState({ skills: 0, agents: TOTAL_AGENTS, synced: 0 });
|
||||
const [detectedAgents, setDetectedAgents] = useState<string[]>([]);
|
||||
|
||||
function getVersion(): string {
|
||||
try {
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const packageJsonPath = join(__dirname, '../../../package.json');
|
||||
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
|
||||
return packageJson.version || '1.2.0';
|
||||
} catch {
|
||||
return '1.2.0';
|
||||
}
|
||||
}
|
||||
|
||||
function scramble(target: string, progress: number): string {
|
||||
return target.split('\n').map(line => {
|
||||
return line.split('').map((char, i) => {
|
||||
if (char === ' ') return char;
|
||||
if (progress > (i / line.length) * 100) return char;
|
||||
return CHARS[Math.floor(Math.random() * CHARS.length)];
|
||||
}).join('');
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
export function Home({ cols = 80, rows = 24 }: HomeProps) {
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [display, setDisplay] = useState('');
|
||||
const version = getVersion();
|
||||
|
||||
const useLogo = cols < 80 ? logoSmall : logo;
|
||||
const isCompact = cols < 70;
|
||||
const isNarrow = cols < 50;
|
||||
const contentWidth = Math.min(cols - 4, 55);
|
||||
const line = '─'.repeat(contentWidth);
|
||||
|
||||
useEffect(() => {
|
||||
if (progress >= 100) {
|
||||
setDisplay(useLogo);
|
||||
return;
|
||||
}
|
||||
const t = setInterval(() => {
|
||||
setProgress(p => {
|
||||
const next = p + 12;
|
||||
setDisplay(scramble(useLogo, next));
|
||||
return next;
|
||||
});
|
||||
}, 35);
|
||||
return () => clearInterval(t);
|
||||
}, [progress, useLogo]);
|
||||
if (animPhase >= 5) return;
|
||||
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [animPhase]);
|
||||
|
||||
useEffect(() => {
|
||||
const skillsData = loadSkills();
|
||||
setStats({
|
||||
skills: skillsData.skills.length,
|
||||
agents: TOTAL_AGENTS,
|
||||
synced: Math.min(skillsData.skills.length, 3),
|
||||
});
|
||||
setDetectedAgents(['claude-code', 'cursor', 'github-copilot']);
|
||||
}, []);
|
||||
|
||||
const visibleAgents = useMemo(() => {
|
||||
const allAgents = Object.entries(AGENT_LOGOS);
|
||||
const perRow = isNarrow || isCompact ? 2 : 3;
|
||||
const maxAgents = isNarrow ? 4 : isCompact ? 6 : 9;
|
||||
return {
|
||||
agents: allAgents.slice(0, maxAgents),
|
||||
perRow,
|
||||
remaining: allAgents.length - maxAgents,
|
||||
};
|
||||
}, [isCompact, isNarrow]);
|
||||
|
||||
const getAgentWidth = () => {
|
||||
if (isNarrow) return 22;
|
||||
if (isCompact) return 26;
|
||||
return 18;
|
||||
};
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text color={colors.primary}>{display || useLogo}</Text>
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text>Manage AI agent skills from your terminal.</Text>
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text bold>Quick Actions:</Text>
|
||||
<Text dimColor> [b] Browse skills marketplace</Text>
|
||||
<Text dimColor> [r] Get smart recommendations</Text>
|
||||
<Text dimColor> [t] Translate skills between agents</Text>
|
||||
<Text dimColor> [c] Manage project context</Text>
|
||||
<Text dimColor> [l] View installed skills</Text>
|
||||
<Text dimColor> [s] Sync skills across agents</Text>
|
||||
</Box>
|
||||
|
||||
{rows >= 18 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text bold>Navigation:</Text>
|
||||
<Text dimColor> ↑↓ Navigate lists</Text>
|
||||
<Text dimColor> Enter Select / Confirm</Text>
|
||||
<Text dimColor> Esc Go back / Home</Text>
|
||||
<Text dimColor> q Quit</Text>
|
||||
</Box>
|
||||
<box flexDirection="column" padding={1}>
|
||||
{animPhase >= 1 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.text}>{symbols.brandIcon} skillkit</text>
|
||||
<text fg={terminalColors.textMuted}> v{version}</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}>universal skills for ai coding agents</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>v{version} - Works with 17 AI agents</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.textMuted}>{line}</text>
|
||||
<text> </text>
|
||||
<box flexDirection="row">
|
||||
<box width={14}><text fg={terminalColors.accent}>{stats.skills}</text></box>
|
||||
<box width={14}><text fg={terminalColors.text}>{stats.agents}</text></box>
|
||||
<box width={14}><text fg={terminalColors.text}>{stats.synced}</text></box>
|
||||
</box>
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.textMuted} width={14}>skills</text>
|
||||
<text fg={terminalColors.textMuted} width={14}>agents</text>
|
||||
<text fg={terminalColors.textMuted} width={14}>synced</text>
|
||||
</box>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>{line}</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{animPhase >= 3 && (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>Works with</text>
|
||||
<text> </text>
|
||||
{Array(Math.ceil(visibleAgents.agents.length / visibleAgents.perRow))
|
||||
.fill(0)
|
||||
.map((_, rowIdx) => (
|
||||
<box key={rowIdx} flexDirection="row">
|
||||
{visibleAgents.agents
|
||||
.slice(rowIdx * visibleAgents.perRow, (rowIdx + 1) * visibleAgents.perRow)
|
||||
.map(([type, agent]) => {
|
||||
const isDetected = detectedAgents.includes(type);
|
||||
return (
|
||||
<box key={type} width={getAgentWidth()} flexDirection="row">
|
||||
<text fg={terminalColors.text}>{agent.icon} {agent.name} </text>
|
||||
<text fg={isDetected ? terminalColors.accent : terminalColors.textMuted}>
|
||||
{isDetected ? '●' : '○'}
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
</box>
|
||||
))}
|
||||
{visibleAgents.remaining > 0 && (
|
||||
<text fg={terminalColors.textMuted}>+{visibleAgents.remaining} more</text>
|
||||
)}
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>{line}</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{animPhase >= 4 && (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>Features</text>
|
||||
<text> </text>
|
||||
{FEATURES.map((feat) => (
|
||||
<box key={feat.key} flexDirection="row">
|
||||
<text fg={feat.color} width={12}> {feat.key}</text>
|
||||
<text fg={terminalColors.textMuted}>{feat.desc}</text>
|
||||
</box>
|
||||
))}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{animPhase >= 5 && (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.textMuted}>{line}</text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{isCompact ? 'b browse m market / help q quit' : 'b browse m market i installed / help q quit'}
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,59 +1,224 @@
|
||||
import { useState } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { useSkills } from '../hooks/useSkills.js';
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { useKeyboard } from '@opentui/react';
|
||||
import { type Screen, loadSkills, filterSkills } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
|
||||
interface Props {
|
||||
interface InstalledProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Installed({ rows = 24 }: Props) {
|
||||
const { skills, loading, refresh, remove } = useSkills();
|
||||
const [sel, setSel] = useState(0);
|
||||
const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
||||
|
||||
const maxVisible = Math.max(5, rows - 6);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), skills.length - maxVisible));
|
||||
const visible = skills.slice(start, start + maxVisible);
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading) return;
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(skills.length - 1, i + 1));
|
||||
else if (input === 'r') refresh();
|
||||
else if (input === 'd' && skills[sel]) remove(skills[sel].name);
|
||||
export function Installed({ onNavigate, cols = 80, rows = 24 }: InstalledProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchMode, setSearchMode] = useState(false);
|
||||
const [animPhase, setAnimPhase] = useState(0);
|
||||
const [spinnerFrame, setSpinnerFrame] = useState(0);
|
||||
const [skills, setSkills] = useState<ReturnType<typeof loadSkills>>({
|
||||
skills: [],
|
||||
loading: true,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const isCompact = cols < 60;
|
||||
const contentWidth = Math.max(1, Math.min(cols - 4, 60));
|
||||
|
||||
// Entrance animation
|
||||
useEffect(() => {
|
||||
if (animPhase >= 2) return;
|
||||
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [animPhase]);
|
||||
|
||||
// Loading spinner
|
||||
useEffect(() => {
|
||||
if (!skills.loading) return;
|
||||
const interval = setInterval(() => {
|
||||
setSpinnerFrame(f => (f + 1) % SPINNER.length);
|
||||
}, 80);
|
||||
return () => clearInterval(interval);
|
||||
}, [skills.loading]);
|
||||
|
||||
// Load skills
|
||||
useEffect(() => {
|
||||
const data = loadSkills();
|
||||
setSkills(data);
|
||||
}, []);
|
||||
|
||||
const filteredSkills = useMemo(() =>
|
||||
filterSkills(skills.skills, searchQuery),
|
||||
[skills.skills, searchQuery]
|
||||
);
|
||||
|
||||
const handleKeyNav = useCallback((delta: number) => {
|
||||
setSelectedIndex(prev => Math.max(0, Math.min(prev + delta, filteredSkills.length - 1)));
|
||||
}, [filteredSkills.length]);
|
||||
|
||||
const handleToggle = useCallback(() => {
|
||||
if (filteredSkills.length === 0) return;
|
||||
const skill = filteredSkills[selectedIndex];
|
||||
if (skill) {
|
||||
setSkills(prev => ({
|
||||
...prev,
|
||||
skills: prev.skills.map(s =>
|
||||
s.name === skill.name ? { ...s, enabled: s.enabled === false } : s
|
||||
),
|
||||
}));
|
||||
}
|
||||
}, [filteredSkills, selectedIndex]);
|
||||
|
||||
const handleKeyboard = useCallback((key: { name?: string; sequence?: string }) => {
|
||||
if (searchMode) {
|
||||
if (key.name === 'escape') {
|
||||
setSearchMode(false);
|
||||
} else if (key.name === 'backspace') {
|
||||
setSearchQuery(prev => prev.slice(0, -1));
|
||||
} else if (key.name === 'return') {
|
||||
setSearchMode(false);
|
||||
} else if (key.sequence && key.sequence.length === 1 && /[a-zA-Z0-9\-_.]/.test(key.sequence)) {
|
||||
setSearchQuery(prev => prev + key.sequence);
|
||||
setSelectedIndex(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.name === 'j' || key.name === 'down') handleKeyNav(1);
|
||||
else if (key.name === 'k' || key.name === 'up') handleKeyNav(-1);
|
||||
else if (key.sequence === '/') setSearchMode(true);
|
||||
else if (key.name === 'return') handleToggle();
|
||||
else if (key.name === 'd') handleToggle();
|
||||
else if (key.name === 'escape') onNavigate('home');
|
||||
}, [searchMode, handleKeyNav, handleToggle, onNavigate]);
|
||||
|
||||
useKeyboard(handleKeyboard);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedIndex >= filteredSkills.length && filteredSkills.length > 0) {
|
||||
setSelectedIndex(filteredSkills.length - 1);
|
||||
}
|
||||
}, [filteredSkills.length, selectedIndex]);
|
||||
|
||||
// Calculate visible items
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(maxVisible / 2), filteredSkills.length - maxVisible));
|
||||
const visibleSkills = filteredSkills.slice(startIdx, startIdx + maxVisible);
|
||||
|
||||
const divider = useMemo(() =>
|
||||
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
|
||||
[contentWidth]
|
||||
);
|
||||
|
||||
// Stats
|
||||
const enabledCount = skills.skills.filter(s => s.enabled !== false).length;
|
||||
const totalCount = skills.skills.length;
|
||||
|
||||
const shortcuts = isCompact
|
||||
? 'j/k nav enter toggle d disable esc back'
|
||||
: 'j/k navigate enter toggle d disable esc back';
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>INSTALLED SKILLS</Text>
|
||||
<Text dimColor>{skills.length} skills</Text>
|
||||
|
||||
{loading && <Text>Loading...</Text>}
|
||||
|
||||
{!loading && skills.length === 0 && (
|
||||
<Text dimColor>No skills installed. Press b to browse.</Text>
|
||||
<box flexDirection="column" padding={1}>
|
||||
{/* Header */}
|
||||
{animPhase >= 1 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
|
||||
<text fg={terminalColors.success}>✓ Installed</text>
|
||||
<text fg={terminalColors.textMuted}>{enabledCount}/{totalCount} active</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}>manage your skills</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{!loading && skills.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((skill, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
return (
|
||||
<Text key={skill.name} inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '}{skill.name.padEnd(30)} {skill.source && <Text color={colors.secondaryDim}>{skill.source}</Text>}
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < skills.length && <Text dimColor> ↓ {skills.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
{/* Search */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text> </text>
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.textMuted}>/ </text>
|
||||
<text fg={searchQuery ? terminalColors.text : terminalColors.textMuted}>
|
||||
{searchQuery || 'type to filter...'}
|
||||
</text>
|
||||
</box>
|
||||
<text> </text>
|
||||
{divider}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>r=refresh d=delete q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
{/* Skills list */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{skills.loading ? (
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.accent}>{SPINNER[spinnerFrame]} </text>
|
||||
<text fg={terminalColors.text}>Loading skills...</text>
|
||||
</box>
|
||||
) : skills.error ? (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.error}>✗ Error loading skills</text>
|
||||
<text fg={terminalColors.textMuted}>{skills.error}</text>
|
||||
</box>
|
||||
) : filteredSkills.length === 0 ? (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{skills.skills.length === 0
|
||||
? 'No skills installed yet'
|
||||
: 'No skills match your search'}
|
||||
</text>
|
||||
{skills.skills.length === 0 && (
|
||||
<>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
Press 'b' to browse or 'm' for marketplace
|
||||
</text>
|
||||
</>
|
||||
)}
|
||||
</box>
|
||||
) : (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>Skills</text>
|
||||
<text> </text>
|
||||
{visibleSkills.map((skill, idx) => {
|
||||
const actualIdx = startIdx + idx;
|
||||
const selected = actualIdx === selectedIndex;
|
||||
const indicator = selected ? '▸' : ' ';
|
||||
const statusIcon = skill.enabled !== false ? '●' : '○';
|
||||
const statusColor = skill.enabled !== false ? terminalColors.success : terminalColors.textMuted;
|
||||
return (
|
||||
<box key={skill.name} flexDirection="row">
|
||||
<text fg={terminalColors.text}>{indicator}</text>
|
||||
<text fg={statusColor}>{statusIcon} </text>
|
||||
<text fg={selected ? terminalColors.accent : terminalColors.text}>
|
||||
{skill.name}
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Scroll indicator */}
|
||||
{filteredSkills.length > maxVisible && (
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{'\n'}showing {startIdx + 1}-{Math.min(startIdx + maxVisible, filteredSkills.length)} of {filteredSkills.length}
|
||||
</text>
|
||||
)}
|
||||
</box>
|
||||
)}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text fg={terminalColors.textMuted}>{shortcuts}</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,182 +1,150 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { useKeyboard } from '@opentui/react';
|
||||
import { type Screen, DEFAULT_REPOS } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
|
||||
interface MarketplaceSkill {
|
||||
name: string;
|
||||
description: string;
|
||||
source: string;
|
||||
repo: string;
|
||||
tags?: string[];
|
||||
stars?: number;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
interface MarketplaceProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
// Known skill repositories to aggregate from
|
||||
const SKILL_SOURCES = [
|
||||
{ owner: 'composioHQ', repo: 'awesome-claude-code-skills', name: 'Composio Curated' },
|
||||
{ owner: 'anthropics', repo: 'courses', name: 'Anthropic Official' },
|
||||
const CATEGORIES = [
|
||||
{ name: 'Development', count: 24 },
|
||||
{ name: 'Testing', count: 18 },
|
||||
{ name: 'DevOps', count: 15 },
|
||||
{ name: 'Security', count: 12 },
|
||||
];
|
||||
|
||||
export function Marketplace({ rows = 24 }: Props) {
|
||||
const [skills, setSkills] = useState<MarketplaceSkill[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [search, setSearch] = useState('');
|
||||
const [installing, setInstalling] = useState<string | null>(null);
|
||||
export function Marketplace({ onNavigate, cols = 80, rows = 24 }: MarketplaceProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [animPhase, setAnimPhase] = useState(0);
|
||||
|
||||
const filtered = skills.filter(s =>
|
||||
s.name.toLowerCase().includes(search.toLowerCase()) ||
|
||||
s.description.toLowerCase().includes(search.toLowerCase()) ||
|
||||
s.tags?.some(t => t.toLowerCase().includes(search.toLowerCase()))
|
||||
const isCompact = cols < 60;
|
||||
const contentWidth = Math.max(1, Math.min(cols - 4, 60));
|
||||
|
||||
// Entrance animation
|
||||
useEffect(() => {
|
||||
if (animPhase >= 3) return;
|
||||
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [animPhase]);
|
||||
|
||||
// Featured repos
|
||||
const featured = useMemo(() =>
|
||||
DEFAULT_REPOS.slice(0, 5).map((r, i) => ({
|
||||
name: r.name,
|
||||
stars: Math.floor(100 - i * 15),
|
||||
source: r.source,
|
||||
})),
|
||||
[]
|
||||
);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), filtered.length - maxVisible));
|
||||
const visible = filtered.slice(start, start + maxVisible);
|
||||
const maxVisible = Math.max(3, Math.floor((rows - 14) / 1));
|
||||
const visibleFeatured = featured.slice(0, maxVisible);
|
||||
|
||||
useEffect(() => {
|
||||
loadMarketplace();
|
||||
}, []);
|
||||
const handleKeyNav = useCallback((delta: number) => {
|
||||
setSelectedIndex(prev => Math.max(0, Math.min(prev + delta, visibleFeatured.length - 1)));
|
||||
}, [visibleFeatured.length]);
|
||||
|
||||
const loadMarketplace = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Aggregate skills from known sources
|
||||
const allSkills: MarketplaceSkill[] = [];
|
||||
|
||||
for (const source of SKILL_SOURCES) {
|
||||
try {
|
||||
// Try to fetch skill index from GitHub
|
||||
const indexUrl = `https://raw.githubusercontent.com/${source.owner}/${source.repo}/main/skills.json`;
|
||||
const response = await fetch(indexUrl);
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (Array.isArray(data)) {
|
||||
allSkills.push(...data.map((s: Record<string, unknown>) => ({
|
||||
name: String(s.name || 'Unknown'),
|
||||
description: String(s.description || ''),
|
||||
source: source.name,
|
||||
repo: `${source.owner}/${source.repo}`,
|
||||
tags: Array.isArray(s.tags) ? s.tags as string[] : [],
|
||||
stars: typeof s.stars === 'number' ? s.stars : undefined,
|
||||
})));
|
||||
}
|
||||
} else {
|
||||
// Fallback: add the repo itself as a skill source
|
||||
allSkills.push({
|
||||
name: source.repo,
|
||||
description: `Skills from ${source.name}`,
|
||||
source: source.name,
|
||||
repo: `${source.owner}/${source.repo}`,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Add repo as fallback
|
||||
allSkills.push({
|
||||
name: source.repo,
|
||||
description: `Skills from ${source.name}`,
|
||||
source: source.name,
|
||||
repo: `${source.owner}/${source.repo}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Add some example skills for demo
|
||||
if (allSkills.length === 0) {
|
||||
allSkills.push(
|
||||
{ name: 'typescript-strict', description: 'Enable strict TypeScript mode', source: 'Built-in', repo: 'skillkit/skills', tags: ['typescript', 'config'] },
|
||||
{ name: 'eslint-setup', description: 'Set up ESLint with recommended rules', source: 'Built-in', repo: 'skillkit/skills', tags: ['eslint', 'linting'] },
|
||||
{ name: 'prettier-config', description: 'Configure Prettier formatting', source: 'Built-in', repo: 'skillkit/skills', tags: ['prettier', 'formatting'] },
|
||||
{ name: 'jest-setup', description: 'Set up Jest testing framework', source: 'Built-in', repo: 'skillkit/skills', tags: ['jest', 'testing'] },
|
||||
{ name: 'nextjs-auth', description: 'Add authentication to Next.js', source: 'Community', repo: 'community/skills', tags: ['nextjs', 'auth'] },
|
||||
);
|
||||
}
|
||||
|
||||
setSkills(allSkills);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load marketplace');
|
||||
const handleInstall = useCallback(() => {
|
||||
const item = visibleFeatured[selectedIndex];
|
||||
if (item) {
|
||||
// Navigate to installed after "installing"
|
||||
onNavigate('installed');
|
||||
}
|
||||
}, [selectedIndex, visibleFeatured, onNavigate]);
|
||||
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || installing) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(filtered.length - 1, i + 1));
|
||||
else if (input === 'r') loadMarketplace();
|
||||
else if (input === '/') setSearch('');
|
||||
else if (key.backspace || key.delete) setSearch(s => s.slice(0, -1));
|
||||
else if (key.return && filtered[sel]) {
|
||||
setInstalling(filtered[sel].name);
|
||||
// Simulate installation
|
||||
setTimeout(() => setInstalling(null), 1500);
|
||||
}
|
||||
else if (input.length === 1 && /[a-zA-Z0-9-_]/.test(input)) {
|
||||
setSearch(s => s + input);
|
||||
setSel(0);
|
||||
}
|
||||
useKeyboard((key: { name?: string }) => {
|
||||
if (key.name === 'j' || key.name === 'down') handleKeyNav(1);
|
||||
else if (key.name === 'k' || key.name === 'up') handleKeyNav(-1);
|
||||
else if (key.name === 'return') handleInstall();
|
||||
else if (key.name === 'b') onNavigate('browse');
|
||||
else if (key.name === 'escape') onNavigate('home');
|
||||
});
|
||||
|
||||
const divider = useMemo(() =>
|
||||
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
|
||||
[contentWidth]
|
||||
);
|
||||
|
||||
const shortcuts = isCompact
|
||||
? 'j/k nav enter install b browse esc back'
|
||||
: 'j/k navigate enter install b full browse esc back';
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>SKILL MARKETPLACE</Text>
|
||||
<Text dimColor>{skills.length} skills from {SKILL_SOURCES.length} sources</Text>
|
||||
|
||||
{search && (
|
||||
<Text>Search: <Text color="yellow">{search}</Text> ({filtered.length} results)</Text>
|
||||
<box flexDirection="column" padding={1}>
|
||||
{/* Header */}
|
||||
{animPhase >= 1 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
|
||||
<text fg={terminalColors.recommend}>★ Marketplace</text>
|
||||
<text fg={terminalColors.textMuted}>{DEFAULT_REPOS.length} available</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}>discover featured skills</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{loading && <Text>Loading marketplace...</Text>}
|
||||
{error && <Text color="red">{error}</Text>}
|
||||
{installing && <Text color="yellow">Installing {installing}...</Text>}
|
||||
|
||||
{!loading && !installing && filtered.length === 0 && (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>No skills found{search ? ` matching "${search}"` : ''}.</Text>
|
||||
</Box>
|
||||
{/* Categories */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text> </text>
|
||||
<text fg={terminalColors.text}>Categories</text>
|
||||
<text> </text>
|
||||
<box flexDirection="row" gap={2}>
|
||||
{CATEGORIES.map(cat => (
|
||||
<text key={cat.name} fg={terminalColors.textMuted}>
|
||||
{cat.name} ({cat.count})
|
||||
</text>
|
||||
))}
|
||||
</box>
|
||||
<text> </text>
|
||||
{divider}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{!loading && !installing && filtered.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((skill, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
{/* Featured section */}
|
||||
{animPhase >= 3 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.text}>Featured</text>
|
||||
<text fg={terminalColors.textMuted}> · trending</text>
|
||||
</box>
|
||||
<text> </text>
|
||||
|
||||
{visibleFeatured.map((item, idx) => {
|
||||
const selected = idx === selectedIndex;
|
||||
const indicator = selected ? '▸' : ' ';
|
||||
return (
|
||||
<Box key={`${skill.repo}/${skill.name}`} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {skill.name.padEnd(25)} <Text dimColor>{skill.source}</Text>
|
||||
</Text>
|
||||
{isSel && (
|
||||
<Box flexDirection="column" marginLeft={3}>
|
||||
<Text dimColor>{skill.description}</Text>
|
||||
{skill.tags && skill.tags.length > 0 && (
|
||||
<Text dimColor>Tags: {skill.tags.join(', ')}</Text>
|
||||
)}
|
||||
<Text dimColor>Repo: {skill.repo}</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
<box key={item.source} flexDirection="row">
|
||||
<text fg={terminalColors.text}>{indicator}</text>
|
||||
<text fg={selected ? terminalColors.accent : terminalColors.text}>
|
||||
{item.name}
|
||||
</text>
|
||||
<text fg={terminalColors.recommend}> ★{item.stars}</text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < filtered.length && <Text dimColor> ↓ {filtered.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
|
||||
{featured.length > maxVisible && (
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{'\n'}+{featured.length - maxVisible} more
|
||||
</text>
|
||||
)}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=install type=search r=refresh q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
{/* Footer */}
|
||||
{animPhase >= 3 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text fg={terminalColors.textMuted}>{shortcuts}</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,284 +1,50 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import {
|
||||
ObservationStore,
|
||||
LearningStore,
|
||||
getMemoryStatus,
|
||||
getMemoryPaths,
|
||||
createMemoryInjector,
|
||||
type Learning,
|
||||
} from '@skillkit/core';
|
||||
/**
|
||||
* Memory Screen
|
||||
* Session memory management
|
||||
*/
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { Header } from '../components/Header.js';
|
||||
|
||||
interface Props {
|
||||
interface MemoryProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
type Tab = 'learnings' | 'observations' | 'search';
|
||||
|
||||
export function Memory({ rows = 24 }: Props) {
|
||||
const [tab, setTab] = useState<Tab>('learnings');
|
||||
const [learnings, setLearnings] = useState<Learning[]>([]);
|
||||
const [observationCount, setObservationCount] = useState(0);
|
||||
const [globalCount, setGlobalCount] = useState(0);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchResults, setSearchResults] = useState<Learning[]>([]);
|
||||
const [isGlobal, setIsGlobal] = useState(false);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
const currentList = tab === 'search' ? searchResults : learnings;
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), currentList.length - maxVisible));
|
||||
const visible = currentList.slice(start, start + maxVisible);
|
||||
|
||||
useEffect(() => {
|
||||
loadMemory();
|
||||
}, [isGlobal]);
|
||||
|
||||
const loadMemory = () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const projectPath = process.cwd();
|
||||
const status = getMemoryStatus(projectPath);
|
||||
|
||||
// Load learnings
|
||||
const store = new LearningStore(
|
||||
isGlobal ? 'global' : 'project',
|
||||
isGlobal ? undefined : projectPath
|
||||
);
|
||||
setLearnings(store.getAll());
|
||||
|
||||
// Get counts
|
||||
if (status.hasObservations) {
|
||||
const obsStore = new ObservationStore(projectPath);
|
||||
setObservationCount(obsStore.count());
|
||||
} else {
|
||||
setObservationCount(0);
|
||||
}
|
||||
|
||||
if (status.hasGlobalLearnings) {
|
||||
const globalStore = new LearningStore('global');
|
||||
setGlobalCount(globalStore.count());
|
||||
} else {
|
||||
setGlobalCount(0);
|
||||
}
|
||||
} catch {
|
||||
setLearnings([]);
|
||||
setObservationCount(0);
|
||||
setGlobalCount(0);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleSearch = (query: string) => {
|
||||
if (!query.trim()) {
|
||||
setSearchResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const projectPath = process.cwd();
|
||||
const injector = createMemoryInjector(projectPath);
|
||||
const results = injector.search(query, {
|
||||
includeGlobal: true,
|
||||
maxLearnings: 20,
|
||||
minRelevance: 0,
|
||||
});
|
||||
setSearchResults(results.map(r => r.learning));
|
||||
} catch {
|
||||
setSearchResults([]);
|
||||
}
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading) return;
|
||||
|
||||
// Tab navigation
|
||||
if (input === '1') { setTab('learnings'); setSel(0); setExpanded(false); }
|
||||
else if (input === '2') { setTab('observations'); setSel(0); setExpanded(false); }
|
||||
else if (input === '3') { setTab('search'); setSel(0); setExpanded(false); }
|
||||
|
||||
// List navigation
|
||||
else if (key.upArrow) {
|
||||
setSel(i => Math.max(0, i - 1));
|
||||
setExpanded(false);
|
||||
}
|
||||
else if (key.downArrow) {
|
||||
setSel(i => Math.min(currentList.length - 1, i + 1));
|
||||
setExpanded(false);
|
||||
}
|
||||
|
||||
// Actions (use 'f' for refresh to avoid conflict with global 'r' for Recommend)
|
||||
else if (input === 'f') loadMemory();
|
||||
else if (input === 'g') setIsGlobal(g => !g);
|
||||
else if (key.return) setExpanded(e => !e);
|
||||
|
||||
// Search input (basic)
|
||||
else if (tab === 'search' && input && input.length === 1 && !key.ctrl && !key.meta) {
|
||||
const newQuery = searchQuery + input;
|
||||
setSearchQuery(newQuery);
|
||||
handleSearch(newQuery);
|
||||
}
|
||||
else if (tab === 'search' && key.backspace) {
|
||||
const newQuery = searchQuery.slice(0, -1);
|
||||
setSearchQuery(newQuery);
|
||||
handleSearch(newQuery);
|
||||
}
|
||||
});
|
||||
|
||||
const ONE_MINUTE = 60_000;
|
||||
const ONE_HOUR = 3_600_000;
|
||||
const ONE_DAY = 86_400_000;
|
||||
|
||||
function formatDate(iso: string): string {
|
||||
const d = new Date(iso);
|
||||
const diff = Date.now() - d.getTime();
|
||||
|
||||
if (diff < ONE_MINUTE) return 'Just now';
|
||||
if (diff < ONE_HOUR) return `${Math.floor(diff / ONE_MINUTE)}m ago`;
|
||||
if (diff < ONE_DAY) return `${Math.floor(diff / ONE_HOUR)}h ago`;
|
||||
return d.toLocaleDateString();
|
||||
}
|
||||
|
||||
function formatEffectiveness(eff?: number): string {
|
||||
if (eff === undefined) return ' -';
|
||||
return eff.toString().padStart(3) + '%';
|
||||
}
|
||||
|
||||
function getEffectivenessColor(eff?: number): string | undefined {
|
||||
if (eff === undefined) return undefined;
|
||||
if (eff >= 70) return 'green';
|
||||
if (eff >= 40) return 'yellow';
|
||||
return 'red';
|
||||
}
|
||||
|
||||
const renderLearnings = () => (
|
||||
<Box flexDirection="column">
|
||||
{currentList.length === 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>No learnings found.</Text>
|
||||
<Text dimColor>Run skills to capture learnings, or add manually:</Text>
|
||||
<Text dimColor> skillkit memory add --title "..." --content "..."</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{currentList.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> {symbols.arrowUp} {start} more</Text>}
|
||||
{visible.map((learning, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
|
||||
return (
|
||||
<Box key={learning.id} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '}
|
||||
<Text color={colors.primary}>{symbols.bullet}</Text>
|
||||
{' '}{learning.title.slice(0, 35).padEnd(35)}{' '}
|
||||
<Text dimColor>{learning.tags.slice(0, 2).join(', ').slice(0, 15).padEnd(15)}</Text>
|
||||
{' '}<Text color={getEffectivenessColor(learning.effectiveness)}>{formatEffectiveness(learning.effectiveness)}</Text>
|
||||
{' '}<Text dimColor>{formatDate(learning.updatedAt)}</Text>
|
||||
</Text>
|
||||
{isSel && expanded && (
|
||||
<Box flexDirection="column" marginLeft={3} marginY={1}>
|
||||
<Text dimColor>ID: {learning.id.slice(0, 8)}</Text>
|
||||
<Text dimColor>Scope: {learning.scope}</Text>
|
||||
<Text dimColor>Source: {learning.source}</Text>
|
||||
<Text dimColor>Tags: {learning.tags.join(', ')}</Text>
|
||||
{learning.frameworks && learning.frameworks.length > 0 && (
|
||||
<Text dimColor>Frameworks: {learning.frameworks.join(', ')}</Text>
|
||||
)}
|
||||
<Text dimColor>Uses: {learning.useCount}</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text wrap="wrap">{learning.content.slice(0, 300)}{learning.content.length > 300 ? '...' : ''}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < currentList.length && (
|
||||
<Text dimColor> {symbols.arrowDown} {currentList.length - start - maxVisible} more</Text>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
|
||||
const renderObservations = () => (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text>Session Observations: <Text bold color={colors.primary}>{observationCount}</Text></Text>
|
||||
<Text dimColor>Observations are raw captures from skill execution.</Text>
|
||||
|
||||
{observationCount > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text>Compress observations into learnings:</Text>
|
||||
<Text dimColor> skillkit memory compress</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{observationCount >= 50 && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="yellow">{symbols.warning} You have many uncompressed observations.</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Observations are stored at:</Text>
|
||||
</Box>
|
||||
<Text dimColor> {getMemoryPaths(process.cwd()).observationsFile}</Text>
|
||||
</Box>
|
||||
);
|
||||
|
||||
const renderSearch = () => (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Box>
|
||||
<Text>Search: </Text>
|
||||
<Text color={colors.primary}>{searchQuery}</Text>
|
||||
<Text color={colors.secondary}>_</Text>
|
||||
</Box>
|
||||
|
||||
{searchQuery && searchResults.length === 0 && (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>No results found for "{searchQuery}"</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{searchResults.length > 0 && renderLearnings()}
|
||||
</Box>
|
||||
);
|
||||
export function Memory({ onNavigate, cols = 80, rows = 24 }: MemoryProps) {
|
||||
const memories = [
|
||||
{ key: 'project-context', size: '2.4 KB', updated: '2 min ago' },
|
||||
{ key: 'user-preferences', size: '1.1 KB', updated: '5 min ago' },
|
||||
{ key: 'session-history', size: '4.7 KB', updated: '1 min ago' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>MEMORY</Text>
|
||||
<Text dimColor>
|
||||
{isGlobal ? 'Global' : 'Project'}: {learnings.length} learning(s)
|
||||
{!isGlobal && globalCount > 0 && <Text> | Global: {globalCount}</Text>}
|
||||
</Text>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<Header
|
||||
title="Memory"
|
||||
subtitle="Manage persistent session memory"
|
||||
count={memories.length}
|
||||
icon="◎"
|
||||
/>
|
||||
|
||||
{/* Tabs */}
|
||||
<Box marginTop={1}>
|
||||
<Text inverse={tab === 'learnings'}>[1] Learnings</Text>
|
||||
<Text> </Text>
|
||||
<Text inverse={tab === 'observations'}>[2] Observations</Text>
|
||||
<Text> </Text>
|
||||
<Text inverse={tab === 'search'}>[3] Search</Text>
|
||||
</Box>
|
||||
<text fg={terminalColors.text}><b>Stored Memories</b></text>
|
||||
<text> </text>
|
||||
|
||||
{loading && <Box marginTop={1}><Text>Loading...</Text></Box>}
|
||||
{memories.map((mem, idx) => (
|
||||
<box key={mem.key} flexDirection="row" marginBottom={1}>
|
||||
<text fg={idx === 0 ? terminalColors.accent : terminalColors.text} width={25}>
|
||||
{idx === 0 ? '\u25B8 ' : ' '}{mem.key}
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted} width={12}>{mem.size}</text>
|
||||
<text fg={terminalColors.textMuted}>{mem.updated}</text>
|
||||
</box>
|
||||
))}
|
||||
|
||||
{!loading && tab === 'learnings' && renderLearnings()}
|
||||
{!loading && tab === 'observations' && renderObservations()}
|
||||
{!loading && tab === 'search' && renderSearch()}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
Enter=expand g=toggle global f=refresh 1-3=tabs
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
Press Enter to view, 'd' to delete, 'c' to clear all
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,186 +1,59 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import {
|
||||
MethodologyManager,
|
||||
type MethodologyPack,
|
||||
type MethodologySkill,
|
||||
} from '@skillkit/core';
|
||||
/**
|
||||
* Methodology Screen
|
||||
* Development methodology packs
|
||||
*/
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { Header } from '../components/Header.js';
|
||||
|
||||
interface Props {
|
||||
interface MethodologyProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
type View = 'packs' | 'skills';
|
||||
|
||||
export function Methodology({ rows = 24 }: Props) {
|
||||
const [packs, setPacks] = useState<MethodologyPack[]>([]);
|
||||
const [selectedPack, setSelectedPack] = useState<MethodologyPack | null>(null);
|
||||
const [skills, setSkills] = useState<MethodologySkill[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [view, setView] = useState<View>('packs');
|
||||
const [sel, setSel] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
const manager = useMemo(() => new MethodologyManager({
|
||||
projectPath: process.cwd(),
|
||||
}), []);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
|
||||
useEffect(() => {
|
||||
loadPacks();
|
||||
}, []);
|
||||
|
||||
const loadPacks = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const loadedPacks = await manager.listAvailablePacks();
|
||||
setPacks(loadedPacks);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load methodology packs');
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const loadSkills = async (pack: MethodologyPack) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const loader = manager.getLoader();
|
||||
const loadedSkills = await loader.loadPackSkills(pack.name);
|
||||
setSkills(loadedSkills);
|
||||
setSelectedPack(pack);
|
||||
setView('skills');
|
||||
setSel(0);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load skills');
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const installPack = async (pack: MethodologyPack) => {
|
||||
setLoading(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
await manager.installPack(pack.name);
|
||||
setMessage(`Installed ${pack.name} methodology pack`);
|
||||
// Refresh packs list after install
|
||||
await loadPacks();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to install pack');
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const items = view === 'packs' ? packs : skills;
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), items.length - maxVisible));
|
||||
const visible = items.slice(start, start + maxVisible);
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(items.length - 1, i + 1));
|
||||
else if (input === 'r') {
|
||||
if (view === 'packs') loadPacks();
|
||||
else if (selectedPack) loadSkills(selectedPack);
|
||||
}
|
||||
else if (key.escape || input === 'b') {
|
||||
if (view === 'skills') {
|
||||
setView('packs');
|
||||
setSel(0);
|
||||
setSelectedPack(null);
|
||||
}
|
||||
}
|
||||
else if (key.return) {
|
||||
if (view === 'packs' && packs[sel]) {
|
||||
loadSkills(packs[sel]);
|
||||
}
|
||||
}
|
||||
else if (input === 'i' && view === 'packs' && packs[sel]) {
|
||||
installPack(packs[sel]);
|
||||
}
|
||||
});
|
||||
|
||||
const renderPackItem = (pack: MethodologyPack, idx: number) => {
|
||||
const isSel = idx === sel;
|
||||
return (
|
||||
<Box key={pack.name} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {pack.name} <Text dimColor>v{pack.version}</Text>
|
||||
</Text>
|
||||
{isSel && (
|
||||
<>
|
||||
<Text dimColor> {pack.description}</Text>
|
||||
<Text dimColor> {pack.skills.length} skill(s) | Tags: {pack.tags?.join(', ') || 'none'}</Text>
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const renderSkillItem = (skill: MethodologySkill, idx: number) => {
|
||||
const isSel = idx === sel;
|
||||
return (
|
||||
<Box key={skill.name} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {skill.name}
|
||||
</Text>
|
||||
{isSel && skill.description && (
|
||||
<Text dimColor> {skill.description}</Text>
|
||||
)}
|
||||
{isSel && skill.tags && (
|
||||
<Text dimColor> Tags: {skill.tags.join(', ')}</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
export function Methodology({ onNavigate, cols = 80, rows = 24 }: MethodologyProps) {
|
||||
const methodologies = [
|
||||
{ name: 'TDD', description: 'Test-Driven Development', skills: 5, active: true },
|
||||
{ name: 'BDD', description: 'Behavior-Driven Development', skills: 4, active: false },
|
||||
{ name: 'Clean Code', description: 'SOLID principles', skills: 6, active: false },
|
||||
{ name: 'Security First', description: 'OWASP guidelines', skills: 8, active: false },
|
||||
];
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>
|
||||
{view === 'packs' ? 'METHODOLOGY PACKS' : `${selectedPack?.name.toUpperCase()} SKILLS`}
|
||||
</Text>
|
||||
<Text dimColor>
|
||||
{view === 'packs'
|
||||
? `${packs.length} pack(s) available`
|
||||
: `${skills.length} skill(s) in pack`}
|
||||
</Text>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<Header
|
||||
title="Methodologies"
|
||||
subtitle="Development methodology skill packs"
|
||||
count={methodologies.length}
|
||||
icon="◎"
|
||||
/>
|
||||
|
||||
{loading && <Text color="yellow">Loading...</Text>}
|
||||
{error && <Text color="red">{symbols.error} {error}</Text>}
|
||||
{message && <Text color="green">{symbols.success} {message}</Text>}
|
||||
<text fg={terminalColors.text}><b>Available Packs</b></text>
|
||||
<text> </text>
|
||||
|
||||
{!loading && items.length === 0 && (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>No {view === 'packs' ? 'methodology packs' : 'skills'} found.</Text>
|
||||
</Box>
|
||||
)}
|
||||
{methodologies.map((meth, idx) => (
|
||||
<box key={meth.name} flexDirection="column" marginBottom={1}>
|
||||
<box flexDirection="row">
|
||||
<text
|
||||
fg={idx === 0 ? terminalColors.accent : terminalColors.text}
|
||||
width={15}
|
||||
>
|
||||
{idx === 0 ? <b>{'\u25B8 '}{meth.name}</b> : <>{'\u25B8 '}{meth.name}</>}
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted}>{meth.skills} skills</text>
|
||||
{meth.active && (
|
||||
<text fg={terminalColors.success}> [active]</text>
|
||||
)}
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}> {meth.description}</text>
|
||||
</box>
|
||||
))}
|
||||
|
||||
{!loading && items.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> {symbols.arrowUp} {start} more</Text>}
|
||||
{view === 'packs'
|
||||
? (visible as MethodologyPack[]).map((pack, i) => renderPackItem(pack, start + i))
|
||||
: (visible as MethodologySkill[]).map((skill, i) => renderSkillItem(skill, start + i))
|
||||
}
|
||||
{start + maxVisible < items.length && (
|
||||
<Text dimColor> {symbols.arrowDown} {items.length - start - maxVisible} more</Text>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{view === 'packs' ? (
|
||||
<Text dimColor>Enter=view skills i=install r=refresh q=quit</Text>
|
||||
) : (
|
||||
<Text dimColor>b/Esc=back r=refresh q=quit</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
Press Enter to activate, 'v' to view skills
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,288 +1,70 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import {
|
||||
PlanParser,
|
||||
PlanValidator,
|
||||
PlanExecutor,
|
||||
type StructuredPlan,
|
||||
type PlanTask,
|
||||
} from '@skillkit/core';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
/**
|
||||
* Plan Screen
|
||||
* Structured plan execution
|
||||
*/
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { Header } from '../components/Header.js';
|
||||
import { ProgressBar } from '../components/ProgressBar.js';
|
||||
|
||||
interface Props {
|
||||
interface PlanProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
type View = 'plans' | 'tasks' | 'steps';
|
||||
export function Plan({ onNavigate, cols = 80, rows = 24 }: PlanProps) {
|
||||
const steps = [
|
||||
{ name: 'Analyze codebase', status: 'done', duration: '2.3s' },
|
||||
{ name: 'Generate tests', status: 'done', duration: '5.1s' },
|
||||
{ name: 'Run linter', status: 'running', duration: '-' },
|
||||
{ name: 'Apply fixes', status: 'pending', duration: '-' },
|
||||
{ name: 'Verify changes', status: 'pending', duration: '-' },
|
||||
];
|
||||
|
||||
interface PlanFile {
|
||||
name: string;
|
||||
path: string;
|
||||
plan?: StructuredPlan;
|
||||
valid?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function Plan({ rows = 24 }: Props) {
|
||||
const [planFiles, setPlanFiles] = useState<PlanFile[]>([]);
|
||||
const [selectedPlan, setSelectedPlan] = useState<PlanFile | null>(null);
|
||||
const [selectedTask, setSelectedTask] = useState<PlanTask | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [view, setView] = useState<View>('plans');
|
||||
const [sel, setSel] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [executing, setExecuting] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
const parser = useMemo(() => new PlanParser(), []);
|
||||
const validator = useMemo(() => new PlanValidator(), []);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
|
||||
useEffect(() => {
|
||||
loadPlans();
|
||||
}, []);
|
||||
|
||||
const loadPlans = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const cwd = process.cwd();
|
||||
const files: PlanFile[] = [];
|
||||
|
||||
// Look for plan files in common locations
|
||||
const searchPaths = [
|
||||
cwd,
|
||||
path.join(cwd, 'plans'),
|
||||
path.join(cwd, '.skillkit', 'plans'),
|
||||
];
|
||||
|
||||
for (const searchPath of searchPaths) {
|
||||
if (fs.existsSync(searchPath)) {
|
||||
const entries = fs.readdirSync(searchPath, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (entry.isFile() && (entry.name.endsWith('.plan.md') || entry.name.endsWith('-plan.md'))) {
|
||||
const filePath = path.join(searchPath, entry.name);
|
||||
const content = fs.readFileSync(filePath, 'utf-8');
|
||||
try {
|
||||
const plan = parser.parse(content);
|
||||
const validation = validator.validate(plan);
|
||||
const errorIssue = validation.issues.find(i => i.type === 'error');
|
||||
files.push({
|
||||
name: entry.name,
|
||||
path: filePath,
|
||||
plan,
|
||||
valid: validation.valid,
|
||||
error: errorIssue?.message,
|
||||
});
|
||||
} catch {
|
||||
files.push({
|
||||
name: entry.name,
|
||||
path: filePath,
|
||||
valid: false,
|
||||
error: 'Failed to parse plan',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setPlanFiles(files);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load plans');
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const selectPlan = (planFile: PlanFile) => {
|
||||
if (planFile.plan) {
|
||||
setSelectedPlan(planFile);
|
||||
setView('tasks');
|
||||
setSel(0);
|
||||
}
|
||||
};
|
||||
|
||||
const selectTask = (task: PlanTask) => {
|
||||
setSelectedTask(task);
|
||||
setView('steps');
|
||||
setSel(0);
|
||||
};
|
||||
|
||||
const executePlan = async (planFile: PlanFile) => {
|
||||
if (!planFile.plan) return;
|
||||
|
||||
setExecuting(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
const executor = new PlanExecutor();
|
||||
await executor.execute(planFile.plan, { dryRun: true });
|
||||
setMessage(`Executed plan: ${planFile.plan.name} (dry run)`);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to execute plan');
|
||||
}
|
||||
setExecuting(false);
|
||||
};
|
||||
|
||||
const getItems = () => {
|
||||
if (view === 'plans') return planFiles;
|
||||
if (view === 'tasks' && selectedPlan?.plan) return selectedPlan.plan.tasks;
|
||||
if (view === 'steps' && selectedTask) return selectedTask.steps;
|
||||
return [];
|
||||
};
|
||||
|
||||
const items = getItems();
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), items.length - maxVisible));
|
||||
const visible = items.slice(start, start + maxVisible);
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || executing) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(items.length - 1, i + 1));
|
||||
else if (input === 'r') loadPlans();
|
||||
else if (key.escape || input === 'b') {
|
||||
if (view === 'steps') {
|
||||
setView('tasks');
|
||||
setSelectedTask(null);
|
||||
setSel(0);
|
||||
} else if (view === 'tasks') {
|
||||
setView('plans');
|
||||
setSelectedPlan(null);
|
||||
setSel(0);
|
||||
}
|
||||
}
|
||||
else if (key.return) {
|
||||
if (view === 'plans' && planFiles[sel]) {
|
||||
selectPlan(planFiles[sel]);
|
||||
} else if (view === 'tasks' && selectedPlan?.plan?.tasks[sel]) {
|
||||
selectTask(selectedPlan.plan.tasks[sel]);
|
||||
}
|
||||
}
|
||||
else if (input === 'x' && view === 'plans' && planFiles[sel]?.plan) {
|
||||
executePlan(planFiles[sel]);
|
||||
}
|
||||
});
|
||||
|
||||
const renderPlanItem = (planFile: PlanFile, idx: number) => {
|
||||
const isSel = idx === sel;
|
||||
const statusIcon = planFile.valid ? symbols.success : symbols.error;
|
||||
const statusColor = planFile.valid ? 'green' : 'red';
|
||||
|
||||
return (
|
||||
<Box key={planFile.path} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} <Text color={statusColor}>{statusIcon}</Text> {planFile.name}
|
||||
</Text>
|
||||
{isSel && planFile.plan && (
|
||||
<>
|
||||
<Text dimColor> {planFile.plan.goal}</Text>
|
||||
<Text dimColor> {planFile.plan.tasks.length} task(s) | {planFile.plan.techStack?.join(', ') || 'No stack'}</Text>
|
||||
</>
|
||||
)}
|
||||
{isSel && planFile.error && (
|
||||
<Text color="red"> {planFile.error}</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const renderTaskItem = (task: PlanTask, idx: number) => {
|
||||
const isSel = idx === sel;
|
||||
return (
|
||||
<Box key={task.id} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} [{task.id}] {task.name}
|
||||
</Text>
|
||||
{isSel && (
|
||||
<>
|
||||
<Text dimColor> {task.steps.length} step(s)</Text>
|
||||
{task.files?.create && <Text dimColor> Create: {task.files.create.join(', ')}</Text>}
|
||||
{task.files?.modify && <Text dimColor> Modify: {task.files.modify.join(', ')}</Text>}
|
||||
{task.files?.test && <Text dimColor> Test: {task.files.test.join(', ')}</Text>}
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const renderStepItem = (step: { number: number; description: string; type: string }, idx: number) => {
|
||||
const isSel = idx === sel;
|
||||
const typeColors: Record<string, string> = {
|
||||
test: 'yellow',
|
||||
verify: 'cyan',
|
||||
implement: 'green',
|
||||
commit: 'magenta',
|
||||
};
|
||||
|
||||
return (
|
||||
<Box key={step.number} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} <Text color={typeColors[step.type] || 'white'}>[{step.type}]</Text> Step {step.number}
|
||||
</Text>
|
||||
{isSel && (
|
||||
<Text dimColor> {step.description}</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const getTitle = () => {
|
||||
if (view === 'plans') return 'PLANS';
|
||||
if (view === 'tasks') return `TASKS: ${selectedPlan?.plan?.name || ''}`;
|
||||
if (view === 'steps') return `STEPS: Task ${selectedTask?.id}`;
|
||||
return 'PLANS';
|
||||
};
|
||||
const completedSteps = steps.filter((s) => s.status === 'done').length;
|
||||
const progress = (completedSteps / steps.length) * 100;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>{getTitle()}</Text>
|
||||
<Text dimColor>
|
||||
{view === 'plans' && `${planFiles.length} plan(s) found`}
|
||||
{view === 'tasks' && selectedPlan?.plan && `${selectedPlan.plan.tasks.length} task(s)`}
|
||||
{view === 'steps' && selectedTask && `${selectedTask.steps.length} step(s)`}
|
||||
</Text>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<Header
|
||||
title="Plan Execution"
|
||||
subtitle="Structured multi-step execution"
|
||||
icon="▣"
|
||||
/>
|
||||
|
||||
{loading && <Text color="yellow">Loading plans...</Text>}
|
||||
{executing && <Text color="yellow">Executing plan...</Text>}
|
||||
{error && <Text color="red">{symbols.error} {error}</Text>}
|
||||
{message && <Text color="green">{symbols.success} {message}</Text>}
|
||||
<box flexDirection="row" marginBottom={1}>
|
||||
<text fg={terminalColors.text}>Progress: </text>
|
||||
<ProgressBar progress={progress} width={30} />
|
||||
</box>
|
||||
|
||||
{!loading && !executing && items.length === 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>No {view} found.</Text>
|
||||
{view === 'plans' && (
|
||||
<Text dimColor>Create a plan file: *.plan.md or *-plan.md</Text>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
<text fg={terminalColors.text}><b>Steps</b></text>
|
||||
<text> </text>
|
||||
|
||||
{!loading && !executing && items.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{view === 'plans' && (visible as PlanFile[]).map((pf, i) => renderPlanItem(pf, start + i))}
|
||||
{view === 'tasks' && (visible as PlanTask[]).map((t, i) => renderTaskItem(t, start + i))}
|
||||
{view === 'steps' && (visible as Array<{ number: number; description: string; type: string }>).map((s, i) => renderStepItem(s, start + i))}
|
||||
{start + maxVisible < items.length && (
|
||||
<Text dimColor> ↓ {items.length - start - maxVisible} more</Text>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
{steps.map((step, idx) => {
|
||||
const statusIcon = step.status === 'done' ? '\u2713' : step.status === 'running' ? '\u27F3' : '\u25CB';
|
||||
const statusColor =
|
||||
step.status === 'done'
|
||||
? terminalColors.success
|
||||
: step.status === 'running'
|
||||
? terminalColors.accent
|
||||
: terminalColors.textMuted;
|
||||
|
||||
<Box marginTop={1}>
|
||||
{view === 'plans' && (
|
||||
<Text dimColor>Enter=view tasks x=execute (dry-run) r=refresh q=quit</Text>
|
||||
)}
|
||||
{view === 'tasks' && (
|
||||
<Text dimColor>Enter=view steps b/Esc=back q=quit</Text>
|
||||
)}
|
||||
{view === 'steps' && (
|
||||
<Text dimColor>b/Esc=back q=quit</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
return (
|
||||
<box key={step.name} flexDirection="row" marginBottom={1}>
|
||||
<text fg={statusColor} width={3}>{statusIcon}</text>
|
||||
<text fg={step.status === 'pending' ? terminalColors.textMuted : terminalColors.text} width={25}>
|
||||
{step.name}
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted}>{step.duration}</text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
Press Enter to continue, Esc to cancel
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,232 +1,57 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
/**
|
||||
* Plugins Screen
|
||||
* Plugin management
|
||||
*/
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { Header } from '../components/Header.js';
|
||||
|
||||
interface PluginInfo {
|
||||
name: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
author?: string;
|
||||
enabled: boolean;
|
||||
translators?: string[];
|
||||
providers?: string[];
|
||||
commands?: string[];
|
||||
}
|
||||
|
||||
interface Props {
|
||||
interface PluginsProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Plugins({ rows = 24 }: Props) {
|
||||
const [plugins, setPlugins] = useState<PluginInfo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 12);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), plugins.length - maxVisible));
|
||||
const visible = plugins.slice(start, start + maxVisible);
|
||||
|
||||
useEffect(() => {
|
||||
loadPlugins();
|
||||
}, []);
|
||||
|
||||
const loadPlugins = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const { createPluginManager, loadPluginsFromDirectory } = await import('@skillkit/core');
|
||||
const { join } = await import('node:path');
|
||||
const manager = createPluginManager(process.cwd());
|
||||
|
||||
// Load plugins from directory first to populate the manager
|
||||
const pluginsDir = join(process.cwd(), '.skillkit', 'plugins');
|
||||
try {
|
||||
const loadedPlugins = await loadPluginsFromDirectory(pluginsDir);
|
||||
for (const plugin of loadedPlugins) {
|
||||
if (!manager.getPlugin(plugin.metadata.name)) {
|
||||
await manager.register(plugin);
|
||||
}
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
// Only ignore ENOENT (directory doesn't exist), rethrow other errors
|
||||
if (err && typeof err === 'object' && 'code' in err && err.code !== 'ENOENT') {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const allPlugins = manager.listPlugins();
|
||||
|
||||
const pluginInfos: PluginInfo[] = allPlugins.map(p => {
|
||||
const plugin = manager.getPlugin(p.name);
|
||||
return {
|
||||
name: p.name,
|
||||
version: p.version,
|
||||
description: p.description,
|
||||
author: p.author,
|
||||
enabled: manager.isPluginEnabled(p.name),
|
||||
translators: plugin?.translators?.map(t => t.agentType as string),
|
||||
providers: plugin?.providers?.map(pr => pr.providerName),
|
||||
commands: plugin?.commands?.map(c => c.name),
|
||||
};
|
||||
});
|
||||
|
||||
setPlugins(pluginInfos);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load plugins');
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const togglePlugin = async (pluginName: string, currentEnabled: boolean) => {
|
||||
setLoading(true);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
const { createPluginManager, loadPluginsFromDirectory } = await import('@skillkit/core');
|
||||
const { join } = await import('node:path');
|
||||
const manager = createPluginManager(process.cwd());
|
||||
|
||||
// Load plugins from directory first so enable/disable can find them
|
||||
const pluginsDir = join(process.cwd(), '.skillkit', 'plugins');
|
||||
try {
|
||||
const loadedPlugins = await loadPluginsFromDirectory(pluginsDir);
|
||||
for (const plugin of loadedPlugins) {
|
||||
if (!manager.getPlugin(plugin.metadata.name)) {
|
||||
await manager.register(plugin);
|
||||
}
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
// Only ignore ENOENT (directory doesn't exist), rethrow other errors
|
||||
if (err && typeof err === 'object' && 'code' in err && err.code !== 'ENOENT') {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentEnabled) {
|
||||
manager.disablePlugin(pluginName);
|
||||
setMessage(`Disabled: ${pluginName}`);
|
||||
} else {
|
||||
manager.enablePlugin(pluginName);
|
||||
setMessage(`Enabled: ${pluginName}`);
|
||||
}
|
||||
|
||||
// Reload
|
||||
await loadPlugins();
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Toggle failed');
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading) return;
|
||||
if (plugins.length === 0 && (key.upArrow || key.downArrow)) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(Math.max(0, plugins.length - 1), i + 1));
|
||||
else if (input === 'r') loadPlugins();
|
||||
else if (input === 'e' && plugins[sel]) {
|
||||
togglePlugin(plugins[sel].name, plugins[sel].enabled);
|
||||
}
|
||||
else if (key.return && plugins[sel]) {
|
||||
togglePlugin(plugins[sel].name, plugins[sel].enabled);
|
||||
}
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color={colors.primary} bold>Plugin Manager</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text color={colors.secondaryDim}>{symbols.spinner[0]} Loading...</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
export function Plugins({ onNavigate, cols = 80, rows = 24 }: PluginsProps) {
|
||||
const plugins = [
|
||||
{ name: 'git-hooks', enabled: true, version: '1.2.0' },
|
||||
{ name: 'ai-suggest', enabled: true, version: '0.9.1' },
|
||||
{ name: 'metrics', enabled: false, version: '2.0.0' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color={colors.primary} bold>Plugin Manager</Text>
|
||||
<Text color={colors.secondaryDim} dimColor>Manage SkillKit extensions</Text>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<Header
|
||||
title="Plugins"
|
||||
subtitle="Extend SkillKit with plugins"
|
||||
count={plugins.length}
|
||||
icon="◈"
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red">{symbols.error} {error}</Text>
|
||||
</Box>
|
||||
)}
|
||||
<text fg={terminalColors.text}><b>Installed Plugins</b></text>
|
||||
<text> </text>
|
||||
|
||||
{message && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="green">{symbols.success} {message}</Text>
|
||||
</Box>
|
||||
)}
|
||||
{plugins.map((plugin, idx) => (
|
||||
<box key={plugin.name} flexDirection="row" marginBottom={1}>
|
||||
<text
|
||||
fg={idx === 0 ? terminalColors.accent : terminalColors.text}
|
||||
width={18}
|
||||
>
|
||||
{idx === 0 ? '\u25B8 ' : ' '}{plugin.name}
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted} width={10}>v{plugin.version}</text>
|
||||
<text
|
||||
fg={plugin.enabled ? terminalColors.success : terminalColors.textMuted}
|
||||
>
|
||||
{plugin.enabled ? '\u25CF enabled' : '\u25CB disabled'}
|
||||
</text>
|
||||
</box>
|
||||
))}
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text color={colors.secondaryDim} bold>
|
||||
Installed Plugins ({plugins.length})
|
||||
</Text>
|
||||
|
||||
{plugins.length === 0 ? (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text color={colors.secondaryDim} dimColor>No plugins installed.</Text>
|
||||
<Text color={colors.secondaryDim} dimColor>
|
||||
Use: skillkit plugin install --source <path-or-package>
|
||||
</Text>
|
||||
</Box>
|
||||
) : (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
{visible.map((plugin, i) => {
|
||||
const actualIndex = start + i;
|
||||
const isSelected = actualIndex === sel;
|
||||
const statusColor = plugin.enabled ? 'green' : 'gray';
|
||||
const statusText = plugin.enabled ? 'enabled' : 'disabled';
|
||||
|
||||
return (
|
||||
<Box key={plugin.name} flexDirection="column">
|
||||
<Text>
|
||||
{isSelected ? symbols.pointer : ' '}{' '}
|
||||
<Text color={isSelected ? colors.primary : colors.secondaryDim} bold={isSelected}>
|
||||
{plugin.name}
|
||||
</Text>
|
||||
<Text dimColor> v{plugin.version}</Text>
|
||||
<Text color={statusColor}> [{statusText}]</Text>
|
||||
</Text>
|
||||
{isSelected && (
|
||||
<Box flexDirection="column" marginLeft={3}>
|
||||
{plugin.description && (
|
||||
<Text color={colors.secondaryDim} dimColor>{plugin.description}</Text>
|
||||
)}
|
||||
{plugin.author && (
|
||||
<Text dimColor>Author: {plugin.author}</Text>
|
||||
)}
|
||||
{plugin.translators && plugin.translators.length > 0 && (
|
||||
<Text dimColor>Translators: {plugin.translators.join(', ')}</Text>
|
||||
)}
|
||||
{plugin.providers && plugin.providers.length > 0 && (
|
||||
<Text dimColor>Providers: {plugin.providers.join(', ')}</Text>
|
||||
)}
|
||||
{plugin.commands && plugin.commands.length > 0 && (
|
||||
<Text dimColor>Commands: {plugin.commands.join(', ')}</Text>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1} borderStyle="single" borderColor={colors.borderDim} paddingX={1}>
|
||||
<Text dimColor>
|
||||
[↑↓] Navigate [e/Enter] Toggle Enable/Disable [r] Refresh
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
Press Enter to toggle, 'a' to add new, 'u' to update
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,353 +1,199 @@
|
||||
import { useState } from 'react';
|
||||
import { existsSync, mkdirSync, cpSync, rmSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { useRecommend } from '../hooks/useRecommend.js';
|
||||
import { detectProvider, type AgentType, type SkillMetadata } from '@skillkit/core';
|
||||
import { detectAgent, getAdapter, getAllAdapters } from '@skillkit/agents';
|
||||
import { getInstallDir, saveSkillMetadata } from '../helpers.js';
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { useKeyboard } from '@opentui/react';
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
|
||||
type View = 'recommendations' | 'search' | 'agents';
|
||||
|
||||
interface Props {
|
||||
interface RecommendProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Recommend({ rows = 24 }: Props) {
|
||||
const {
|
||||
recommendations,
|
||||
profile,
|
||||
loading,
|
||||
error,
|
||||
totalScanned,
|
||||
indexStatus,
|
||||
refresh,
|
||||
updateIndex,
|
||||
search,
|
||||
searchResults,
|
||||
} = useRecommend();
|
||||
const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
||||
|
||||
const [view, setView] = useState<View>('recommendations');
|
||||
const [sel, setSel] = useState(0);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [searchMode, setSearchMode] = useState(false);
|
||||
const [installing, setInstalling] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [selectedSkill, setSelectedSkill] = useState<{ name: string; source: string } | null>(null);
|
||||
const [agents, setAgents] = useState<{ type: AgentType; name: string; detected: boolean }[]>([]);
|
||||
export function Recommend({ onNavigate, cols = 80, rows = 24 }: RecommendProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [analyzing, setAnalyzing] = useState(true);
|
||||
const [spinnerFrame, setSpinnerFrame] = useState(0);
|
||||
const [animPhase, setAnimPhase] = useState(0);
|
||||
const [analysisProgress, setAnalysisProgress] = useState(0);
|
||||
|
||||
const items = view === 'recommendations'
|
||||
? recommendations
|
||||
: view === 'search'
|
||||
? searchResults
|
||||
: agents;
|
||||
const isCompact = cols < 60;
|
||||
const contentWidth = Math.max(1, Math.min(cols - 4, 60));
|
||||
|
||||
const maxVisible = Math.max(5, rows - 10);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), items.length - maxVisible));
|
||||
const visible = items.slice(start, start + maxVisible);
|
||||
useEffect(() => {
|
||||
if (animPhase >= 3) return;
|
||||
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [animPhase]);
|
||||
|
||||
const showAgentSelection = async (skillName: string, source: string) => {
|
||||
setSelectedSkill({ name: skillName, source });
|
||||
const adapters = getAllAdapters();
|
||||
const agentList: typeof agents = [];
|
||||
for (const a of adapters) {
|
||||
agentList.push({
|
||||
type: a.type as AgentType,
|
||||
name: a.name,
|
||||
detected: await a.isDetected(),
|
||||
useEffect(() => {
|
||||
if (!analyzing) return;
|
||||
const interval = setInterval(() => {
|
||||
setSpinnerFrame(f => (f + 1) % SPINNER.length);
|
||||
}, 80);
|
||||
return () => clearInterval(interval);
|
||||
}, [analyzing]);
|
||||
|
||||
// Simulate analysis
|
||||
useEffect(() => {
|
||||
if (!analyzing) return;
|
||||
const interval = setInterval(() => {
|
||||
setAnalysisProgress(p => {
|
||||
if (p >= 100) {
|
||||
setAnalyzing(false);
|
||||
return 100;
|
||||
}
|
||||
return p + Math.random() * 15 + 5;
|
||||
});
|
||||
}, 200);
|
||||
return () => clearInterval(interval);
|
||||
}, [analyzing]);
|
||||
|
||||
// Recommendations data
|
||||
const recommendations = useMemo(() => [
|
||||
{ name: 'tdd-workflow', reason: 'Based on your test files and coverage patterns', confidence: 95 },
|
||||
{ name: 'react-patterns', reason: 'Detected React in package.json with hooks usage', confidence: 88 },
|
||||
{ name: 'typescript-strict', reason: 'tsconfig.json found with strict mode disabled', confidence: 82 },
|
||||
{ name: 'git-workflow', reason: '.git directory with complex branching detected', confidence: 75 },
|
||||
{ name: 'api-design', reason: 'REST endpoints found in your codebase', confidence: 68 },
|
||||
{ name: 'docker-compose', reason: 'docker-compose.yml detected for orchestration', confidence: 62 },
|
||||
], []);
|
||||
|
||||
const maxVisible = Math.max(3, Math.floor((rows - 10) / 2));
|
||||
const visibleRecs = recommendations.slice(0, maxVisible);
|
||||
|
||||
const handleKeyNav = useCallback((delta: number) => {
|
||||
setSelectedIndex(prev => Math.max(0, Math.min(prev + delta, visibleRecs.length - 1)));
|
||||
}, [visibleRecs.length]);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
setAnalyzing(true);
|
||||
setAnalysisProgress(0);
|
||||
setSelectedIndex(0);
|
||||
}, []);
|
||||
|
||||
const handleInstall = useCallback(() => {
|
||||
if (analyzing) return;
|
||||
const rec = visibleRecs[selectedIndex];
|
||||
if (rec) {
|
||||
// Navigate to installed after "installing"
|
||||
onNavigate('installed');
|
||||
}
|
||||
setAgents(agentList);
|
||||
setView('agents');
|
||||
setSel(0);
|
||||
};
|
||||
}, [analyzing, selectedIndex, visibleRecs, onNavigate]);
|
||||
|
||||
const installSkill = async (skillName: string, source: string, agentType?: AgentType) => {
|
||||
if (!source) {
|
||||
setMessage('Error: No source available for this skill');
|
||||
return;
|
||||
}
|
||||
|
||||
setInstalling(skillName);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
const provider = detectProvider(source);
|
||||
if (!provider) {
|
||||
setMessage(`Error: Unknown provider for ${source}`);
|
||||
setInstalling(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await provider.clone(source, '', { depth: 1 });
|
||||
|
||||
if (!result.success || !result.discoveredSkills) {
|
||||
setMessage(`Error: ${result.error || 'Failed to fetch'}`);
|
||||
setInstalling(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const skill = result.discoveredSkills.find(s => s.name === skillName);
|
||||
if (!skill) {
|
||||
setMessage(`Error: Skill ${skillName} not found in repo`);
|
||||
setInstalling(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const targetAgentType = agentType || await detectAgent();
|
||||
const adapter = getAdapter(targetAgentType);
|
||||
const installDir = getInstallDir(false, targetAgentType);
|
||||
|
||||
if (!existsSync(installDir)) {
|
||||
mkdirSync(installDir, { recursive: true });
|
||||
}
|
||||
|
||||
const targetPath = join(installDir, skillName);
|
||||
|
||||
if (existsSync(targetPath)) {
|
||||
rmSync(targetPath, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
cpSync(skill.path, targetPath, { recursive: true, dereference: true });
|
||||
|
||||
const metadata: SkillMetadata = {
|
||||
name: skillName,
|
||||
description: '',
|
||||
source: source,
|
||||
sourceType: provider.type,
|
||||
subpath: skillName,
|
||||
installedAt: new Date().toISOString(),
|
||||
enabled: true,
|
||||
};
|
||||
saveSkillMetadata(targetPath, metadata);
|
||||
|
||||
if (result.tempRoot) {
|
||||
rmSync(result.tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
setMessage(`✓ Installed ${skillName} to ${adapter.name}`);
|
||||
} catch (err) {
|
||||
setMessage(`Error: ${err instanceof Error ? err.message : 'Unknown error'}`);
|
||||
} finally {
|
||||
setInstalling(null);
|
||||
if (agentType) {
|
||||
setSelectedSkill(null);
|
||||
setView('recommendations');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || installing) return;
|
||||
|
||||
// Handle search input mode
|
||||
if (searchMode) {
|
||||
if (key.escape) {
|
||||
setSearchMode(false);
|
||||
setSearchQuery('');
|
||||
setView('recommendations');
|
||||
return;
|
||||
}
|
||||
if (key.return) {
|
||||
setSearchMode(false);
|
||||
if (searchQuery.trim()) {
|
||||
search(searchQuery);
|
||||
setView('search');
|
||||
setSel(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (key.backspace || key.delete) {
|
||||
setSearchQuery(q => q.slice(0, -1));
|
||||
return;
|
||||
}
|
||||
if (input && !key.ctrl && !key.meta) {
|
||||
setSearchQuery(q => q + input);
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Navigation
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(items.length - 1, i + 1));
|
||||
else if (key.return) {
|
||||
if (view === 'agents' && agents[sel]) {
|
||||
installSkill(selectedSkill!.name, selectedSkill!.source, agents[sel].type);
|
||||
} else if ((view === 'recommendations' || view === 'search') && items[sel]) {
|
||||
const skill = items[sel] as typeof recommendations[0];
|
||||
if (skill.skill.source) {
|
||||
installSkill(skill.skill.name, skill.skill.source);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Actions
|
||||
else if (input === '/') {
|
||||
setSearchMode(true);
|
||||
setSearchQuery('');
|
||||
}
|
||||
else if (input === 'm' && (view === 'recommendations' || view === 'search') && items[sel]) {
|
||||
const skill = items[sel] as typeof recommendations[0];
|
||||
if (skill.skill.source) {
|
||||
showAgentSelection(skill.skill.name, skill.skill.source);
|
||||
}
|
||||
}
|
||||
else if (input === 'u') {
|
||||
updateIndex();
|
||||
}
|
||||
else if (input === 'r' && view !== 'recommendations') {
|
||||
if (view === 'agents') {
|
||||
setView('recommendations');
|
||||
} else {
|
||||
setView('recommendations');
|
||||
setSearchQuery('');
|
||||
}
|
||||
setSel(0);
|
||||
}
|
||||
else if (input === 'R') {
|
||||
refresh();
|
||||
}
|
||||
useKeyboard((key: { name?: string }) => {
|
||||
if (key.name === 'j' || key.name === 'down') handleKeyNav(1);
|
||||
else if (key.name === 'k' || key.name === 'up') handleKeyNav(-1);
|
||||
else if (key.name === 'return') handleInstall();
|
||||
else if (key.name === 'r') handleRefresh();
|
||||
else if (key.name === 'escape') onNavigate('home');
|
||||
});
|
||||
|
||||
// Agent selection view
|
||||
if (view === 'agents') {
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>SELECT AGENT</Text>
|
||||
<Text dimColor>Install "{selectedSkill?.name}" to which agent?</Text>
|
||||
const divider = useMemo(() =>
|
||||
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
|
||||
[contentWidth]
|
||||
);
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{visible.map((agent, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
const a = agent as typeof agents[0];
|
||||
const status = a.detected ? '(ready)' : '(will create)';
|
||||
return (
|
||||
<Text key={a.type} inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {a.name.padEnd(20)} <Text color={colors.secondaryDim}>{status}</Text>
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=install r=back q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Score bar helper
|
||||
const getScoreBar = (score: number): string => {
|
||||
const filled = Math.round(score / 10);
|
||||
const empty = 10 - filled;
|
||||
return '█'.repeat(filled) + '░'.repeat(empty);
|
||||
// Confidence color
|
||||
const getConfColor = (conf: number) => {
|
||||
if (conf >= 80) return terminalColors.success;
|
||||
if (conf >= 60) return terminalColors.recommend;
|
||||
return terminalColors.textMuted;
|
||||
};
|
||||
|
||||
const getScoreColor = (score: number) => {
|
||||
if (score >= 70) return 'green';
|
||||
if (score >= 50) return 'yellow';
|
||||
return 'gray';
|
||||
};
|
||||
const shortcuts = isCompact
|
||||
? 'j/k nav enter install r refresh esc back'
|
||||
: 'j/k navigate enter install r refresh esc back';
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>
|
||||
{view === 'search' ? `SEARCH: "${searchQuery}"` : 'RECOMMENDATIONS'}
|
||||
</Text>
|
||||
|
||||
{/* Status bar */}
|
||||
{loading && <Text dimColor>Loading...</Text>}
|
||||
{installing && <Text>Installing {installing}...</Text>}
|
||||
{message && <Text dimColor>{message}</Text>}
|
||||
{error && <Text color="red">{error}</Text>}
|
||||
|
||||
{/* Search input */}
|
||||
{searchMode && (
|
||||
<Box marginTop={1}>
|
||||
<Text>Search: {searchQuery}</Text>
|
||||
<Text dimColor>█</Text>
|
||||
</Box>
|
||||
<box flexDirection="column" padding={1}>
|
||||
{/* Header */}
|
||||
{animPhase >= 1 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
|
||||
<text fg={terminalColors.recommend}>◎ Recommendations</text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{analyzing ? 'analyzing...' : `${recommendations.length} found`}
|
||||
</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}>AI skill suggestions</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Index status warning */}
|
||||
{indexStatus === 'missing' && !loading && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text color="yellow">No skill index found.</Text>
|
||||
<Text dimColor>Press 'u' to update index from known sources.</Text>
|
||||
</Box>
|
||||
{/* Analysis progress */}
|
||||
{animPhase >= 2 && analyzing && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text> </text>
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.accent}>{SPINNER[spinnerFrame]} </text>
|
||||
<text fg={terminalColors.text}>Analyzing</text>
|
||||
<text fg={terminalColors.textMuted}> your project...</text>
|
||||
</box>
|
||||
<text> </text>
|
||||
{divider}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{indexStatus === 'stale' && !loading && (
|
||||
<Text dimColor>Index may be outdated. Press 'u' to update.</Text>
|
||||
{/* Results summary */}
|
||||
{animPhase >= 2 && !analyzing && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text> </text>
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.success}>✓ </text>
|
||||
<text fg={terminalColors.text}>Analysis complete</text>
|
||||
<text fg={terminalColors.textMuted}> · found {recommendations.length} matching skills</text>
|
||||
</box>
|
||||
<text> </text>
|
||||
{divider}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Profile info */}
|
||||
{profile && !searchMode && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>
|
||||
Project: {profile.name}
|
||||
{profile.type ? ` (${profile.type})` : ''}
|
||||
</Text>
|
||||
{profile.stack.languages.length > 0 && (
|
||||
<Text dimColor>
|
||||
Stack: {profile.stack.languages.map(l => l.name).join(', ')}
|
||||
{profile.stack.frameworks.length > 0 && `, ${profile.stack.frameworks.map(f => f.name).join(', ')}`}
|
||||
</Text>
|
||||
{/* Recommendations list */}
|
||||
{animPhase >= 3 && !analyzing && (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>Suggested Skills</text>
|
||||
<text> </text>
|
||||
|
||||
{visibleRecs.map((rec, idx) => {
|
||||
const selected = idx === selectedIndex;
|
||||
const indicator = selected ? '▸' : ' ';
|
||||
return (
|
||||
<box key={rec.name} flexDirection="column">
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.text}>{indicator}</text>
|
||||
<text fg={selected ? terminalColors.accent : terminalColors.text}>
|
||||
{rec.name}
|
||||
</text>
|
||||
<text fg={getConfColor(rec.confidence)}> {rec.confidence}%</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}> {rec.reason}</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
|
||||
{recommendations.length > maxVisible && (
|
||||
<text fg={terminalColors.textMuted}>
|
||||
+{recommendations.length - maxVisible} more
|
||||
</text>
|
||||
)}
|
||||
</Box>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Item count */}
|
||||
{!searchMode && (
|
||||
<Text dimColor>
|
||||
{view === 'search'
|
||||
? `${searchResults.length} results`
|
||||
: `${recommendations.length} of ${totalScanned} skills matched`}
|
||||
</Text>
|
||||
{/* Footer */}
|
||||
{animPhase >= 3 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text fg={terminalColors.textMuted}>{shortcuts}</text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* List */}
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((item, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
const skill = (item as typeof recommendations[0]).skill;
|
||||
const score = (item as typeof recommendations[0]).score;
|
||||
|
||||
return (
|
||||
<Box key={skill.name} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '}
|
||||
<Text color={getScoreColor(score)}>{score.toString().padStart(3)}%</Text>
|
||||
{' '}
|
||||
<Text color={getScoreColor(score)}>{getScoreBar(score)}</Text>
|
||||
{' '}
|
||||
<Text bold>{skill.name}</Text>
|
||||
</Text>
|
||||
{isSel && skill.description && (
|
||||
<Text dimColor> {skill.description.slice(0, 60)}{skill.description.length > 60 ? '...' : ''}</Text>
|
||||
)}
|
||||
{isSel && skill.source && (
|
||||
<Text dimColor> Source: {skill.source}</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < items.length && <Text dimColor> ↓ {items.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
|
||||
{/* Help bar */}
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{view === 'search'
|
||||
? 'Enter=install m=choose agent /=search r=back u=update q=quit'
|
||||
: 'Enter=install m=choose agent /=search u=update R=refresh q=quit'}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,193 +1,140 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import TextInput from 'ink-text-input';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { loadConfig, saveConfig, AgentType as AgentTypeSchema, type SkillkitConfig, type AgentType } from '@skillkit/core';
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { useKeyboard } from '@opentui/react';
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
|
||||
interface Props {
|
||||
interface SettingsProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
interface Setting {
|
||||
id: keyof SkillkitConfig | 'agent' | 'autoSync' | 'cacheDir';
|
||||
interface SettingItem {
|
||||
key: string;
|
||||
label: string;
|
||||
type: 'select' | 'toggle' | 'text';
|
||||
options?: string[];
|
||||
value: string;
|
||||
type: 'select' | 'path' | 'toggle';
|
||||
}
|
||||
|
||||
// Get all valid agent types from the Zod schema
|
||||
const ALL_AGENTS: AgentType[] = AgentTypeSchema.options;
|
||||
|
||||
const SETTINGS: Setting[] = [
|
||||
{ id: 'agent', label: 'Default Agent', type: 'select', options: ['auto-detect', ...ALL_AGENTS] },
|
||||
{ id: 'autoSync', label: 'Auto Sync', type: 'toggle' },
|
||||
{ id: 'cacheDir', label: 'Cache Dir', type: 'text' },
|
||||
const DEFAULT_SETTINGS: SettingItem[] = [
|
||||
{ key: 'defaultAgent', label: 'Default Agent', value: 'claude-code', type: 'select' },
|
||||
{ key: 'skillsDir', label: 'Skills Directory', value: '.claude/skills', type: 'path' },
|
||||
{ key: 'autoSync', label: 'Auto Sync', value: 'enabled', type: 'toggle' },
|
||||
{ key: 'theme', label: 'Theme', value: 'dark', type: 'select' },
|
||||
{ key: 'telemetry', label: 'Telemetry', value: 'disabled', type: 'toggle' },
|
||||
];
|
||||
|
||||
export function Settings(_props: Props) {
|
||||
const [config, setConfig] = useState<SkillkitConfig | null>(null);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [editValue, setEditValue] = useState('');
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
export function Settings({ onNavigate, cols = 80 }: SettingsProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [settings, setSettings] = useState<SettingItem[]>(DEFAULT_SETTINGS);
|
||||
const [animPhase, setAnimPhase] = useState(0);
|
||||
|
||||
const isCompact = cols < 60;
|
||||
const contentWidth = Math.max(1, Math.min(cols - 4, 60));
|
||||
|
||||
// Load config on mount
|
||||
useEffect(() => {
|
||||
try {
|
||||
const loaded = loadConfig();
|
||||
setConfig(loaded);
|
||||
} catch (err) {
|
||||
setError(`Failed to load config: ${err}`);
|
||||
if (animPhase >= 2) return;
|
||||
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [animPhase]);
|
||||
|
||||
const handleKeyNav = useCallback((delta: number) => {
|
||||
setSelectedIndex(prev => Math.max(0, Math.min(prev + delta, settings.length - 1)));
|
||||
}, [settings.length]);
|
||||
|
||||
const handleToggle = useCallback(() => {
|
||||
const setting = settings[selectedIndex];
|
||||
if (setting?.type === 'toggle') {
|
||||
setSettings(prev => prev.map((s, i) =>
|
||||
i === selectedIndex ? { ...s, value: s.value === 'enabled' ? 'disabled' : 'enabled' } : s
|
||||
));
|
||||
}
|
||||
}, [selectedIndex, settings]);
|
||||
|
||||
const handleReset = useCallback(() => {
|
||||
setSettings(DEFAULT_SETTINGS);
|
||||
}, []);
|
||||
|
||||
const getCurrentValue = (setting: Setting): string => {
|
||||
if (!config) return '';
|
||||
const handleKeyboard = useCallback((key: { name?: string }) => {
|
||||
if (key.name === 'j' || key.name === 'down') handleKeyNav(1);
|
||||
else if (key.name === 'k' || key.name === 'up') handleKeyNav(-1);
|
||||
else if (key.name === 'return') handleToggle();
|
||||
else if (key.name === 'r') handleReset();
|
||||
else if (key.name === 'escape') onNavigate('home');
|
||||
}, [handleKeyNav, handleToggle, handleReset, onNavigate]);
|
||||
|
||||
switch (setting.id) {
|
||||
case 'agent':
|
||||
// Map 'universal' back to 'auto-detect' for display consistency
|
||||
return config.agent === 'universal' ? 'auto-detect' : (config.agent || 'auto-detect');
|
||||
case 'autoSync':
|
||||
return config.autoSync ? 'enabled' : 'disabled';
|
||||
case 'cacheDir':
|
||||
return config.cacheDir || '~/.skillkit/cache';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
useKeyboard(handleKeyboard);
|
||||
|
||||
const handleSave = (setting: Setting, value: string) => {
|
||||
if (!config) return;
|
||||
const divider = useMemo(() =>
|
||||
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
|
||||
[contentWidth]
|
||||
);
|
||||
|
||||
const newConfig = { ...config };
|
||||
|
||||
switch (setting.id) {
|
||||
case 'agent':
|
||||
if (value === 'auto-detect') {
|
||||
newConfig.agent = 'universal';
|
||||
} else {
|
||||
newConfig.agent = value as AgentType;
|
||||
}
|
||||
break;
|
||||
case 'autoSync':
|
||||
newConfig.autoSync = value === 'enabled';
|
||||
break;
|
||||
case 'cacheDir':
|
||||
newConfig.cacheDir = value || undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
saveConfig(newConfig, false);
|
||||
setConfig(newConfig);
|
||||
setSaved(true);
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
} catch (err) {
|
||||
setError(`Failed to save: ${err}`);
|
||||
setTimeout(() => setError(null), 3000);
|
||||
}
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (editing) {
|
||||
if (key.return) {
|
||||
handleSave(SETTINGS[sel], editValue);
|
||||
setEditing(false);
|
||||
} else if (key.escape) {
|
||||
setEditing(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.upArrow) {
|
||||
setSel(i => Math.max(0, i - 1));
|
||||
} else if (key.downArrow) {
|
||||
setSel(i => Math.min(SETTINGS.length - 1, i + 1));
|
||||
} else if (key.return || input === ' ') {
|
||||
const setting = SETTINGS[sel];
|
||||
|
||||
if (setting.type === 'toggle') {
|
||||
const current = getCurrentValue(setting);
|
||||
const newValue = current === 'enabled' ? 'disabled' : 'enabled';
|
||||
handleSave(setting, newValue);
|
||||
} else if (setting.type === 'select' && setting.options) {
|
||||
const current = getCurrentValue(setting);
|
||||
const idx = setting.options.indexOf(current);
|
||||
const nextIdx = (idx + 1) % setting.options.length;
|
||||
handleSave(setting, setting.options[nextIdx]);
|
||||
} else if (setting.type === 'text') {
|
||||
setEditValue(getCurrentValue(setting));
|
||||
setEditing(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (!config) {
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>SETTINGS</Text>
|
||||
{error ? (
|
||||
<Text color={colors.danger}>{symbols.error} {error}</Text>
|
||||
) : (
|
||||
<Text dimColor>Loading...</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const shortcuts = isCompact
|
||||
? 'j/k nav enter toggle r reset esc back'
|
||||
: 'j/k navigate enter toggle r reset defaults esc back';
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>SETTINGS</Text>
|
||||
<Text dimColor>Configure SkillKit (changes save automatically)</Text>
|
||||
<box flexDirection="column" padding={1}>
|
||||
{/* Header */}
|
||||
{animPhase >= 1 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
|
||||
<text fg={terminalColors.text}>⚙ Settings</text>
|
||||
<text fg={terminalColors.textMuted}>{settings.length} options</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}>configure skillkit</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{SETTINGS.map((s, i) => {
|
||||
const isSel = i === sel;
|
||||
const value = getCurrentValue(s);
|
||||
const isEditing = editing && isSel;
|
||||
{/* Settings list */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text> </text>
|
||||
<text fg={terminalColors.text}>Configuration</text>
|
||||
<text> </text>
|
||||
|
||||
return (
|
||||
<Box key={s.id}>
|
||||
<Text inverse={isSel && !isEditing}>
|
||||
{isSel ? symbols.pointer : ' '}{s.label.padEnd(16)}
|
||||
</Text>
|
||||
{isEditing ? (
|
||||
<Box marginLeft={1}>
|
||||
<TextInput
|
||||
value={editValue}
|
||||
onChange={setEditValue}
|
||||
onSubmit={() => {
|
||||
handleSave(s, editValue);
|
||||
setEditing(false);
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
) : (
|
||||
<Text color={colors.secondaryDim}> {value}</Text>
|
||||
)}
|
||||
{s.type === 'toggle' && isSel && !isEditing && (
|
||||
<Text dimColor> (space to toggle)</Text>
|
||||
)}
|
||||
{s.type === 'select' && isSel && !isEditing && (
|
||||
<Text dimColor> (enter to cycle)</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
{settings.map((setting, idx) => {
|
||||
const selected = idx === selectedIndex;
|
||||
const indicator = selected ? '▸' : ' ';
|
||||
const valueColor = setting.type === 'toggle'
|
||||
? (setting.value === 'enabled' ? terminalColors.success : terminalColors.textMuted)
|
||||
: terminalColors.textMuted;
|
||||
const toggleIcon = setting.type === 'toggle'
|
||||
? (setting.value === 'enabled' ? '● ' : '○ ')
|
||||
: '';
|
||||
return (
|
||||
<box key={setting.key} flexDirection="row">
|
||||
<text fg={terminalColors.text}>{indicator}</text>
|
||||
<text fg={selected ? terminalColors.accent : terminalColors.text} width={18}>
|
||||
{setting.label}
|
||||
</text>
|
||||
<text fg={valueColor}>{toggleIcon}{setting.value}</text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
{saved && <Text color={colors.success}>{symbols.check} Settings saved</Text>}
|
||||
{error && <Text color={colors.danger}>{symbols.error} {error}</Text>}
|
||||
{!saved && !error && (
|
||||
<Text dimColor>
|
||||
{editing ? 'Enter=save Esc=cancel' : 'Enter/Space=edit q=quit'}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
{/* Config location */}
|
||||
{animPhase >= 2 && !isCompact && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text fg={terminalColors.textMuted}>config: ~/.config/skillkit/config.json</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text fg={terminalColors.textMuted}>{shortcuts}</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,78 +1,185 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { getAllAdapters } from '@skillkit/agents';
|
||||
/**
|
||||
* Sync Screen - Cross-Agent Synchronization
|
||||
* Clean monochromatic design
|
||||
*/
|
||||
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
|
||||
import { useKeyboard } from '@opentui/react';
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { AGENT_LOGOS } from '../theme/symbols.js';
|
||||
|
||||
interface AgentStatus {
|
||||
name: string;
|
||||
type: string;
|
||||
detected: boolean;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
interface SyncProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Sync({ rows = 24 }: Props) {
|
||||
const [agents, setAgents] = useState<AgentStatus[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
||||
|
||||
const maxVisible = Math.max(5, rows - 6);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), agents.length - maxVisible));
|
||||
const visible = agents.slice(start, start + maxVisible);
|
||||
export function Sync({ onNavigate, cols = 80, rows = 24 }: SyncProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [syncStatus, setSyncStatus] = useState<'idle' | 'syncing' | 'done'>('idle');
|
||||
const [spinnerFrame, setSpinnerFrame] = useState(0);
|
||||
const [animPhase, setAnimPhase] = useState(0);
|
||||
const syncTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const isCompact = cols < 60;
|
||||
const contentWidth = Math.max(1, Math.min(cols - 4, 60));
|
||||
|
||||
// Cleanup timeout on unmount
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const adapters = getAllAdapters();
|
||||
const s: AgentStatus[] = [];
|
||||
for (const a of adapters) {
|
||||
s.push({ name: a.name, type: a.type, detected: await a.isDetected() });
|
||||
return () => {
|
||||
if (syncTimeoutRef.current) {
|
||||
clearTimeout(syncTimeoutRef.current);
|
||||
}
|
||||
setAgents(s);
|
||||
setLoading(false);
|
||||
})();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || syncing) return;
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(agents.length - 1, i + 1));
|
||||
else if (input === 'a') { setSyncing(true); setTimeout(() => setSyncing(false), 500); }
|
||||
else if (key.return && agents[sel]?.detected) { setSyncing(true); setTimeout(() => setSyncing(false), 300); }
|
||||
// Entrance animation
|
||||
useEffect(() => {
|
||||
if (animPhase >= 2) return;
|
||||
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [animPhase]);
|
||||
|
||||
// Spinner animation
|
||||
useEffect(() => {
|
||||
if (syncStatus !== 'syncing') return;
|
||||
const interval = setInterval(() => {
|
||||
setSpinnerFrame(f => (f + 1) % SPINNER.length);
|
||||
}, 80);
|
||||
return () => clearInterval(interval);
|
||||
}, [syncStatus]);
|
||||
|
||||
// Agents with sync data
|
||||
const agents = useMemo(() => {
|
||||
const agentTypes = ['claude-code', 'cursor', 'github-copilot', 'codex', 'gemini-cli', 'windsurf'];
|
||||
return agentTypes.slice(0, isCompact ? 4 : 6).map((type) => ({
|
||||
type,
|
||||
...(AGENT_LOGOS[type] || { name: type, icon: '◇' }),
|
||||
synced: type === 'claude-code' || type === 'cursor',
|
||||
skillCount: type === 'claude-code' ? 12 : type === 'cursor' ? 8 : 0,
|
||||
}));
|
||||
}, [isCompact]);
|
||||
|
||||
const syncedCount = agents.filter(a => a.synced).length;
|
||||
const totalSkills = agents.reduce((sum, a) => sum + a.skillCount, 0);
|
||||
|
||||
const handleKeyNav = useCallback((delta: number) => {
|
||||
setSelectedIndex(prev => Math.max(0, Math.min(prev + delta, agents.length - 1)));
|
||||
}, [agents.length]);
|
||||
|
||||
const handleSync = useCallback(() => {
|
||||
if (syncStatus === 'syncing') return;
|
||||
if (syncTimeoutRef.current) clearTimeout(syncTimeoutRef.current);
|
||||
setSyncStatus('syncing');
|
||||
syncTimeoutRef.current = setTimeout(() => setSyncStatus('done'), 1500);
|
||||
}, [syncStatus]);
|
||||
|
||||
const handleSyncAll = useCallback(() => {
|
||||
if (syncStatus === 'syncing') return;
|
||||
if (syncTimeoutRef.current) clearTimeout(syncTimeoutRef.current);
|
||||
setSyncStatus('syncing');
|
||||
syncTimeoutRef.current = setTimeout(() => setSyncStatus('done'), 2000);
|
||||
}, [syncStatus]);
|
||||
|
||||
// Clamp selectedIndex when agents list shrinks
|
||||
useEffect(() => {
|
||||
setSelectedIndex(prev => Math.max(0, Math.min(prev, agents.length - 1)));
|
||||
}, [agents.length]);
|
||||
|
||||
useKeyboard((key: { name?: string }) => {
|
||||
if (key.name === 'j' || key.name === 'down') handleKeyNav(1);
|
||||
else if (key.name === 'k' || key.name === 'up') handleKeyNav(-1);
|
||||
else if (key.name === 'return') handleSync();
|
||||
else if (key.name === 'a') handleSyncAll();
|
||||
else if (key.name === 'escape') onNavigate('home');
|
||||
});
|
||||
|
||||
const detected = agents.filter(a => a.detected).length;
|
||||
const divider = useMemo(() =>
|
||||
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
|
||||
[contentWidth]
|
||||
);
|
||||
|
||||
const shortcuts = isCompact
|
||||
? 'j/k nav enter sync a sync all esc back'
|
||||
: 'j/k navigate enter sync selected a sync all esc back';
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>SYNC SKILLS</Text>
|
||||
<Text dimColor>{detected}/{agents.length} agents detected</Text>
|
||||
|
||||
{loading && <Text>Detecting agents...</Text>}
|
||||
{syncing && <Text>Syncing...</Text>}
|
||||
|
||||
{!loading && !syncing && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((agent, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
return (
|
||||
<Text key={agent.type} inverse={isSel} dimColor={!agent.detected}>
|
||||
{isSel ? symbols.pointer : ' '}{agent.detected ? symbols.checkboxOn : symbols.checkboxOff} {agent.name.padEnd(20)} {agent.detected ? 'Ready' : 'N/A'}
|
||||
</Text>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < agents.length && <Text dimColor> ↓ {agents.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
<box flexDirection="column" padding={1}>
|
||||
{/* Header */}
|
||||
{animPhase >= 1 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
|
||||
<text fg={terminalColors.sync}>⇄ Sync</text>
|
||||
<text fg={terminalColors.textMuted}>{syncedCount}/{agents.length} synced</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}>share skills across agents</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=sync a=all q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
{/* Status */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text> </text>
|
||||
{syncStatus === 'syncing' ? (
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.accent}>{SPINNER[spinnerFrame]} </text>
|
||||
<text fg={terminalColors.text}>Syncing skills...</text>
|
||||
</box>
|
||||
) : syncStatus === 'done' ? (
|
||||
<box flexDirection="row">
|
||||
<text fg={terminalColors.success}>✓ </text>
|
||||
<text fg={terminalColors.text}>Sync complete</text>
|
||||
<text fg={terminalColors.textMuted}> · {totalSkills} skills synced</text>
|
||||
</box>
|
||||
) : (
|
||||
<box flexDirection="row" gap={3}>
|
||||
<text fg={terminalColors.success}>● {syncedCount} synced</text>
|
||||
<text fg={terminalColors.textMuted}>○ {agents.length - syncedCount} pending</text>
|
||||
</box>
|
||||
)}
|
||||
<text> </text>
|
||||
{divider}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Agents list */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>Agents</text>
|
||||
<text> </text>
|
||||
|
||||
{agents.map((agent, idx) => {
|
||||
const selected = idx === selectedIndex;
|
||||
const indicator = selected ? '▸' : ' ';
|
||||
const statusIcon = agent.synced ? '●' : '○';
|
||||
const statusColor = agent.synced ? terminalColors.success : terminalColors.textMuted;
|
||||
return (
|
||||
<box key={agent.type} flexDirection="row">
|
||||
<text fg={terminalColors.text}>{indicator}</text>
|
||||
<text fg={selected ? terminalColors.accent : terminalColors.text}>
|
||||
{agent.icon} {agent.name}
|
||||
</text>
|
||||
<text fg={statusColor}> {statusIcon}</text>
|
||||
<text fg={terminalColors.textMuted}> {agent.skillCount} skills</text>
|
||||
</box>
|
||||
);
|
||||
})}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text fg={terminalColors.textMuted}>{shortcuts}</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,221 +1,59 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
/**
|
||||
* Team Screen
|
||||
* Team collaboration
|
||||
*/
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { Header } from '../components/Header.js';
|
||||
|
||||
interface SharedSkill {
|
||||
name: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
author: string;
|
||||
downloads?: number;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
interface TeamConfig {
|
||||
teamId: string;
|
||||
teamName: string;
|
||||
registryUrl: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
interface TeamProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Team({ rows = 24 }: Props) {
|
||||
const [config, setConfig] = useState<TeamConfig | null>(null);
|
||||
const [skills, setSkills] = useState<SharedSkill[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
const maxVisible = Math.max(5, rows - 12);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), skills.length - maxVisible));
|
||||
const visible = skills.slice(start, start + maxVisible);
|
||||
|
||||
useEffect(() => {
|
||||
loadTeam();
|
||||
}, []);
|
||||
|
||||
const loadTeam = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const { createTeamManager } = await import('@skillkit/core');
|
||||
const manager = createTeamManager(process.cwd());
|
||||
const teamConfig = manager.load();
|
||||
|
||||
if (!teamConfig) {
|
||||
setConfig(null);
|
||||
setSkills([]);
|
||||
setError('Team not initialized. Run `skillkit team init` first.');
|
||||
} else {
|
||||
setConfig(teamConfig);
|
||||
const sharedSkills = manager.listSharedSkills();
|
||||
setSkills(sharedSkills);
|
||||
setSel(s => Math.min(s, Math.max(0, sharedSkills.length - 1)));
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load team');
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const syncTeam = async () => {
|
||||
if (!config) return;
|
||||
setLoading(true);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
const { createTeamManager } = await import('@skillkit/core');
|
||||
const manager = createTeamManager(process.cwd());
|
||||
manager.load(); // Load config before sync
|
||||
const result = await manager.sync();
|
||||
|
||||
const changes = [...result.added, ...result.updated];
|
||||
if (changes.length > 0) {
|
||||
setMessage(`Synced: ${changes.join(', ')}`);
|
||||
} else {
|
||||
setMessage('Already up to date');
|
||||
}
|
||||
|
||||
// Reload skills
|
||||
const sharedSkills = manager.listSharedSkills();
|
||||
setSkills(sharedSkills);
|
||||
setSel(s => Math.min(s, Math.max(0, sharedSkills.length - 1)));
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Sync failed');
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const importSkill = async (skillName: string) => {
|
||||
if (!config) return;
|
||||
setLoading(true);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
const { createTeamManager } = await import('@skillkit/core');
|
||||
const manager = createTeamManager(process.cwd());
|
||||
manager.load(); // Load config before import
|
||||
const result = await manager.importSkill(skillName, { overwrite: false });
|
||||
|
||||
if (result.success) {
|
||||
setMessage(`Imported: ${skillName}`);
|
||||
} else {
|
||||
setError(result.error || 'Import failed');
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Import failed');
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading) return;
|
||||
if (skills.length === 0 && (key.upArrow || key.downArrow)) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(Math.max(0, skills.length - 1), i + 1));
|
||||
else if (input === 'r') loadTeam();
|
||||
else if (input === 's') syncTeam();
|
||||
else if (key.return && skills[sel]) {
|
||||
importSkill(skills[sel].name);
|
||||
}
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color={colors.primary} bold>Team Collaboration</Text>
|
||||
<Box marginTop={1}>
|
||||
<Text color={colors.secondaryDim}>{symbols.spinner[0]} Loading...</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (!config) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color={colors.primary} bold>Team Collaboration</Text>
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text color={colors.secondaryDim}>{symbols.warning} Team not initialized</Text>
|
||||
<Text color={colors.secondaryDim} dimColor>
|
||||
Run: skillkit team init --name "Team Name" --registry <url>
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>[r] Refresh</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
export function Team({ onNavigate, cols = 80, rows = 24 }: TeamProps) {
|
||||
const members = [
|
||||
{ name: 'You', role: 'Owner', status: 'online', skills: 12 },
|
||||
{ name: 'Alice', role: 'Admin', status: 'online', skills: 8 },
|
||||
{ name: 'Bob', role: 'Member', status: 'offline', skills: 5 },
|
||||
];
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color={colors.primary} bold>Team: {config.teamName}</Text>
|
||||
<Text color={colors.secondaryDim} dimColor>Registry: {config.registryUrl}</Text>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<Header
|
||||
title="Team"
|
||||
subtitle="Collaborate with your development team"
|
||||
count={members.length}
|
||||
icon="◉"
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="red">{symbols.error} {error}</Text>
|
||||
</Box>
|
||||
)}
|
||||
<text fg={terminalColors.text}><b>Team Members</b></text>
|
||||
<text> </text>
|
||||
|
||||
{message && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="green">{symbols.success} {message}</Text>
|
||||
</Box>
|
||||
)}
|
||||
{members.map((member, idx) => (
|
||||
<box key={member.name} flexDirection="row" marginBottom={1}>
|
||||
<text
|
||||
fg={idx === 0 ? terminalColors.accent : terminalColors.text}
|
||||
width={15}
|
||||
>
|
||||
{idx === 0 ? '\u25B8 ' : ' '}{member.name}
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted} width={10}>{member.role}</text>
|
||||
<text
|
||||
fg={member.status === 'online' ? terminalColors.success : terminalColors.textMuted}
|
||||
width={10}
|
||||
>
|
||||
{member.status === 'online' ? '\u25CF online' : '\u25CB offline'}
|
||||
</text>
|
||||
<text fg={terminalColors.textMuted}>{member.skills} skills</text>
|
||||
</box>
|
||||
))}
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text color={colors.secondaryDim} bold>
|
||||
Shared Skills ({skills.length})
|
||||
</Text>
|
||||
|
||||
{skills.length === 0 ? (
|
||||
<Text color={colors.secondaryDim} dimColor>
|
||||
No shared skills. Use `skillkit team share --name <skill>` to share.
|
||||
</Text>
|
||||
) : (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
{visible.map((skill, i) => {
|
||||
const actualIndex = start + i;
|
||||
const isSelected = actualIndex === sel;
|
||||
return (
|
||||
<Box key={skill.name} flexDirection="column">
|
||||
<Text>
|
||||
{isSelected ? symbols.pointer : ' '}{' '}
|
||||
<Text color={isSelected ? colors.primary : colors.secondaryDim} bold={isSelected}>
|
||||
{skill.name}
|
||||
</Text>
|
||||
<Text dimColor> v{skill.version}</Text>
|
||||
<Text dimColor> by {skill.author}</Text>
|
||||
{skill.downloads !== undefined && (
|
||||
<Text dimColor> | {skill.downloads} downloads</Text>
|
||||
)}
|
||||
</Text>
|
||||
{skill.description && isSelected && (
|
||||
<Text color={colors.secondaryDim} dimColor> {skill.description}</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1} borderStyle="single" borderColor={colors.borderDim} paddingX={1}>
|
||||
<Text dimColor>
|
||||
[↑↓] Navigate [Enter] Import [s] Sync [r] Refresh
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
Press 'i' to invite, 's' to share skills
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,286 +1,64 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import {
|
||||
translateSkill,
|
||||
getSupportedTranslationAgents,
|
||||
type AgentType,
|
||||
} from '@skillkit/core';
|
||||
import { getAllAdapters, getAdapter } from '@skillkit/agents';
|
||||
import { getInstallDir } from '../helpers.js';
|
||||
/**
|
||||
* Translate Screen
|
||||
* Skill format conversion with diff view
|
||||
*/
|
||||
import { useState } from 'react';
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
import { AGENT_LOGOS } from '../theme/symbols.js';
|
||||
import { Header } from '../components/Header.js';
|
||||
|
||||
type View = 'skills' | 'agents' | 'preview' | 'result';
|
||||
|
||||
interface InstalledSkill {
|
||||
name: string;
|
||||
path: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
interface TranslateProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Translate({ rows = 24 }: Props) {
|
||||
const [view, setView] = useState<View>('skills');
|
||||
const [skills, setSkills] = useState<InstalledSkill[]>([]);
|
||||
const [agents, setAgents] = useState<{ type: AgentType; name: string }[]>([]);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [selectedSkill, setSelectedSkill] = useState<InstalledSkill | null>(null);
|
||||
const [selectedAgent, setSelectedAgent] = useState<{ type: AgentType; name: string } | null>(null);
|
||||
const [preview, setPreview] = useState<string>('');
|
||||
const [result, setResult] = useState<{ success: boolean; message: string; path?: string } | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
export function Translate(_props: TranslateProps) {
|
||||
const [sourceAgent] = useState('claude-code');
|
||||
const [targetAgent] = useState('cursor');
|
||||
|
||||
useEffect(() => {
|
||||
const loadSkills = () => {
|
||||
const installDir = getInstallDir(false);
|
||||
const foundSkills: InstalledSkill[] = [];
|
||||
|
||||
if (existsSync(installDir)) {
|
||||
const dirs = readdirSync(installDir, { withFileTypes: true })
|
||||
.filter(d => d.isDirectory())
|
||||
.map(d => d.name);
|
||||
|
||||
for (const dir of dirs) {
|
||||
const skillPath = join(installDir, dir);
|
||||
const skillMdPath = join(skillPath, 'SKILL.md');
|
||||
|
||||
if (existsSync(skillMdPath)) {
|
||||
const content = readFileSync(skillMdPath, 'utf-8');
|
||||
foundSkills.push({
|
||||
name: dir,
|
||||
path: skillPath,
|
||||
content,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setSkills(foundSkills);
|
||||
};
|
||||
|
||||
loadSkills();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const adapters = getAllAdapters();
|
||||
const supportedAgents = getSupportedTranslationAgents();
|
||||
const agentList = adapters
|
||||
.filter(a => supportedAgents.includes(a.type as AgentType))
|
||||
.map(a => ({
|
||||
type: a.type as AgentType,
|
||||
name: a.name,
|
||||
}));
|
||||
setAgents(agentList);
|
||||
}, []);
|
||||
|
||||
const currentItems = view === 'skills' ? skills : agents;
|
||||
const maxVisible = Math.max(5, rows - 12);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), currentItems.length - maxVisible));
|
||||
const visible = currentItems.slice(start, start + maxVisible);
|
||||
|
||||
const generatePreview = (skill: InstalledSkill, agent: { type: AgentType; name: string }) => {
|
||||
try {
|
||||
const result = translateSkill(skill.content, agent.type, { sourceFilename: 'SKILL.md' });
|
||||
return result.content;
|
||||
} catch (err) {
|
||||
return `Error: ${err instanceof Error ? err.message : 'Translation failed'}`;
|
||||
}
|
||||
};
|
||||
|
||||
const executeTranslation = () => {
|
||||
if (!selectedSkill || !selectedAgent) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const translationResult = translateSkill(selectedSkill.content, selectedAgent.type, {
|
||||
sourceFilename: 'SKILL.md',
|
||||
});
|
||||
|
||||
if (!translationResult.success) {
|
||||
setResult({
|
||||
success: false,
|
||||
message: `Translation failed: ${translationResult.warnings.join(', ')}`,
|
||||
});
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const adapter = getAdapter(selectedAgent.type);
|
||||
const targetDir = adapter?.skillsDir
|
||||
? join(process.cwd(), adapter.skillsDir)
|
||||
: join(process.cwd(), `.${selectedAgent.type}/skills/`);
|
||||
|
||||
if (!existsSync(targetDir)) {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
}
|
||||
|
||||
const filename = translationResult.filename || `${selectedSkill.name}.md`;
|
||||
const targetPath = join(targetDir, filename);
|
||||
|
||||
writeFileSync(targetPath, translationResult.content, 'utf-8');
|
||||
|
||||
setResult({
|
||||
success: true,
|
||||
message: `Translated ${selectedSkill.name} to ${selectedAgent.name} format`,
|
||||
path: targetPath,
|
||||
});
|
||||
} catch (err) {
|
||||
setResult({
|
||||
success: false,
|
||||
message: `Error: ${err instanceof Error ? err.message : 'Unknown error'}`,
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setView('result');
|
||||
}
|
||||
};
|
||||
|
||||
useInput((_input, key) => {
|
||||
if (loading) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(currentItems.length - 1, i + 1));
|
||||
else if (key.escape) {
|
||||
if (view === 'result') {
|
||||
setView('skills');
|
||||
setSelectedSkill(null);
|
||||
setSelectedAgent(null);
|
||||
setResult(null);
|
||||
setSel(0);
|
||||
} else if (view === 'preview') {
|
||||
setView('agents');
|
||||
} else if (view === 'agents') {
|
||||
setView('skills');
|
||||
setSelectedSkill(null);
|
||||
}
|
||||
}
|
||||
else if (key.return) {
|
||||
if (view === 'skills' && skills[sel]) {
|
||||
setSelectedSkill(skills[sel]);
|
||||
setView('agents');
|
||||
setSel(0);
|
||||
} else if (view === 'agents' && agents[sel]) {
|
||||
setSelectedAgent(agents[sel]);
|
||||
const previewContent = generatePreview(selectedSkill!, agents[sel]);
|
||||
setPreview(previewContent);
|
||||
setView('preview');
|
||||
} else if (view === 'preview') {
|
||||
executeTranslation();
|
||||
} else if (view === 'result') {
|
||||
setView('skills');
|
||||
setSelectedSkill(null);
|
||||
setSelectedAgent(null);
|
||||
setResult(null);
|
||||
setSel(0);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (view === 'result' && result) {
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>TRANSLATION {result.success ? 'COMPLETE' : 'FAILED'}</Text>
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text color={result.success ? 'green' : 'red'}>
|
||||
{result.success ? '✓' : '✗'} {result.message}
|
||||
</Text>
|
||||
{result.path && (
|
||||
<Text dimColor>Saved to: {result.path}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={2}>
|
||||
<Text dimColor>Press Enter or Esc to continue</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (view === 'preview') {
|
||||
const previewLines = preview.split('\n').slice(0, maxVisible);
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>TRANSLATION PREVIEW</Text>
|
||||
<Text dimColor>
|
||||
{selectedSkill?.name} → {selectedAgent?.name}
|
||||
</Text>
|
||||
|
||||
<Box marginTop={1} flexDirection="column" borderStyle="single" paddingX={1}>
|
||||
{previewLines.map((line, i) => (
|
||||
<Text key={i} dimColor>{line.slice(0, 70)}</Text>
|
||||
))}
|
||||
{preview.split('\n').length > maxVisible && (
|
||||
<Text dimColor>... ({preview.split('\n').length - maxVisible} more lines)</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=confirm translation Esc=back</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
const sourceInfo = AGENT_LOGOS[sourceAgent];
|
||||
const targetInfo = AGENT_LOGOS[targetAgent];
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>
|
||||
{view === 'skills' ? 'TRANSLATE SKILL' : 'SELECT TARGET AGENT'}
|
||||
</Text>
|
||||
<box flexDirection="column" paddingLeft={1}>
|
||||
<Header
|
||||
title="Translate Skills"
|
||||
subtitle="Convert skills between agent formats"
|
||||
icon="⇄"
|
||||
/>
|
||||
|
||||
{view === 'skills' && (
|
||||
<Text dimColor>Select a skill to translate to another agent format</Text>
|
||||
)}
|
||||
<box flexDirection="row" marginTop={1} marginBottom={1}>
|
||||
<box flexDirection="column" width={25}>
|
||||
<text fg={terminalColors.textMuted}>Source Agent</text>
|
||||
<text fg={terminalColors.accent}>
|
||||
<b>{sourceInfo?.icon} {sourceInfo?.name}</b>
|
||||
</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}> → </text>
|
||||
<box flexDirection="column" width={25}>
|
||||
<text fg={terminalColors.textMuted}>Target Agent</text>
|
||||
<text fg={terminalColors.text}>
|
||||
<b>{targetInfo?.icon} {targetInfo?.name}</b>
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
|
||||
{view === 'agents' && selectedSkill && (
|
||||
<Text dimColor>Translate "{selectedSkill.name}" to which agent format?</Text>
|
||||
)}
|
||||
<text fg={terminalColors.textMuted}>
|
||||
{'\u2500'.repeat(50)}
|
||||
</text>
|
||||
<text> </text>
|
||||
|
||||
{skills.length === 0 && view === 'skills' && (
|
||||
<Box marginTop={1}>
|
||||
<Text color="yellow">No skills installed. Install some skills first with 'skillkit install'</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((item, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
|
||||
if (view === 'skills') {
|
||||
const skill = item as InstalledSkill;
|
||||
return (
|
||||
<Text key={skill.name} inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {skill.name}
|
||||
</Text>
|
||||
);
|
||||
} else {
|
||||
const agent = item as { type: AgentType; name: string };
|
||||
return (
|
||||
<Text key={agent.type} inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {agent.name.padEnd(20)} <Text dimColor>({agent.type})</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
})}
|
||||
{start + maxVisible < currentItems.length && (
|
||||
<Text dimColor> ↓ {currentItems.length - start - maxVisible} more</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
{view === 'skills'
|
||||
? 'Enter=select skill q=quit'
|
||||
: 'Enter=select agent Esc=back q=quit'}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
<text fg={terminalColors.text}><b>Select a skill to translate:</b></text>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
No skills selected. Press 'i' to view installed skills.
|
||||
</text>
|
||||
<text> </text>
|
||||
<text fg={terminalColors.textMuted}>
|
||||
Use Tab to switch agents, Enter to translate
|
||||
</text>
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,96 +1,133 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import { colors, symbols } from '../theme.js';
|
||||
import { listWorkflows, type Workflow as WorkflowType } from '@skillkit/core';
|
||||
/**
|
||||
* Workflow Screen - Automation Builder
|
||||
* Clean monochromatic design
|
||||
*/
|
||||
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
import { useKeyboard } from '@opentui/react';
|
||||
import { type Screen } from '../state/index.js';
|
||||
import { terminalColors } from '../theme/colors.js';
|
||||
|
||||
interface Props {
|
||||
interface WorkflowProps {
|
||||
onNavigate: (screen: Screen) => void;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function Workflow({ rows = 24 }: Props) {
|
||||
const [workflows, setWorkflows] = useState<WorkflowType[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [sel, setSel] = useState(0);
|
||||
const [running, setRunning] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const WORKFLOWS = [
|
||||
{ name: 'test-and-commit', steps: 3, lastRun: '1 hour ago', status: 'success' as const },
|
||||
{ name: 'deploy-preview', steps: 5, lastRun: '2 hours ago', status: 'success' as const },
|
||||
{ name: 'full-ci', steps: 8, lastRun: '1 day ago', status: 'failed' as const },
|
||||
{ name: 'quick-fix', steps: 2, lastRun: '3 days ago', status: 'pending' as const },
|
||||
];
|
||||
|
||||
const maxVisible = Math.max(5, rows - 8);
|
||||
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), workflows.length - maxVisible));
|
||||
const visible = workflows.slice(start, start + maxVisible);
|
||||
export function Workflow({ onNavigate, cols = 80, rows = 24 }: WorkflowProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const [animPhase, setAnimPhase] = useState(0);
|
||||
|
||||
const isCompact = cols < 60;
|
||||
const contentWidth = Math.max(1, Math.min(cols - 4, 60));
|
||||
|
||||
// Entrance animation
|
||||
useEffect(() => {
|
||||
loadWorkflows();
|
||||
if (animPhase >= 2) return;
|
||||
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
|
||||
return () => clearTimeout(timer);
|
||||
}, [animPhase]);
|
||||
|
||||
const successCount = WORKFLOWS.filter(w => w.status === 'success').length;
|
||||
const failedCount = WORKFLOWS.filter(w => w.status === 'failed').length;
|
||||
|
||||
const handleKeyNav = useCallback((delta: number) => {
|
||||
setSelectedIndex(prev => Math.max(0, Math.min(prev + delta, WORKFLOWS.length - 1)));
|
||||
}, []);
|
||||
|
||||
const loadWorkflows = () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const wfs = listWorkflows(process.cwd());
|
||||
setWorkflows(wfs);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to load workflows');
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
useInput((input, key) => {
|
||||
if (loading || running) return;
|
||||
|
||||
if (key.upArrow) setSel(i => Math.max(0, i - 1));
|
||||
else if (key.downArrow) setSel(i => Math.min(workflows.length - 1, i + 1));
|
||||
else if (input === 'r') loadWorkflows();
|
||||
else if (key.return && workflows[sel]) {
|
||||
// Simulate running workflow
|
||||
setRunning(workflows[sel].name);
|
||||
setTimeout(() => setRunning(null), 2000);
|
||||
}
|
||||
useKeyboard((key: { name?: string }) => {
|
||||
if (key.name === 'j' || key.name === 'down') handleKeyNav(1);
|
||||
else if (key.name === 'k' || key.name === 'up') handleKeyNav(-1);
|
||||
else if (key.name === 'escape') onNavigate('home');
|
||||
});
|
||||
|
||||
const divider = useMemo(() =>
|
||||
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
|
||||
[contentWidth]
|
||||
);
|
||||
|
||||
const shortcuts = isCompact
|
||||
? 'j/k nav esc back'
|
||||
: 'j/k navigate esc back';
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Text bold color={colors.primary}>WORKFLOWS</Text>
|
||||
<Text dimColor>{workflows.length} workflow(s) found</Text>
|
||||
|
||||
{loading && <Text>Loading workflows...</Text>}
|
||||
{error && <Text color="red">{error}</Text>}
|
||||
{running && <Text color="yellow">Running: {running}...</Text>}
|
||||
|
||||
{!loading && !running && workflows.length === 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<Text dimColor>No workflows found.</Text>
|
||||
<Text dimColor>Create one with: skillkit workflow create</Text>
|
||||
</Box>
|
||||
<box flexDirection="column" padding={1}>
|
||||
{/* Header */}
|
||||
{animPhase >= 1 && (
|
||||
<box flexDirection="column">
|
||||
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
|
||||
<text fg={terminalColors.workflow}>⟳ Workflows</text>
|
||||
<text fg={terminalColors.textMuted}>{WORKFLOWS.length} workflows</text>
|
||||
</box>
|
||||
<text fg={terminalColors.textMuted}>automate skill chains</text>
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{!loading && !running && workflows.length > 0 && (
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
{start > 0 && <Text dimColor> ↑ {start} more</Text>}
|
||||
{visible.map((wf, i) => {
|
||||
const idx = start + i;
|
||||
const isSel = idx === sel;
|
||||
return (
|
||||
<Box key={wf.name} flexDirection="column">
|
||||
<Text inverse={isSel}>
|
||||
{isSel ? symbols.pointer : ' '} {wf.name}
|
||||
</Text>
|
||||
{isSel && wf.description && (
|
||||
<Text dimColor> {wf.description}</Text>
|
||||
)}
|
||||
{isSel && (
|
||||
<Text dimColor> {wf.waves.length} wave(s), {wf.waves.reduce((acc, w) => acc + w.skills.length, 0)} skill(s)</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
{start + maxVisible < workflows.length && <Text dimColor> ↓ {workflows.length - start - maxVisible} more</Text>}
|
||||
</Box>
|
||||
{/* Stats */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text> </text>
|
||||
<box flexDirection="row" gap={3}>
|
||||
<text fg={terminalColors.success}>✓ {successCount} passed</text>
|
||||
{failedCount > 0 && (
|
||||
<text fg={terminalColors.error}>✗ {failedCount} failed</text>
|
||||
)}
|
||||
</box>
|
||||
<text> </text>
|
||||
{divider}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>Enter=run r=refresh q=quit</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
{/* Workflows list */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.text}>Workflows</text>
|
||||
<text> </text>
|
||||
|
||||
{WORKFLOWS.length === 0 ? (
|
||||
<box flexDirection="column">
|
||||
<text fg={terminalColors.textMuted}>No workflows yet</text>
|
||||
</box>
|
||||
) : (
|
||||
WORKFLOWS.map((wf, idx) => {
|
||||
const selected = idx === selectedIndex;
|
||||
const indicator = selected ? '▸' : ' ';
|
||||
const statusIcon = wf.status === 'success' ? '✓'
|
||||
: wf.status === 'failed' ? '✗' : '○';
|
||||
const statusColor = wf.status === 'success' ? terminalColors.success
|
||||
: wf.status === 'failed' ? terminalColors.error : terminalColors.textMuted;
|
||||
return (
|
||||
<box key={wf.name} flexDirection="row">
|
||||
<text fg={terminalColors.text}>{indicator}</text>
|
||||
<text fg={selected ? terminalColors.accent : terminalColors.text} width={18}>
|
||||
{wf.name}
|
||||
</text>
|
||||
<text fg={statusColor}>{statusIcon} </text>
|
||||
<text fg={terminalColors.textMuted}>{wf.steps}s · {wf.lastRun}</text>
|
||||
</box>
|
||||
);
|
||||
})
|
||||
)}
|
||||
<text> </text>
|
||||
</box>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
{animPhase >= 2 && (
|
||||
<box flexDirection="column">
|
||||
{divider}
|
||||
<text fg={terminalColors.textMuted}>{shortcuts}</text>
|
||||
</box>
|
||||
)}
|
||||
</box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
/**
|
||||
* Screens module for SkillKit TUI
|
||||
*/
|
||||
|
||||
export { Home } from './Home.js';
|
||||
export { Browse } from './Browse.js';
|
||||
export { Installed } from './Installed.js';
|
||||
export { Sync } from './Sync.js';
|
||||
export { Settings } from './Settings.js';
|
||||
export { Marketplace } from './Marketplace.js';
|
||||
export { Recommend } from './Recommend.js';
|
||||
export { Translate } from './Translate.js';
|
||||
export { Context } from './Context.js';
|
||||
export { Sync } from './Sync.js';
|
||||
export { Memory } from './Memory.js';
|
||||
export { Workflow } from './Workflow.js';
|
||||
export { Execute } from './Execute.js';
|
||||
export { History } from './History.js';
|
||||
export { Marketplace } from './Marketplace.js';
|
||||
export { Team } from './Team.js';
|
||||
export { Plugins } from './Plugins.js';
|
||||
export { Methodology } from './Methodology.js';
|
||||
export { Plan } from './Plan.js';
|
||||
export { Settings } from './Settings.js';
|
||||
export { Help } from './Help.js';
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Agent state management for SkillKit TUI
|
||||
*/
|
||||
import { loadConfig } from '@skillkit/core';
|
||||
import { detectAgent, getAdapter, getAllAdapters } from '@skillkit/agents';
|
||||
import type { AgentType } from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Agent status information
|
||||
*/
|
||||
export interface AgentStatus {
|
||||
type: AgentType;
|
||||
name: string;
|
||||
detected: boolean;
|
||||
configured: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agents state
|
||||
*/
|
||||
export interface AgentsState {
|
||||
agents: AgentStatus[];
|
||||
currentAgent: AgentType;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create initial agents state
|
||||
*/
|
||||
export function createAgentsState(): AgentsState {
|
||||
return {
|
||||
agents: [],
|
||||
currentAgent: 'universal',
|
||||
loading: true,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all agents with their detection status
|
||||
*/
|
||||
export async function loadAgents(): Promise<AgentsState> {
|
||||
try {
|
||||
const config = loadConfig();
|
||||
const currentAgent = config.agent || 'universal';
|
||||
const detectedAgent = await detectAgent();
|
||||
const allAdapters = getAllAdapters();
|
||||
|
||||
const agents: AgentStatus[] = allAdapters.map((adapter) => ({
|
||||
type: adapter.type,
|
||||
name: adapter.name,
|
||||
detected: adapter.type === detectedAgent,
|
||||
configured: adapter.type === currentAgent,
|
||||
}));
|
||||
|
||||
return {
|
||||
agents,
|
||||
currentAgent,
|
||||
loading: false,
|
||||
error: null,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
agents: [],
|
||||
currentAgent: 'universal',
|
||||
loading: false,
|
||||
error: err instanceof Error ? err.message : 'Failed to load agents',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get count of detected agents
|
||||
*/
|
||||
export function getDetectedAgentCount(state: AgentsState): number {
|
||||
return state.agents.filter((a) => a.detected).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of detected agents
|
||||
*/
|
||||
export function getDetectedAgents(state: AgentsState): AgentStatus[] {
|
||||
return state.agents.filter((a) => a.detected);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agent adapter by type
|
||||
*/
|
||||
export function getAgentAdapter(type: AgentType) {
|
||||
return getAdapter(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Total number of supported agents
|
||||
*/
|
||||
export const TOTAL_AGENTS = 17;
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* State management module for SkillKit TUI
|
||||
*/
|
||||
|
||||
// Types
|
||||
export {
|
||||
type SkillItem,
|
||||
type RepoInfo,
|
||||
type FetchedSkill,
|
||||
type Screen,
|
||||
NAV_KEYS,
|
||||
STATUS_BAR_SHORTCUTS,
|
||||
type ScreenMeta,
|
||||
type SidebarSection,
|
||||
SIDEBAR_NAV,
|
||||
} from './types.js';
|
||||
|
||||
// Navigation
|
||||
export {
|
||||
type NavigationState,
|
||||
createNavigationState,
|
||||
navigateTo,
|
||||
goBack,
|
||||
getScreenFromKey,
|
||||
isNavKey,
|
||||
} from './navigation.js';
|
||||
|
||||
// Skills
|
||||
export {
|
||||
type SkillsState,
|
||||
createSkillsState,
|
||||
loadSkills,
|
||||
removeSkill,
|
||||
filterSkills,
|
||||
} from './skills.js';
|
||||
|
||||
// Agents
|
||||
export {
|
||||
type AgentStatus,
|
||||
type AgentsState,
|
||||
createAgentsState,
|
||||
loadAgents,
|
||||
getDetectedAgentCount,
|
||||
getDetectedAgents,
|
||||
getAgentAdapter,
|
||||
TOTAL_AGENTS,
|
||||
} from './agents.js';
|
||||
|
||||
// Marketplace
|
||||
export {
|
||||
type MarketplaceState,
|
||||
DEFAULT_REPOS,
|
||||
getMarketplaceRepos,
|
||||
createMarketplaceState,
|
||||
readSkillDescription,
|
||||
fetchRepoSkills,
|
||||
cleanupTempRoot,
|
||||
filterMarketplaceSkills,
|
||||
toSkillItems,
|
||||
sortSkillsByName,
|
||||
} from './marketplace.js';
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* Marketplace state management for SkillKit TUI
|
||||
*/
|
||||
import { detectProvider, loadConfig, extractFrontmatter } from '@skillkit/core';
|
||||
import { readFileSync, existsSync, rmSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { SkillItem, RepoInfo, FetchedSkill } from './types.js';
|
||||
|
||||
/**
|
||||
* Default popular repos - can be extended via config.marketplaceSources
|
||||
*/
|
||||
export const DEFAULT_REPOS: RepoInfo[] = [
|
||||
{ source: 'anthropics/skills', name: 'Anthropic Official' },
|
||||
{ source: 'vercel-labs/agent-skills', name: 'Vercel Labs' },
|
||||
{ source: 'expo/skills', name: 'Expo / React Native' },
|
||||
{ source: 'remotion-dev/skills', name: 'Remotion Video' },
|
||||
{ source: 'ComposioHQ/awesome-claude-skills', name: 'Composio Awesome' },
|
||||
{ source: 'travisvn/awesome-claude-skills', name: 'Travis Awesome' },
|
||||
{ source: 'mhattingpete/claude-skills-marketplace', name: 'Skills Marketplace' },
|
||||
{ source: 'coreyhaines31/marketingskills', name: 'Marketing Skills' },
|
||||
{ source: 'obra/superpowers', name: 'Superpowers TDD' },
|
||||
{ source: 'softaworks/agent-toolkit', name: 'Softaworks Toolkit' },
|
||||
{ source: 'wshobson/agents', name: 'Dev Patterns' },
|
||||
{ source: 'langgenius/dify', name: 'Dify Frontend' },
|
||||
{ source: 'trailofbits/skills', name: 'Trail of Bits Security' },
|
||||
{ source: 'better-auth/skills', name: 'Better Auth' },
|
||||
{ source: 'onmax/nuxt-skills', name: 'Nuxt / Vue' },
|
||||
{ source: 'hyf0/vue-skills', name: 'Vue Best Practices' },
|
||||
{ source: 'jezweb/claude-skills', name: 'Cloudflare / TanStack' },
|
||||
{ source: 'elysiajs/skills', name: 'ElysiaJS / Bun' },
|
||||
{ source: 'kadajett/agent-nestjs-skills', name: 'NestJS' },
|
||||
{ source: 'callstackincubator/agent-skills', name: 'React Native' },
|
||||
{ source: 'cloudai-x/threejs-skills', name: 'Three.js' },
|
||||
{ source: 'emalorenzo/three-agent-skills', name: 'Three.js Advanced' },
|
||||
{ source: 'dimillian/skills', name: 'SwiftUI iOS' },
|
||||
{ source: 'stripe/ai', name: 'Stripe Payments' },
|
||||
{ source: 'waynesutton/convexskills', name: 'Convex Backend' },
|
||||
{ source: 'kepano/obsidian-skills', name: 'Obsidian Notes' },
|
||||
{ source: 'jimliu/baoyu-skills', name: 'Baoyu Tools' },
|
||||
{ source: 'giuseppe-trisciuoglio/developer-kit', name: 'Shadcn / Radix' },
|
||||
{ source: 'openrouterteam/agent-skills', name: 'OpenRouter SDK' },
|
||||
{ source: 'intellectronica/agent-skills', name: 'Context7' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Marketplace state
|
||||
*/
|
||||
export interface MarketplaceState {
|
||||
allSkills: FetchedSkill[];
|
||||
filteredSkills: FetchedSkill[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
currentRepo: string | null;
|
||||
fetchedRepos: Set<string>;
|
||||
failedRepos: string[];
|
||||
repos: RepoInfo[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get marketplace repos from config or use defaults
|
||||
*/
|
||||
export function getMarketplaceRepos(): RepoInfo[] {
|
||||
try {
|
||||
const config = loadConfig();
|
||||
if (config.marketplaceSources?.length) {
|
||||
const configRepos: RepoInfo[] = config.marketplaceSources.map((source) => ({
|
||||
source,
|
||||
name: source.split('/').pop() || source,
|
||||
}));
|
||||
const existingSources = new Set(configRepos.map((r) => r.source));
|
||||
for (const repo of DEFAULT_REPOS) {
|
||||
if (!existingSources.has(repo.source)) {
|
||||
configRepos.push(repo);
|
||||
}
|
||||
}
|
||||
return configRepos;
|
||||
}
|
||||
} catch {
|
||||
// Config load failed, use defaults
|
||||
}
|
||||
return DEFAULT_REPOS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create initial marketplace state
|
||||
*/
|
||||
export function createMarketplaceState(): MarketplaceState {
|
||||
return {
|
||||
allSkills: [],
|
||||
filteredSkills: [],
|
||||
loading: false,
|
||||
error: null,
|
||||
currentRepo: null,
|
||||
fetchedRepos: new Set(),
|
||||
failedRepos: [],
|
||||
repos: getMarketplaceRepos(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to read skill description from frontmatter
|
||||
*/
|
||||
export function readSkillDescription(skillPath: string): string | undefined {
|
||||
const skillMdPath = join(skillPath, 'SKILL.md');
|
||||
if (!existsSync(skillMdPath)) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const content = readFileSync(skillMdPath, 'utf-8');
|
||||
const frontmatter = extractFrontmatter(content);
|
||||
if (frontmatter && typeof frontmatter.description === 'string') {
|
||||
return frontmatter.description;
|
||||
}
|
||||
} catch {
|
||||
// Failed to read, return undefined
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch skills from a single repository
|
||||
*/
|
||||
export async function fetchRepoSkills(
|
||||
source: string,
|
||||
repos: RepoInfo[]
|
||||
): Promise<{
|
||||
skills: FetchedSkill[];
|
||||
tempRoot?: string;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const provider = detectProvider(source);
|
||||
if (!provider) {
|
||||
return { skills: [], error: `Could not detect provider for: ${source}` };
|
||||
}
|
||||
|
||||
const result = await provider.clone(source, '', { depth: 1 });
|
||||
|
||||
if (!result.success || !result.discoveredSkills) {
|
||||
return { skills: [], error: result.error || 'Failed to fetch skills' };
|
||||
}
|
||||
|
||||
const repoName = repos.find((r) => r.source === source)?.name || source;
|
||||
const skills: FetchedSkill[] = result.discoveredSkills.map((skill) => ({
|
||||
name: skill.name,
|
||||
source: source,
|
||||
repoName: repoName,
|
||||
description: readSkillDescription(skill.path),
|
||||
}));
|
||||
|
||||
return { skills, tempRoot: result.tempRoot };
|
||||
} catch (err) {
|
||||
return {
|
||||
skills: [],
|
||||
error: err instanceof Error ? err.message : 'Failed to fetch repository',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up temp directory from fetch
|
||||
*/
|
||||
export function cleanupTempRoot(tempRoot: string): void {
|
||||
try {
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter skills by search query
|
||||
*/
|
||||
export function filterMarketplaceSkills(
|
||||
skills: FetchedSkill[],
|
||||
query: string
|
||||
): FetchedSkill[] {
|
||||
if (!query.trim()) return skills;
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
return skills.filter(
|
||||
(s) =>
|
||||
s.name.toLowerCase().includes(lowerQuery) ||
|
||||
s.source.toLowerCase().includes(lowerQuery) ||
|
||||
s.repoName.toLowerCase().includes(lowerQuery) ||
|
||||
s.description?.toLowerCase().includes(lowerQuery)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert fetched skills to skill items for display
|
||||
*/
|
||||
export function toSkillItems(skills: FetchedSkill[]): SkillItem[] {
|
||||
return skills.map((s) => ({
|
||||
name: s.name,
|
||||
description: s.description || s.repoName,
|
||||
source: s.source,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort skills alphabetically by name
|
||||
*/
|
||||
export function sortSkillsByName(skills: FetchedSkill[]): FetchedSkill[] {
|
||||
return [...skills].sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Navigation state management for SkillKit TUI
|
||||
*/
|
||||
import type { Screen } from './types.js';
|
||||
import { NAV_KEYS } from './types.js';
|
||||
|
||||
/**
|
||||
* Navigation state
|
||||
*/
|
||||
export interface NavigationState {
|
||||
currentScreen: Screen;
|
||||
previousScreen: Screen | null;
|
||||
history: Screen[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create initial navigation state
|
||||
*/
|
||||
export function createNavigationState(): NavigationState {
|
||||
return {
|
||||
currentScreen: 'home',
|
||||
previousScreen: null,
|
||||
history: ['home'],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to a new screen
|
||||
*/
|
||||
export function navigateTo(state: NavigationState, screen: Screen): NavigationState {
|
||||
if (state.currentScreen === screen) return state;
|
||||
|
||||
return {
|
||||
currentScreen: screen,
|
||||
previousScreen: state.currentScreen,
|
||||
history: [...state.history, screen],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Go back to previous screen (or home)
|
||||
*/
|
||||
export function goBack(state: NavigationState): NavigationState {
|
||||
const previousScreen = state.previousScreen || 'home';
|
||||
return {
|
||||
currentScreen: previousScreen,
|
||||
previousScreen: state.history[state.history.length - 3] || null,
|
||||
history: state.history.slice(0, -1),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get screen from key press
|
||||
*/
|
||||
export function getScreenFromKey(key: string): Screen | undefined {
|
||||
return NAV_KEYS[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a key is a navigation key
|
||||
*/
|
||||
export function isNavKey(key: string): boolean {
|
||||
return key in NAV_KEYS;
|
||||
}
|
||||
|
||||
export { NAV_KEYS };
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Skills state management for SkillKit TUI
|
||||
*/
|
||||
import { findAllSkills } from '@skillkit/core';
|
||||
import { rmSync } from 'node:fs';
|
||||
import { resolve, normalize } from 'node:path';
|
||||
import { getSearchDirs } from '../utils/helpers.js';
|
||||
import type { SkillItem } from './types.js';
|
||||
import type { AgentType } from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Skills store state
|
||||
*/
|
||||
export interface SkillsState {
|
||||
skills: SkillItem[];
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create initial skills state
|
||||
*/
|
||||
export function createSkillsState(): SkillsState {
|
||||
return {
|
||||
skills: [],
|
||||
loading: true,
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Load installed skills
|
||||
* @param agentType - Optional agent type to load skills for
|
||||
* @returns Updated skills state
|
||||
*/
|
||||
export function loadSkills(agentType?: AgentType): SkillsState {
|
||||
try {
|
||||
const searchDirs = getSearchDirs(agentType);
|
||||
const foundSkills = findAllSkills(searchDirs);
|
||||
|
||||
const skillItems: SkillItem[] = foundSkills.map((s) => ({
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
source: s.metadata?.source,
|
||||
enabled: s.enabled,
|
||||
}));
|
||||
|
||||
return {
|
||||
skills: skillItems,
|
||||
loading: false,
|
||||
error: null,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
skills: [],
|
||||
loading: false,
|
||||
error: err instanceof Error ? err.message : 'Failed to load skills',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a skill by name
|
||||
* @param skillName - Name of the skill to remove
|
||||
* @param agentType - Optional agent type
|
||||
* @returns true if removed, false otherwise
|
||||
*/
|
||||
export function removeSkill(skillName: string, agentType?: AgentType): boolean {
|
||||
try {
|
||||
const searchDirs = getSearchDirs(agentType);
|
||||
const allSkills = findAllSkills(searchDirs);
|
||||
const skill = allSkills.find((s) => s.name === skillName);
|
||||
|
||||
if (skill) {
|
||||
const normalizedPath = normalize(resolve(skill.path));
|
||||
const isWithinSearchDirs = searchDirs.some((dir) => {
|
||||
const normalizedDir = normalize(resolve(dir));
|
||||
return normalizedPath.startsWith(normalizedDir + '/') || normalizedPath === normalizedDir;
|
||||
});
|
||||
|
||||
if (!isWithinSearchDirs) {
|
||||
return false;
|
||||
}
|
||||
|
||||
rmSync(skill.path, { recursive: true, force: true });
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter skills by search query
|
||||
*/
|
||||
export function filterSkills(skills: SkillItem[], query: string): SkillItem[] {
|
||||
if (!query.trim()) return skills;
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
return skills.filter(
|
||||
(s) =>
|
||||
s.name.toLowerCase().includes(lowerQuery) ||
|
||||
s.description?.toLowerCase().includes(lowerQuery) ||
|
||||
s.source?.toLowerCase().includes(lowerQuery)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
export interface SkillItem {
|
||||
name: string;
|
||||
description?: string;
|
||||
source?: string;
|
||||
installs?: number;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface RepoInfo {
|
||||
source: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface FetchedSkill {
|
||||
name: string;
|
||||
source: string;
|
||||
repoName: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export type Screen =
|
||||
| 'home' | 'browse' | 'installed' | 'marketplace' | 'recommend'
|
||||
| 'translate' | 'context' | 'memory' | 'team' | 'plugins'
|
||||
| 'methodology' | 'plan' | 'workflow' | 'execute' | 'history'
|
||||
| 'sync' | 'settings' | 'help';
|
||||
|
||||
export const NAV_KEYS: Record<string, Screen> = {
|
||||
h: 'home', m: 'marketplace', b: 'browse', w: 'workflow',
|
||||
x: 'execute', y: 'history', r: 'recommend', t: 'translate',
|
||||
c: 'context', e: 'memory', i: 'installed', s: 'sync',
|
||||
a: 'team', p: 'plugins', o: 'methodology', n: 'plan',
|
||||
',': 'settings', '/': 'help',
|
||||
} as const;
|
||||
|
||||
export const STATUS_BAR_SHORTCUTS = 'b browse m market i installed s sync / help q quit';
|
||||
|
||||
export interface ScreenMeta {
|
||||
key: string;
|
||||
label: string;
|
||||
screen: Screen;
|
||||
}
|
||||
|
||||
export interface SidebarSection {
|
||||
section: string;
|
||||
items: ScreenMeta[];
|
||||
}
|
||||
|
||||
export const SIDEBAR_NAV: SidebarSection[] = [
|
||||
{
|
||||
section: 'Discover',
|
||||
items: [
|
||||
{ key: 'h', label: 'Home', screen: 'home' },
|
||||
{ key: 'b', label: 'Browse', screen: 'browse' },
|
||||
{ key: 'm', label: 'Market', screen: 'marketplace' },
|
||||
{ key: 'r', label: 'Recommend', screen: 'recommend' },
|
||||
],
|
||||
},
|
||||
{
|
||||
section: 'Manage',
|
||||
items: [
|
||||
{ key: 'i', label: 'Installed', screen: 'installed' },
|
||||
{ key: 's', label: 'Sync', screen: 'sync' },
|
||||
{ key: 't', label: 'Translate', screen: 'translate' },
|
||||
],
|
||||
},
|
||||
{
|
||||
section: 'Execute',
|
||||
items: [
|
||||
{ key: 'w', label: 'Workflows', screen: 'workflow' },
|
||||
{ key: 'x', label: 'Execute', screen: 'execute' },
|
||||
{ key: 'n', label: 'Plan', screen: 'plan' },
|
||||
],
|
||||
},
|
||||
{
|
||||
section: 'Team',
|
||||
items: [
|
||||
{ key: 'a', label: 'Team', screen: 'team' },
|
||||
{ key: 'c', label: 'Context', screen: 'context' },
|
||||
{ key: 'e', label: 'Memory', screen: 'memory' },
|
||||
],
|
||||
},
|
||||
{
|
||||
section: 'More',
|
||||
items: [
|
||||
{ key: 'p', label: 'Plugins', screen: 'plugins' },
|
||||
{ key: 'o', label: 'Methods', screen: 'methodology' },
|
||||
{ key: ',', label: 'Settings', screen: 'settings' },
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -1,37 +0,0 @@
|
||||
import chalk from 'chalk';
|
||||
|
||||
export const colors = {
|
||||
primary: 'white',
|
||||
secondary: 'white',
|
||||
secondaryDim: 'gray',
|
||||
success: 'white',
|
||||
danger: 'white',
|
||||
warning: 'white',
|
||||
background: 'bgBlack',
|
||||
borderDim: 'gray',
|
||||
};
|
||||
|
||||
export const symbols = {
|
||||
pointer: chalk.white('❯'),
|
||||
bullet: '●',
|
||||
checkboxOn: chalk.white('✔'),
|
||||
checkboxOff: chalk.dim('✖'),
|
||||
check: chalk.white('✓'),
|
||||
star: '★',
|
||||
spinner: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
|
||||
arrowUp: '↑',
|
||||
arrowDown: '↓',
|
||||
success: '✓',
|
||||
error: '✗',
|
||||
warning: '⚠',
|
||||
info: 'ℹ',
|
||||
};
|
||||
|
||||
export const logo = `
|
||||
███████╗██╗ ██╗██╗██╗ ██╗ ██╗ ██╗██╗████████╗
|
||||
██╔════╝██║ ██╔╝██║██║ ██║ ██║ ██╔╝██║╚══██╔══╝
|
||||
███████╗█████╔╝ ██║██║ ██║ █████╔╝ ██║ ██║
|
||||
╚════██║██╔═██╗ ██║██║ ██║ ██╔═██╗ ██║ ██║
|
||||
███████║██║ ██╗██║███████╗███████╗██║ ██╗██║ ██║
|
||||
╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝
|
||||
`;
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Animation presets for SkillKit TUI
|
||||
* Uses OpenTUI's useTimeline for smooth 60fps animations
|
||||
*/
|
||||
|
||||
/**
|
||||
* Animation easing functions available in OpenTUI
|
||||
*/
|
||||
export type EasingFunction =
|
||||
| 'linear'
|
||||
| 'easeInQuad'
|
||||
| 'easeOutQuad'
|
||||
| 'easeInOutQuad'
|
||||
| 'easeInCubic'
|
||||
| 'easeOutCubic'
|
||||
| 'easeInOutCubic'
|
||||
| 'easeInQuart'
|
||||
| 'easeOutQuart'
|
||||
| 'easeInOutQuart';
|
||||
|
||||
/**
|
||||
* Animation preset configuration
|
||||
*/
|
||||
export interface AnimationPreset {
|
||||
duration: number;
|
||||
ease: EasingFunction;
|
||||
stagger?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Predefined animation presets
|
||||
*/
|
||||
export const animations = {
|
||||
/**
|
||||
* Staggered fade-in for entrance animations
|
||||
* Used on home screen for progressive content reveal
|
||||
*/
|
||||
staggeredFadeIn: {
|
||||
duration: 800,
|
||||
ease: 'easeOutCubic' as EasingFunction,
|
||||
stagger: 100,
|
||||
},
|
||||
|
||||
/**
|
||||
* Logo reveal with scramble effect
|
||||
* Used for branding animation on startup
|
||||
*/
|
||||
logoReveal: {
|
||||
duration: 600,
|
||||
ease: 'easeOutCubic' as EasingFunction,
|
||||
},
|
||||
|
||||
/**
|
||||
* Count-up animation for stats
|
||||
* Used in StatsCard component
|
||||
*/
|
||||
countUp: {
|
||||
duration: 1200,
|
||||
ease: 'easeOutQuart' as EasingFunction,
|
||||
},
|
||||
|
||||
/**
|
||||
* Screen transition animation
|
||||
* Used when navigating between screens
|
||||
*/
|
||||
screenTransition: {
|
||||
duration: 200,
|
||||
ease: 'easeInOutCubic' as EasingFunction,
|
||||
},
|
||||
|
||||
/**
|
||||
* Quick fade for tooltips and hints
|
||||
*/
|
||||
quickFade: {
|
||||
duration: 150,
|
||||
ease: 'easeOutQuad' as EasingFunction,
|
||||
},
|
||||
|
||||
/**
|
||||
* Pulse animation for active states
|
||||
*/
|
||||
pulse: {
|
||||
duration: 1000,
|
||||
ease: 'easeInOutQuad' as EasingFunction,
|
||||
},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Scramble effect characters
|
||||
* Used for text reveal animations
|
||||
*/
|
||||
export const SCRAMBLE_CHARS = '█▓▒░◆◇◈⟁◎✦⬡▣';
|
||||
|
||||
/**
|
||||
* Scramble animation configuration
|
||||
*/
|
||||
export interface ScrambleConfig {
|
||||
/** Animation duration in ms */
|
||||
duration: number;
|
||||
/** Progress increment per frame */
|
||||
increment: number;
|
||||
/** Frame interval in ms */
|
||||
interval: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default scramble animation config
|
||||
*/
|
||||
export const DEFAULT_SCRAMBLE_CONFIG: ScrambleConfig = {
|
||||
duration: 420,
|
||||
increment: 12,
|
||||
interval: 35,
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate scrambled text with progressive reveal
|
||||
* @param target - The target text to reveal
|
||||
* @param progress - Progress percentage (0-100)
|
||||
* @param chars - Characters to use for scrambling
|
||||
*/
|
||||
export function scrambleText(
|
||||
target: string,
|
||||
progress: number,
|
||||
chars: string = SCRAMBLE_CHARS
|
||||
): string {
|
||||
return target
|
||||
.split('\n')
|
||||
.map((line) => {
|
||||
return line
|
||||
.split('')
|
||||
.map((char, i) => {
|
||||
if (char === ' ') return char;
|
||||
if (progress > (i / line.length) * 100) return char;
|
||||
return chars[Math.floor(Math.random() * chars.length)];
|
||||
})
|
||||
.join('');
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate staggered delay for an item in a list
|
||||
* @param index - Item index
|
||||
* @param stagger - Delay between items in ms
|
||||
* @returns Delay in ms for this item
|
||||
*/
|
||||
export function getStaggerDelay(index: number, stagger: number = 100): number {
|
||||
return index * stagger;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Monochromatic color palette for SkillKit TUI
|
||||
* Inspired by OpenSync's elegant dark theme
|
||||
*/
|
||||
|
||||
export const colors = {
|
||||
// Base (monochromatic grays)
|
||||
background: '#0d0d0d',
|
||||
surface: '#1a1a1a',
|
||||
surfaceHover: '#262626',
|
||||
border: '#333333',
|
||||
borderDim: '#1f1f1f',
|
||||
|
||||
// Text hierarchy
|
||||
text: '#ffffff',
|
||||
textSecondary: '#a0a0a0',
|
||||
textMuted: '#666666',
|
||||
|
||||
// Accent (single brand color - vibrant green)
|
||||
accent: '#00ff88',
|
||||
accentDim: '#00cc6a',
|
||||
|
||||
// Status colors (subtle variations)
|
||||
success: '#22c55e',
|
||||
warning: '#eab308',
|
||||
error: '#ef4444',
|
||||
info: '#3b82f6',
|
||||
|
||||
// Feature-specific accent colors (for colored keywords)
|
||||
sync: '#00d9ff', // cyan
|
||||
browse: '#22c55e', // green
|
||||
recommend: '#fbbf24', // yellow/gold
|
||||
translate: '#a855f7', // purple
|
||||
workflow: '#3b82f6', // blue
|
||||
team: '#ffffff', // white
|
||||
private: '#ef4444', // red
|
||||
tag: '#fbbf24', // yellow
|
||||
export: '#22c55e', // green
|
||||
delete: '#ef4444', // red
|
||||
} as const;
|
||||
|
||||
export type ColorName = keyof typeof colors;
|
||||
export type ColorValue = (typeof colors)[ColorName];
|
||||
|
||||
/**
|
||||
* Get a color value by name
|
||||
*/
|
||||
export function getColor(name: ColorName): ColorValue {
|
||||
return colors[name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminal-safe color names for OpenTUI
|
||||
* Maps our design system colors to terminal-compatible values
|
||||
*/
|
||||
export const terminalColors = {
|
||||
background: 'black',
|
||||
surface: 'black',
|
||||
text: 'white',
|
||||
textSecondary: 'gray',
|
||||
textMuted: 'gray',
|
||||
accent: 'green',
|
||||
success: 'green',
|
||||
warning: 'yellow',
|
||||
error: 'red',
|
||||
info: 'blue',
|
||||
sync: 'cyan',
|
||||
browse: 'green',
|
||||
recommend: 'yellow',
|
||||
translate: 'magenta',
|
||||
workflow: 'blue',
|
||||
team: 'white',
|
||||
border: 'gray',
|
||||
} as const;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user