mirror of
https://github.com/rohitg00/skillkit.git
synced 2026-11-20 12:23:29 +00:00
Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7aa566d9b5 | ||
|
|
803ff5692a | ||
|
|
f036104c6d | ||
|
|
257fe9fbb6 | ||
|
|
a5efe29a6c | ||
|
|
6916c09962 | ||
|
|
41da423306 | ||
|
|
c5e78b7f83 | ||
|
|
438bc2720a | ||
|
|
85d9eee7e9 | ||
|
|
d14b57c651 | ||
|
|
4a6003ec46 | ||
|
|
6d36a4a3f7 | ||
|
|
0c5eb93891 | ||
|
|
2432410f79 | ||
|
|
4e3e2b3145 | ||
|
|
82e4a2ae62 | ||
|
|
ff5b3f7b4b | ||
|
|
15134cebbb | ||
|
|
6d01413a68 | ||
|
|
a9d6727ca5 | ||
|
|
2078be9eb4 | ||
|
|
44da0f8592 | ||
|
|
4089e5a0be | ||
|
|
c564d32ea9 | ||
|
|
4f65aecbc9 | ||
|
|
c1ba42d616 | ||
|
|
c8172097be | ||
|
|
80e41e517c | ||
|
|
26ea7e9002 | ||
|
|
1b5722a8c0 | ||
|
|
0210556634 | ||
|
|
570ae26cd5 | ||
|
|
413519d486 | ||
|
|
eadbaff07e | ||
|
|
10e8c389e3 | ||
|
|
94c77707c4 | ||
|
|
821fd1b495 | ||
|
|
288427d9b3 | ||
|
|
131bc122be | ||
|
|
e35cd0d0df | ||
|
|
287dfeac58 | ||
|
|
32914cb8dc | ||
|
|
04c4faff6a | ||
|
|
d8a6b4a700 | ||
|
|
0518ed40a3 | ||
|
|
91e7ab3450 | ||
|
|
d62fe0b761 | ||
|
|
1344d65b3d |
@@ -0,0 +1,89 @@
|
||||
name: Skill Submission
|
||||
description: Submit a new skill to the SkillKit marketplace
|
||||
title: "[Skill Submission] "
|
||||
labels: ["skill-submission"]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Submit Your Skill to SkillKit Marketplace
|
||||
|
||||
Thanks for contributing! Please fill out the details below.
|
||||
|
||||
**Tip:** You can also use our [web form](https://rohitg00.github.io/skillkit/) to submit skills.
|
||||
|
||||
- type: input
|
||||
id: skill-name
|
||||
attributes:
|
||||
label: Skill Name
|
||||
description: A descriptive name for your skill
|
||||
placeholder: e.g., React Best Practices
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Description
|
||||
description: What does this skill teach AI agents?
|
||||
placeholder: A brief description of your skill...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: repo-owner
|
||||
attributes:
|
||||
label: GitHub Owner
|
||||
description: The owner of the repository (username or organization)
|
||||
placeholder: e.g., your-username
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: repo-name
|
||||
attributes:
|
||||
label: Repository Name
|
||||
description: The name of the repository containing the skill
|
||||
placeholder: e.g., my-agent-skills
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: skill-path
|
||||
attributes:
|
||||
label: Skill Path
|
||||
description: Path to SKILL.md in the repository
|
||||
placeholder: skills/my-skill/SKILL.md
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: tags
|
||||
attributes:
|
||||
label: Tags
|
||||
description: Comma-separated tags for categorization
|
||||
placeholder: react, typescript, frontend
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: author-github
|
||||
attributes:
|
||||
label: Author GitHub Username
|
||||
description: Your GitHub username
|
||||
placeholder: your-username
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: checkboxes
|
||||
id: checklist
|
||||
attributes:
|
||||
label: Checklist
|
||||
description: Please confirm the following
|
||||
options:
|
||||
- label: Repository is public
|
||||
required: true
|
||||
- label: SKILL.md follows the agentskills.io standard format
|
||||
required: true
|
||||
- label: Skill has been tested with at least one AI agent
|
||||
required: false
|
||||
@@ -7,6 +7,7 @@ on:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
# Unit tests run on all Node versions
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -35,5 +36,55 @@ jobs:
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: Test
|
||||
- name: Unit Tests
|
||||
run: pnpm test
|
||||
|
||||
# E2E tests run on latest Node only (to save CI time)
|
||||
e2e:
|
||||
runs-on: ubuntu-latest
|
||||
needs: test # Run after unit tests pass
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Use Node.js 22
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: E2E Tests
|
||||
run: pnpm test:e2e
|
||||
|
||||
- name: Upload E2E Test Results
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-test-results
|
||||
path: |
|
||||
e2e/**/*.log
|
||||
/tmp/skillkit-e2e-*
|
||||
retention-days: 7
|
||||
|
||||
# Final status check for branch protection
|
||||
ci-success:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [test, e2e]
|
||||
if: always()
|
||||
steps:
|
||||
- name: Check all jobs passed
|
||||
run: |
|
||||
if [[ "${{ needs.test.result }}" != "success" ]] || [[ "${{ needs.e2e.result }}" != "success" ]]; then
|
||||
echo "One or more jobs failed"
|
||||
exit 1
|
||||
fi
|
||||
echo "All CI checks passed!"
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
name: Process Skill Submission
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [labeled]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: process-submission-${{ github.event.issue.number }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
process-submission:
|
||||
if: github.event.label.name == 'approved'
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Parse Issue and Update skills.json
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
|
||||
const issue = context.payload.issue;
|
||||
const body = issue.body;
|
||||
|
||||
// Parse issue body for skill details
|
||||
const parseField = (label) => {
|
||||
const regex = new RegExp(`\\*\\*${label}:\\*\\*\\s*(.+?)(?:\\n|$)`, 'i');
|
||||
const match = body.match(regex);
|
||||
return match ? match[1].trim() : '';
|
||||
};
|
||||
|
||||
const parseCheckbox = (text) => {
|
||||
const regex = new RegExp(`- \\[(x|X)\\]\\s*${text}`, 'i');
|
||||
return regex.test(body);
|
||||
};
|
||||
|
||||
// Extract fields from form-based issue
|
||||
let skillName, description, repoOwner, repoName, skillPath, tags, authorGithub;
|
||||
|
||||
if (body.includes('### Skill Name')) {
|
||||
// YAML form format
|
||||
const sections = body.split('###').filter(s => s.trim());
|
||||
for (const section of sections) {
|
||||
const lines = section.trim().split('\n');
|
||||
const header = lines[0].trim().toLowerCase();
|
||||
const value = lines.slice(1).join('\n').trim();
|
||||
|
||||
if (header.includes('skill name')) skillName = value;
|
||||
if (header.includes('description')) description = value;
|
||||
if (header.includes('github owner')) repoOwner = value;
|
||||
if (header.includes('repository name')) repoName = value;
|
||||
if (header.includes('skill path')) skillPath = value;
|
||||
if (header.includes('tags')) tags = value;
|
||||
if (header.includes('author github')) authorGithub = value;
|
||||
}
|
||||
} else {
|
||||
// Markdown format from web form
|
||||
skillName = parseField('Name');
|
||||
description = parseField('Description');
|
||||
repoOwner = parseField('Owner');
|
||||
repoName = parseField('Repo');
|
||||
skillPath = parseField('Skill Path');
|
||||
tags = parseField('Tags');
|
||||
const authorField = parseField('Author') || '';
|
||||
authorGithub = authorField.replace(/^@/, '').trim();
|
||||
}
|
||||
|
||||
if (!skillName || !repoOwner || !repoName) {
|
||||
console.log('Missing required fields');
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
body: '❌ Could not parse skill details. Missing required fields (name, owner, or repo).'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate skill ID
|
||||
const skillSlug = skillName.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
|
||||
const skillId = `${repoOwner}/${repoName}/${skillSlug}`;
|
||||
|
||||
// Read current skills.json
|
||||
const skillsPath = 'marketplace/skills.json';
|
||||
const skillsData = JSON.parse(fs.readFileSync(skillsPath, 'utf-8'));
|
||||
|
||||
// Check for duplicates
|
||||
if (skillsData.skills.some(s => s.id === skillId)) {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
body: `⚠️ Skill with ID \`${skillId}\` already exists in the marketplace.`
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse and validate tags
|
||||
const filteredTags = tags
|
||||
? tags.split(',').map(t => t.trim().toLowerCase()).filter(t => t.length > 0)
|
||||
: [];
|
||||
|
||||
if (filteredTags.length === 0) {
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: issue.number,
|
||||
body: '❌ At least one tag is required. Please add tags to your submission.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Add new skill
|
||||
const newSkill = {
|
||||
id: skillId,
|
||||
name: skillName,
|
||||
description: description || '',
|
||||
source: `${repoOwner}/${repoName}`,
|
||||
tags: filteredTags,
|
||||
author: authorGithub
|
||||
};
|
||||
|
||||
skillsData.skills.push(newSkill);
|
||||
skillsData.updatedAt = new Date().toISOString().split('T')[0];
|
||||
|
||||
// Write updated skills.json
|
||||
fs.writeFileSync(skillsPath, JSON.stringify(skillsData, null, 2) + '\n');
|
||||
|
||||
// Also update docs copy
|
||||
const docsCopyPath = 'docs/skillkit/data/skills.json';
|
||||
fs.writeFileSync(docsCopyPath, JSON.stringify(skillsData, null, 2) + '\n');
|
||||
|
||||
// Also update core copy
|
||||
const coreCopyPath = 'packages/core/src/marketplace/data/skills.json';
|
||||
fs.writeFileSync(coreCopyPath, JSON.stringify(skillsData, null, 2) + '\n');
|
||||
|
||||
console.log(`Added skill: ${skillId}`);
|
||||
|
||||
// Set output for commit
|
||||
core.setOutput('skill_name', skillName);
|
||||
core.setOutput('skill_id', skillId);
|
||||
|
||||
- name: Commit Changes
|
||||
run: |
|
||||
git config --local user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git config --local user.name "github-actions[bot]"
|
||||
git add marketplace/skills.json docs/skillkit/data/skills.json packages/core/src/marketplace/data/skills.json
|
||||
git commit -m "feat(marketplace): add skill from #${{ github.event.issue.number }}"
|
||||
git push
|
||||
|
||||
- name: Close Issue with Comment
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.payload.issue.number,
|
||||
body: `✅ **Skill added to marketplace!**\n\nYour skill has been added and will be available in the next release.\n\nThank you for contributing to SkillKit! 🎉`
|
||||
});
|
||||
|
||||
await github.rest.issues.update({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.payload.issue.number,
|
||||
state: 'closed'
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Publish to npm
|
||||
name: Publish to npm and GitHub Packages
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -6,7 +6,7 @@ on:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
publish-npm:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
permissions:
|
||||
@@ -44,3 +44,64 @@ jobs:
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
generate_release_notes: true
|
||||
|
||||
publish-github-packages:
|
||||
runs-on: ubuntu-latest
|
||||
needs: publish-npm
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js for GitHub Packages
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'pnpm'
|
||||
registry-url: 'https://npm.pkg.github.com'
|
||||
scope: '@rohitg00'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build
|
||||
run: pnpm build
|
||||
|
||||
- name: Configure npm for GitHub Packages
|
||||
run: |
|
||||
echo "@rohitg00:registry=https://npm.pkg.github.com" >> .npmrc
|
||||
echo "//npm.pkg.github.com/:_authToken=${{ secrets.GITHUB_TOKEN }}" >> .npmrc
|
||||
|
||||
- name: Publish main skillkit package to GitHub Packages
|
||||
working-directory: apps/skillkit
|
||||
run: |
|
||||
# Create a temporary package.json with GitHub Packages scope and resolved dependencies
|
||||
node -e "
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const pkg = require('./package.json');
|
||||
|
||||
pkg.name = '@rohitg00/skillkit';
|
||||
pkg.publishConfig = { registry: 'https://npm.pkg.github.com' };
|
||||
|
||||
// Resolve workspace:* dependencies to actual versions
|
||||
for (const [dep, version] of Object.entries(pkg.dependencies || {})) {
|
||||
if (version.startsWith('workspace:')) {
|
||||
const depName = dep.replace('@skillkit/', '');
|
||||
const depPkgPath = path.join('..', '..', 'packages', depName, 'package.json');
|
||||
const depPkg = JSON.parse(fs.readFileSync(depPkgPath, 'utf8'));
|
||||
pkg.dependencies[dep] = depPkg.version;
|
||||
}
|
||||
}
|
||||
|
||||
fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2));
|
||||
"
|
||||
npm publish
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
+5
-1
@@ -59,4 +59,8 @@ skillkit.yaml
|
||||
.skillkit/
|
||||
|
||||
# Turbo cache
|
||||
.turbo/
|
||||
.turbo/
|
||||
|
||||
# Project documentation (not for version control)
|
||||
CLAUDE.md
|
||||
prd.md
|
||||
@@ -1,35 +1,36 @@
|
||||
# SkillKit
|
||||
<div align="center">
|
||||
|
||||
```
|
||||
██ SKILLKIT
|
||||
```
|
||||
</div>
|
||||
|
||||
**Universal Skills for AI Coding Agents**
|
||||
|
||||
[](https://www.npmjs.com/package/skillkit)
|
||||
[](https://www.npmjs.com/package/skillkit)
|
||||
[](https://github.com/rohitg00/skillkit/pkgs/npm/skillkit)
|
||||
[](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml)
|
||||
[](https://rohitg00.github.io/skillkit/)
|
||||
[](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.5.0
|
||||
## Why SkillKit?
|
||||
|
||||
- **Team Collaboration**: Share skill bundles with your team via Git
|
||||
- **Plugin System**: Extend SkillKit with custom translators, providers, and commands
|
||||
- **Methodologies**: 5 ready-to-use development frameworks (Agile, TDD, DevOps, etc.)
|
||||
- **Agent Orchestration**: Coordinate multiple AI agents working together
|
||||
- **Hooks & Automation**: Auto-trigger skills on git commits, file changes
|
||||
**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
|
||||
@@ -47,6 +48,25 @@ skillkit recommend
|
||||
|
||||

|
||||
|
||||
## Beautiful CLI Experience
|
||||
|
||||
SkillKit features a polished, interactive CLI with visual feedback:
|
||||
|
||||
```
|
||||
███████╗██╗ ██╗██╗██╗ ██╗ ██╗ ██╗██╗████████╗
|
||||
██╔════╝██║ ██╔╝██║██║ ██║ ██║ ██╔╝██║╚══██╔══╝
|
||||
███████╗█████╔╝ ██║██║ ██║ █████╔╝ ██║ ██║
|
||||
╚════██║██╔═██╗ ██║██║ ██║ ██╔═██╗ ██║ ██║
|
||||
███████║██║ ██╗██║███████╗███████╗██║ ██╗██║ ██║
|
||||
╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝
|
||||
```
|
||||
|
||||
- **Adaptive Logo** - Full ASCII art on wide terminals, compact on narrow
|
||||
- **Agent Icons** - Visual indicators: ⟁ Claude · ◫ Cursor · ◎ Codex · ✦ Gemini · ⬡ OpenCode
|
||||
- **Interactive Selection** - Multi-select skills and agents with visual feedback
|
||||
- **Progress Indicators** - Step trails, spinners, and progress bars
|
||||
- **Smart Defaults** - Remembers your last selected agents
|
||||
|
||||
## What Makes SkillKit Different
|
||||
|
||||
| Feature | Without SkillKit | With SkillKit |
|
||||
@@ -95,6 +115,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
|
||||
@@ -230,7 +256,7 @@ skillkit cicd pre-commit
|
||||
| OpenCode | SKILL.md | `.opencode/skills/` |
|
||||
| Antigravity | SKILL.md | `.antigravity/skills/` |
|
||||
| Amp | SKILL.md | `.amp/skills/` |
|
||||
| Clawdbot | SKILL.md | `skills/` |
|
||||
| Clawdbot | SKILL.md | `skills/` or `~/.clawdbot/skills/` |
|
||||
| Droid (Factory) | SKILL.md | `.factory/skills/` |
|
||||
| GitHub Copilot | Markdown | `.github/skills/` |
|
||||
| Goose | SKILL.md | `.goose/skills/` |
|
||||
@@ -272,6 +298,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
|
||||
@@ -403,6 +444,9 @@ bun add -g skillkit
|
||||
|
||||
# npx (no install)
|
||||
npx skillkit <command>
|
||||
|
||||
# GitHub Packages (alternative registry)
|
||||
npm install -g @rohitg00/skillkit --registry=https://npm.pkg.github.com
|
||||
```
|
||||
|
||||
## Configuration
|
||||
@@ -420,16 +464,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.
|
||||
@@ -443,3 +477,4 @@ Contributions welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md
|
||||
- [Agent Skills Specification](https://agentskills.io/specification)
|
||||
- [GitHub Repository](https://github.com/rohitg00/skillkit)
|
||||
- [NPM Package](https://www.npmjs.com/package/skillkit)
|
||||
- [GitHub Package](https://github.com/rohitg00/skillkit/pkgs/npm/skillkit)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "skillkit",
|
||||
"version": "1.5.0",
|
||||
"description": "Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more",
|
||||
"version": "1.7.4",
|
||||
"description": "Supercharge AI coding agents with portable skills. Install, translate, and share skills across Claude Code, Cursor, Codex, Copilot & 13 more",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"skillkit": "./dist/cli.js",
|
||||
|
||||
@@ -39,6 +39,14 @@ import {
|
||||
CommandCmd,
|
||||
AICommand,
|
||||
AuditCommand,
|
||||
PublishCommand,
|
||||
AgentCommand,
|
||||
AgentListCommand,
|
||||
AgentShowCommand,
|
||||
AgentCreateCommand,
|
||||
AgentTranslateCommand,
|
||||
AgentSyncCommand,
|
||||
AgentValidateCommand,
|
||||
} from '@skillkit/cli';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
@@ -91,5 +99,13 @@ cli.register(PlanCommand);
|
||||
cli.register(CommandCmd);
|
||||
cli.register(AICommand);
|
||||
cli.register(AuditCommand);
|
||||
cli.register(PublishCommand);
|
||||
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,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,85 @@
|
||||
import React from 'react';
|
||||
import { Hero } from './components/Hero';
|
||||
import { Features } from './components/Features';
|
||||
import { Agents } from './components/Agents';
|
||||
import { Footer } from './components/Footer';
|
||||
import { SkillGenerator } from './components/SkillGenerator';
|
||||
import { SkillSubmitForm } from './components/SkillSubmitForm';
|
||||
|
||||
const GITHUB_ICON = (
|
||||
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
const NPM_ICON = (
|
||||
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M0 7.334v8h6.666v1.332H12v-1.332h12v-8H0zm6.666 6.664H5.334v-4H3.999v4H1.335V8.667h5.331v5.331zm4 0v1.336H8.001V8.667h5.334v5.332h-2.669v-.001zm12.001 0h-1.33v-4h-1.336v4h-1.335v-4h-1.33v4h-2.671V8.667h8.002v5.331zM10.665 10H12v2.667h-1.335V10z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
function scrollToTop(e: React.MouseEvent): void {
|
||||
e.preventDefault();
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}
|
||||
|
||||
export default function App(): React.ReactElement {
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-zinc-100 font-sans selection:bg-white selection:text-black">
|
||||
<nav className="fixed top-0 left-0 right-0 z-50 border-b border-zinc-800 bg-background/90 backdrop-blur-md">
|
||||
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex h-14 items-center justify-between">
|
||||
<a href="#" onClick={scrollToTop} className="flex items-center gap-2 cursor-pointer">
|
||||
<div className="w-4 h-4 bg-white"></div>
|
||||
<span className="text-base font-bold tracking-tight text-white font-mono">SKILLKIT</span>
|
||||
</a>
|
||||
<div className="flex items-center gap-2 sm:gap-4">
|
||||
<a
|
||||
href="https://www.npmjs.com/package/skillkit"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-zinc-400 hover:text-red-500 transition-colors p-2"
|
||||
aria-label="npm"
|
||||
>
|
||||
{NPM_ICON}
|
||||
</a>
|
||||
<a
|
||||
href="https://github.com/rohitg00/skillkit"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-zinc-400 hover:text-white transition-colors p-2"
|
||||
aria-label="GitHub"
|
||||
>
|
||||
{GITHUB_ICON}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main className="pt-14">
|
||||
<Hero />
|
||||
<Agents />
|
||||
<Features />
|
||||
|
||||
<section id="skills" className="py-12 border-b border-zinc-800">
|
||||
<SkillGenerator />
|
||||
</section>
|
||||
|
||||
<section id="submit" className="py-12 border-b border-zinc-800 bg-surface">
|
||||
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
|
||||
<div className="text-center mb-8">
|
||||
<h2 className="text-2xl font-bold text-white mb-2 font-mono">Submit Your Skill</h2>
|
||||
<p className="text-zinc-400 font-mono text-sm">
|
||||
Share your AI agent skills with the community.
|
||||
</p>
|
||||
</div>
|
||||
<SkillSubmitForm />
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<Footer />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
# SkillKit Documentation Website
|
||||
|
||||
Landing page for SkillKit - the universal CLI for managing AI agent skills.
|
||||
|
||||
**Live site:** https://rohitg00.github.io/skillkit/
|
||||
|
||||
## Development
|
||||
|
||||
**Prerequisites:** Node.js 20+
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. (Optional) Set `GEMINI_API_KEY` in `.env.local` for the skill generator feature
|
||||
|
||||
3. Run locally:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
4. Build for production:
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
The site is automatically deployed to GitHub Pages when changes are pushed to the `main` branch.
|
||||
|
||||
The deployment workflow is defined in `.github/workflows/deploy-docs.yml`.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- React 19
|
||||
- Vite
|
||||
- Tailwind CSS (via CDN)
|
||||
- TypeScript
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,53 @@
|
||||
import React from 'react';
|
||||
|
||||
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: 'primary' | 'secondary' | 'outline' | 'ghost';
|
||||
fullWidth?: boolean;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
const BASE_STYLES = "inline-flex items-center justify-center px-6 py-3 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-black disabled:opacity-50 font-mono tracking-tight";
|
||||
|
||||
const VARIANT_STYLES = {
|
||||
primary: "bg-white text-black hover:bg-zinc-200 border border-white",
|
||||
secondary: "bg-zinc-900 text-zinc-100 hover:bg-zinc-800 border border-zinc-800",
|
||||
outline: "bg-transparent text-zinc-300 border border-zinc-700 hover:border-zinc-500 hover:text-white",
|
||||
ghost: "bg-transparent text-zinc-400 hover:text-white hover:bg-zinc-900"
|
||||
} as const;
|
||||
|
||||
export function Button({
|
||||
children,
|
||||
variant = 'primary',
|
||||
className = '',
|
||||
fullWidth = false,
|
||||
isLoading = false,
|
||||
disabled,
|
||||
...props
|
||||
}: ButtonProps): React.ReactElement {
|
||||
const widthClass = fullWidth ? 'w-full' : '';
|
||||
|
||||
const classes = [
|
||||
BASE_STYLES,
|
||||
VARIANT_STYLES[variant],
|
||||
widthClass,
|
||||
className,
|
||||
].filter(Boolean).join(' ');
|
||||
|
||||
return (
|
||||
<button
|
||||
className={classes}
|
||||
disabled={disabled || isLoading}
|
||||
{...props}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<svg className="animate-spin -ml-1 mr-2 h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
PROCESSING
|
||||
</>
|
||||
) : children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import React from 'react';
|
||||
|
||||
interface CardProps {
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
noPadding?: boolean;
|
||||
onClick?: () => void;
|
||||
onDragOver?: (e: React.DragEvent) => void;
|
||||
onDragLeave?: (e: React.DragEvent) => void;
|
||||
onDrop?: (e: React.DragEvent) => void;
|
||||
}
|
||||
|
||||
export function Card({
|
||||
children,
|
||||
className = '',
|
||||
noPadding = false,
|
||||
onClick,
|
||||
onDragOver,
|
||||
onDragLeave,
|
||||
onDrop
|
||||
}: CardProps): React.ReactElement {
|
||||
const paddingClass = noPadding ? '' : 'p-6';
|
||||
const clickableClass = onClick ? 'cursor-pointer' : '';
|
||||
|
||||
function handleKeyDown(e: React.KeyboardEvent): void {
|
||||
if (!onClick) return;
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
if (e.key === ' ') {
|
||||
e.preventDefault();
|
||||
}
|
||||
onClick();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`relative bg-black border border-zinc-800 transition-colors duration-300 ${paddingClass} ${clickableClass} ${className}`}
|
||||
onClick={onClick}
|
||||
role={onClick ? 'button' : undefined}
|
||||
tabIndex={onClick ? 0 : undefined}
|
||||
onKeyDown={onClick ? handleKeyDown : undefined}
|
||||
onDragOver={onDragOver}
|
||||
onDragLeave={onDragLeave}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import React from 'react';
|
||||
|
||||
interface Feature {
|
||||
title: string;
|
||||
description: string;
|
||||
icon: React.ReactNode;
|
||||
}
|
||||
|
||||
const FEATURES: Feature[] = [
|
||||
{
|
||||
title: 'Multi-Agent',
|
||||
description: 'Write once, deploy to 17+ AI coding agents automatically.',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
|
||||
</svg>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Smart Discovery',
|
||||
description: 'AI analyzes your stack and recommends skills.',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
|
||||
</svg>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Persistent Memory',
|
||||
description: 'Save learnings as reusable skills.',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 3v2m6-2v2M9 19v2m6-2v2M5 9H3m2 6H3m18-6h-2m2 6h-2M7 19h10a2 2 0 002-2V7a2 2 0 00-2-2H7a2 2 0 00-2 2v10a2 2 0 002 2zM9 9h6v6H9V9z" />
|
||||
</svg>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Team Sync',
|
||||
description: 'Share skills via Git across your team.',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
|
||||
</svg>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Testing',
|
||||
description: 'Built-in framework for skill validation.',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: 'Workflows',
|
||||
description: 'Compose multi-step automated pipelines.',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M13 10V3L4 14h7v7l9-11h-7z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
];
|
||||
|
||||
const COMPARISONS = [
|
||||
['Agents', '1', '17+'],
|
||||
['Translation', 'Manual', 'Auto'],
|
||||
['Sharing', 'Copy/paste', 'Git sync'],
|
||||
['Discovery', 'Forums', 'AI-powered'],
|
||||
] as const;
|
||||
|
||||
export function Features(): React.ReactElement {
|
||||
return (
|
||||
<section id="features" className="py-12 border-b border-zinc-800 bg-surface">
|
||||
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-5 gap-6 lg:gap-8 mb-10">
|
||||
<div className="lg:col-span-2">
|
||||
<h2 className="text-xl font-bold text-white mb-2 font-mono">Why SkillKit?</h2>
|
||||
<p className="text-zinc-500 font-mono text-sm mb-6">
|
||||
Universal bridge for AI coding agents.
|
||||
</p>
|
||||
<div className="flex gap-6 sm:gap-8">
|
||||
<div>
|
||||
<div className="text-2xl sm:text-3xl font-bold text-white font-mono">17+</div>
|
||||
<div className="text-zinc-600 text-[10px] sm:text-xs font-mono">Agents</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl sm:text-3xl font-bold text-white font-mono">1</div>
|
||||
<div className="text-zinc-600 text-[10px] sm:text-xs font-mono">Command</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-2xl sm:text-3xl font-bold text-white font-mono">∞</div>
|
||||
<div className="text-zinc-600 text-[10px] sm:text-xs font-mono">Skills</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="lg:col-span-3 border border-zinc-800 bg-black/50 p-4 font-mono text-xs backdrop-blur-sm">
|
||||
<div className="grid grid-cols-3 gap-2 border-b border-zinc-800 pb-2 mb-3 text-zinc-500 uppercase tracking-wider text-[10px]">
|
||||
<div>Feature</div>
|
||||
<div className="text-center">Without</div>
|
||||
<div className="text-right">SkillKit</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{COMPARISONS.map(([feature, without, withSkillKit], index) => (
|
||||
<div
|
||||
key={feature}
|
||||
className="grid grid-cols-3 gap-2 items-center py-1.5 hover:bg-zinc-900/50 transition-colors -mx-2 px-2 rounded"
|
||||
style={{ animationDelay: `${index * 100}ms` }}
|
||||
>
|
||||
<div className="text-zinc-300">{feature}</div>
|
||||
<div className="text-center text-zinc-600">{without}</div>
|
||||
<div className="text-right text-white font-medium">{withSkillKit}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 xs:grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
|
||||
{FEATURES.map((feature, index) => (
|
||||
<div
|
||||
key={feature.title}
|
||||
className="group relative p-4 border border-zinc-800 bg-zinc-900/30 hover:bg-zinc-900/80 hover:border-zinc-700 transition-all duration-300 cursor-default"
|
||||
style={{ animationDelay: `${index * 50}ms` }}
|
||||
>
|
||||
<div className="absolute inset-0 bg-gradient-to-b from-zinc-800/0 to-zinc-800/20 opacity-0 group-hover:opacity-100 transition-opacity"></div>
|
||||
<div className="relative">
|
||||
<div className="text-zinc-500 group-hover:text-white transition-colors mb-2">
|
||||
{feature.icon}
|
||||
</div>
|
||||
<h4 className="text-xs font-bold text-white mb-1 font-mono">{feature.title}</h4>
|
||||
<p className="text-zinc-600 text-[10px] leading-relaxed font-mono group-hover:text-zinc-400 transition-colors">
|
||||
{feature.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import React from 'react';
|
||||
|
||||
const GITHUB_ICON = (
|
||||
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export function Footer(): React.ReactElement {
|
||||
const currentYear = new Date().getFullYear();
|
||||
|
||||
return (
|
||||
<footer className="border-t border-border py-6 bg-black">
|
||||
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 flex flex-col sm:flex-row justify-between items-center gap-3">
|
||||
<div className="flex flex-col sm:flex-row items-center gap-2 sm:gap-4 text-center sm:text-left">
|
||||
<p className="text-zinc-500 text-xs font-mono">
|
||||
© {currentYear} SKILLKIT
|
||||
</p>
|
||||
<span className="hidden sm:inline text-zinc-700">•</span>
|
||||
<a
|
||||
href="https://agentskills.io"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-zinc-600 hover:text-zinc-400 text-xs font-mono transition-colors"
|
||||
>
|
||||
Agent Skills standard
|
||||
</a>
|
||||
</div>
|
||||
<a
|
||||
href="https://github.com/rohitg00/skillkit"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label="SkillKit on GitHub"
|
||||
className="text-zinc-500 hover:text-white transition-colors"
|
||||
>
|
||||
{GITHUB_ICON}
|
||||
</a>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button } from './Button';
|
||||
|
||||
const ASCII_LOGO = `███████╗██╗ ██╗██╗██╗ ██╗ ██╗ ██╗██╗████████╗
|
||||
██╔════╝██║ ██╔╝██║██║ ██║ ██║ ██╔╝██║╚══██╔══╝
|
||||
███████╗█████╔╝ ██║██║ ██║ █████╔╝ ██║ ██║
|
||||
╚════██║██╔═██╗ ██║██║ ██║ ██╔═██╗ ██║ ██║
|
||||
███████║██║ ██╗██║███████╗███████╗██║ ██╗██║ ██║
|
||||
╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝`;
|
||||
|
||||
interface TerminalLine {
|
||||
type: 'cmd' | 'out';
|
||||
text: string;
|
||||
}
|
||||
|
||||
const TERMINAL_LINES: TerminalLine[] = [
|
||||
{ type: 'cmd', text: 'skillkit init' },
|
||||
{ type: 'out', text: '→ Next.js + TypeScript detected' },
|
||||
{ type: 'cmd', text: 'skillkit install anthropics/skills' },
|
||||
{ type: 'out', text: '→ Installed 3 skills' },
|
||||
{ type: 'cmd', text: 'skillkit sync --all' },
|
||||
{ type: 'out', text: ' .claude/skills/' },
|
||||
{ type: 'out', text: ' .cursor/skills/' },
|
||||
{ type: 'out', text: ' .windsurf/skills/' },
|
||||
{ type: 'cmd', text: 'skillkit translate --to codex,copilot' },
|
||||
{ type: 'out', text: '→ 2 formats generated' },
|
||||
];
|
||||
|
||||
const FADE_ANIMATION_STYLES = `
|
||||
@keyframes fade-in {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.animate-fade-in {
|
||||
animation: fade-in 0.6s ease-out forwards;
|
||||
}
|
||||
.animate-fade-in-delay {
|
||||
animation: fade-in 0.6s ease-out 0.2s forwards;
|
||||
opacity: 0;
|
||||
}
|
||||
`;
|
||||
|
||||
const CHECK_ICON = (
|
||||
<svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
const COPY_ICON = (
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export function Hero(): React.ReactElement {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [visibleLines, setVisibleLines] = useState(0);
|
||||
const [typingIndex, setTypingIndex] = useState(0);
|
||||
const [currentText, setCurrentText] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (visibleLines >= TERMINAL_LINES.length) {
|
||||
const resetTimer = setTimeout(() => {
|
||||
setVisibleLines(0);
|
||||
setTypingIndex(0);
|
||||
setCurrentText('');
|
||||
}, 3000);
|
||||
return () => clearTimeout(resetTimer);
|
||||
}
|
||||
|
||||
const line = TERMINAL_LINES[visibleLines];
|
||||
if (line.type === 'cmd') {
|
||||
if (typingIndex < line.text.length) {
|
||||
const timer = setTimeout(() => {
|
||||
setCurrentText(line.text.slice(0, typingIndex + 1));
|
||||
setTypingIndex(typingIndex + 1);
|
||||
}, 40);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
setVisibleLines(visibleLines + 1);
|
||||
setTypingIndex(0);
|
||||
setCurrentText('');
|
||||
}, 200);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
setVisibleLines(visibleLines + 1);
|
||||
}, 150);
|
||||
return () => clearTimeout(timer);
|
||||
}, [visibleLines, typingIndex]);
|
||||
|
||||
async function copyInstall(): Promise<void> {
|
||||
try {
|
||||
await navigator.clipboard.writeText('npx skillkit@latest');
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
} catch {
|
||||
// Clipboard API failed, silently ignore
|
||||
}
|
||||
}
|
||||
|
||||
function openGitHub(): void {
|
||||
window.open('https://github.com/rohitg00/skillkit', '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
|
||||
const isTyping = visibleLines < TERMINAL_LINES.length && TERMINAL_LINES[visibleLines].type === 'cmd';
|
||||
const isComplete = visibleLines >= TERMINAL_LINES.length;
|
||||
|
||||
return (
|
||||
<div className="relative border-b border-zinc-800 overflow-hidden">
|
||||
<div className="absolute inset-0 bg-gradient-to-b from-zinc-900/50 to-transparent pointer-events-none"></div>
|
||||
|
||||
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 pt-8 pb-10 relative">
|
||||
<div className="hidden lg:block mb-6 overflow-hidden">
|
||||
<pre className="text-zinc-800 text-[8px] leading-none font-mono select-none animate-pulse">
|
||||
{ASCII_LOGO}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 items-start">
|
||||
<div className="animate-fade-in">
|
||||
<div className="inline-flex items-center space-x-2 border border-zinc-800 bg-zinc-900/50 px-2 py-0.5 mb-3 backdrop-blur-sm">
|
||||
<span className="flex h-1.5 w-1.5 bg-white rounded-full"></span>
|
||||
<span className="text-xs font-mono text-zinc-400">v1.7.1</span>
|
||||
</div>
|
||||
|
||||
<h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold tracking-tight text-white mb-3 font-mono">
|
||||
Universal Skills for<br />
|
||||
<span className="text-zinc-500">AI Coding Agents</span>
|
||||
</h1>
|
||||
|
||||
<p className="text-sm text-zinc-400 mb-5 max-w-lg font-mono leading-relaxed">
|
||||
Portable, reusable skills that work across Claude Code, Cursor, Codex,
|
||||
Windsurf, GitHub Copilot, and 12 more agents.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 mb-4">
|
||||
<button
|
||||
onClick={copyInstall}
|
||||
className="inline-flex items-center bg-black border border-zinc-700 px-3 py-2 hover:border-zinc-500 transition-colors"
|
||||
>
|
||||
<span className="text-zinc-500 mr-2 select-none">$</span>
|
||||
<span className="font-mono text-zinc-100 text-sm">npx skillkit@latest</span>
|
||||
<span className="ml-2 text-zinc-500 hover:text-white transition-colors flex items-center gap-1">
|
||||
{copied ? (
|
||||
<>
|
||||
{CHECK_ICON}
|
||||
<span className="text-xs text-green-400">Copied!</span>
|
||||
</>
|
||||
) : (
|
||||
COPY_ICON
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
<Button variant="outline" onClick={openGitHub}>
|
||||
GITHUB
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="hidden lg:block relative animate-fade-in-delay w-full">
|
||||
<div className="absolute -inset-1 bg-gradient-to-r from-zinc-800 via-zinc-700 to-zinc-800 rounded-lg opacity-20 blur-lg"></div>
|
||||
<div className="relative border border-zinc-800 bg-black rounded-lg overflow-hidden">
|
||||
<div className="flex items-center gap-1.5 px-3 py-2 border-b border-zinc-800 bg-zinc-900/50">
|
||||
<div className="w-2.5 h-2.5 rounded-full bg-zinc-700"></div>
|
||||
<div className="w-2.5 h-2.5 rounded-full bg-zinc-700"></div>
|
||||
<div className="w-2.5 h-2.5 rounded-full bg-zinc-700"></div>
|
||||
<span className="ml-2 text-zinc-500 text-xs font-mono">skillkit</span>
|
||||
</div>
|
||||
<div className="p-4 font-mono text-xs min-h-[200px] max-h-[280px]">
|
||||
{TERMINAL_LINES.slice(0, visibleLines).map((line, index) => (
|
||||
<div key={index} className="mb-1">
|
||||
{line.type === 'cmd' ? (
|
||||
<div className="flex items-center">
|
||||
<span className="text-zinc-600 mr-2">$</span>
|
||||
<span className="text-zinc-100">{line.text}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="pl-4 text-zinc-500">
|
||||
<span className="text-zinc-400">{line.text.slice(0, 1)}</span>
|
||||
{line.text.slice(1)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{isTyping && (
|
||||
<div className="flex items-center">
|
||||
<span className="text-zinc-600 mr-2">$</span>
|
||||
<span className="text-zinc-100">{currentText}</span>
|
||||
<span className="w-2 h-4 bg-zinc-400 ml-0.5 animate-pulse"></span>
|
||||
</div>
|
||||
)}
|
||||
{isComplete && (
|
||||
<div className="flex items-center mt-1">
|
||||
<span className="text-zinc-600 mr-2">$</span>
|
||||
<span className="w-2 h-4 bg-zinc-600 animate-pulse"></span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>{FADE_ANIMATION_STYLES}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { Button } from './Button';
|
||||
import { Card } from './Card';
|
||||
import { generateAgentSkill } from '../services/geminiService';
|
||||
import { searchSkills, IndexedSkill } from '../data/skills-index';
|
||||
import { AgentSkill, LoadingState } from '../types';
|
||||
|
||||
interface PriorityBadgeProps {
|
||||
priority: string;
|
||||
}
|
||||
|
||||
type ViewMode = 'search' | 'marketplace' | 'generated' | 'content';
|
||||
|
||||
const PRIORITY_COLORS = {
|
||||
must: 'bg-red-900/50 text-red-300 border-red-800',
|
||||
should: 'bg-yellow-900/50 text-yellow-300 border-yellow-800',
|
||||
may: 'bg-blue-900/50 text-blue-300 border-blue-800',
|
||||
} as const;
|
||||
|
||||
function PriorityBadge({ priority }: PriorityBadgeProps): React.ReactElement {
|
||||
const colorClass = PRIORITY_COLORS[priority as keyof typeof PRIORITY_COLORS] || PRIORITY_COLORS.may;
|
||||
return (
|
||||
<span className={`text-xs px-2 py-0.5 border font-mono uppercase ${colorClass}`}>
|
||||
{priority}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function generateSkillMd(skill: AgentSkill): string {
|
||||
const frontmatter = `---
|
||||
name: "${skill.name}"
|
||||
description: "${skill.description}"
|
||||
version: "${skill.version}"
|
||||
tags: [${skill.tags.map(t => `"${t}"`).join(', ')}]
|
||||
${skill.filePatterns?.length ? `globs: [${skill.filePatterns.map(p => `"${p}"`).join(', ')}]` : ''}
|
||||
---`;
|
||||
|
||||
const principlesSection = skill.principles.map(p =>
|
||||
`### ${p.priority.toUpperCase()}: ${p.title}\n\n${p.description}`
|
||||
).join('\n\n');
|
||||
|
||||
const patternsSection = skill.patterns.map(p =>
|
||||
`### ${p.name}\n\n${p.description}\n\n\`\`\`${p.language || 'typescript'}\n${p.example}\n\`\`\``
|
||||
).join('\n\n');
|
||||
|
||||
const antiPatternsSection = skill.antiPatterns.map(ap => {
|
||||
let content = `### ${ap.name}\n\n${ap.description}`;
|
||||
if (ap.badExample) {
|
||||
content += `\n\n**Bad:**\n\`\`\`typescript\n${ap.badExample}\n\`\`\``;
|
||||
}
|
||||
if (ap.goodExample) {
|
||||
content += `\n\n**Good:**\n\`\`\`typescript\n${ap.goodExample}\n\`\`\``;
|
||||
}
|
||||
return content;
|
||||
}).join('\n\n');
|
||||
|
||||
const content = `# ${skill.title}
|
||||
|
||||
${skill.description}
|
||||
|
||||
## When to Apply
|
||||
|
||||
${skill.applicability}
|
||||
|
||||
${skill.filePatterns?.length ? `**File patterns:** ${skill.filePatterns.map(p => `\`${p}\``).join(', ')}` : ''}
|
||||
|
||||
## Principles
|
||||
|
||||
${principlesSection}
|
||||
|
||||
## Patterns
|
||||
|
||||
${patternsSection}
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
${antiPatternsSection}
|
||||
|
||||
${skill.references?.length ? `## References\n\n${skill.references.map(r => `- ${r}`).join('\n')}` : ''}
|
||||
`;
|
||||
|
||||
return `${frontmatter}\n\n${content}`;
|
||||
}
|
||||
|
||||
function downloadContent(content: string, filename: string): void {
|
||||
const blob = new Blob([content], { type: 'text/markdown' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
// localStorage cache for AI-generated skills
|
||||
const CACHE_KEY = 'skillkit_ai_cache';
|
||||
const CACHE_VERSION = 1;
|
||||
const MAX_CACHE_ENTRIES = 50;
|
||||
const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
||||
|
||||
interface CachedSkill {
|
||||
skill: AgentSkill;
|
||||
query: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
interface SkillCache {
|
||||
version: number;
|
||||
skills: Record<string, CachedSkill>;
|
||||
}
|
||||
|
||||
function normalizeQuery(query: string): string {
|
||||
return query.toLowerCase().trim().replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
function getSkillCache(): SkillCache {
|
||||
try {
|
||||
const cached = localStorage.getItem(CACHE_KEY);
|
||||
if (cached) {
|
||||
const parsed = JSON.parse(cached) as SkillCache;
|
||||
if (parsed.version === CACHE_VERSION) {
|
||||
// Prune expired entries
|
||||
const now = Date.now();
|
||||
let mutated = false;
|
||||
for (const [key, value] of Object.entries(parsed.skills)) {
|
||||
if (!value?.timestamp || now - value.timestamp >= CACHE_TTL_MS) {
|
||||
delete parsed.skills[key];
|
||||
mutated = true;
|
||||
}
|
||||
}
|
||||
if (mutated) {
|
||||
localStorage.setItem(CACHE_KEY, JSON.stringify(parsed));
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore parse errors
|
||||
}
|
||||
return { version: CACHE_VERSION, skills: {} };
|
||||
}
|
||||
|
||||
function getCachedSkill(query: string): AgentSkill | null {
|
||||
const cache = getSkillCache();
|
||||
const key = normalizeQuery(query);
|
||||
const cached = cache.skills[key];
|
||||
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
|
||||
return cached.skill;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function setCachedSkill(query: string, skill: AgentSkill): void {
|
||||
try {
|
||||
const cache = getSkillCache();
|
||||
const key = normalizeQuery(query);
|
||||
cache.skills[key] = {
|
||||
skill,
|
||||
query: key,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
// Enforce max entries limit
|
||||
const entries = Object.entries(cache.skills);
|
||||
if (entries.length > MAX_CACHE_ENTRIES) {
|
||||
entries
|
||||
.sort((a, b) => a[1].timestamp - b[1].timestamp)
|
||||
.slice(0, entries.length - MAX_CACHE_ENTRIES)
|
||||
.forEach(([k]) => delete cache.skills[k]);
|
||||
}
|
||||
localStorage.setItem(CACHE_KEY, JSON.stringify(cache));
|
||||
} catch {
|
||||
// Ignore storage errors (quota exceeded, etc.)
|
||||
}
|
||||
}
|
||||
|
||||
export function SkillGenerator(): React.ReactElement {
|
||||
const [input, setInput] = useState('');
|
||||
const [status, setStatus] = useState<LoadingState>(LoadingState.IDLE);
|
||||
const [viewMode, setViewMode] = useState<ViewMode>('search');
|
||||
|
||||
const [marketplaceResults, setMarketplaceResults] = useState<IndexedSkill[]>([]);
|
||||
const [selectedSkill, setSelectedSkill] = useState<IndexedSkill | null>(null);
|
||||
const [skillContent, setSkillContent] = useState<string | null>(null);
|
||||
const [generatedSkill, setGeneratedSkill] = useState<AgentSkill | null>(null);
|
||||
const [isFromCache, setIsFromCache] = useState(false);
|
||||
const [activeTab, setActiveTab] = useState<'principles' | 'patterns' | 'antipatterns'>('principles');
|
||||
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
function handleSearch(e: React.FormEvent): void {
|
||||
e.preventDefault();
|
||||
if (!input.trim()) return;
|
||||
|
||||
setError(null);
|
||||
setSelectedSkill(null);
|
||||
setSkillContent(null);
|
||||
setGeneratedSkill(null);
|
||||
|
||||
const results = searchSkills(input);
|
||||
setMarketplaceResults(results);
|
||||
setViewMode(results.length > 0 ? 'marketplace' : 'search');
|
||||
setStatus(LoadingState.SUCCESS);
|
||||
}
|
||||
|
||||
async function handleViewSkill(skill: IndexedSkill): Promise<void> {
|
||||
setSelectedSkill(skill);
|
||||
setSkillContent(null);
|
||||
setViewMode('content');
|
||||
|
||||
if (skill.rawUrl) {
|
||||
setStatus(LoadingState.LOADING);
|
||||
try {
|
||||
const response = await fetch(skill.rawUrl);
|
||||
if (response.ok) {
|
||||
const content = await response.text();
|
||||
setSkillContent(content);
|
||||
}
|
||||
} catch {
|
||||
// Silently handle fetch errors
|
||||
}
|
||||
setStatus(LoadingState.SUCCESS);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleGenerateWithAI(): Promise<void> {
|
||||
setError(null);
|
||||
|
||||
// Check cache first
|
||||
const cached = getCachedSkill(input);
|
||||
if (cached) {
|
||||
setGeneratedSkill(cached);
|
||||
setIsFromCache(true);
|
||||
setViewMode('generated');
|
||||
setStatus(LoadingState.SUCCESS);
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus(LoadingState.LOADING);
|
||||
setIsFromCache(false);
|
||||
|
||||
try {
|
||||
const result = await generateAgentSkill(input);
|
||||
setGeneratedSkill(result);
|
||||
setCachedSkill(input, result); // Cache the result
|
||||
setViewMode('generated');
|
||||
setStatus(LoadingState.SUCCESS);
|
||||
} catch {
|
||||
setError("Failed to generate skill. Please try again.");
|
||||
setStatus(LoadingState.ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
function submitToMarketplace(): void {
|
||||
if (!generatedSkill) return;
|
||||
|
||||
const slug = generatedSkill.name.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
|
||||
const skillContent = generateSkillMd(generatedSkill);
|
||||
|
||||
const body = `## 📤 AI-Generated Skill: ${generatedSkill.title}
|
||||
|
||||
### Skill Details
|
||||
- **Name:** ${generatedSkill.name}
|
||||
- **Description:** ${generatedSkill.description}
|
||||
- **Tags:** ${generatedSkill.tags.join(', ')}
|
||||
- **Version:** ${generatedSkill.version}
|
||||
|
||||
### SKILL.md Content
|
||||
|
||||
<details>
|
||||
<summary>Click to expand</summary>
|
||||
|
||||
\`\`\`markdown
|
||||
${skillContent.slice(0, 4000)}${skillContent.length > 4000 ? '\n...(truncated)' : ''}
|
||||
\`\`\`
|
||||
|
||||
</details>
|
||||
|
||||
### Checklist for Maintainer
|
||||
- [ ] Review skill content for quality
|
||||
- [ ] Add to \`marketplace/skills.json\`
|
||||
|
||||
---
|
||||
**Generated via:** AI Skill Generator
|
||||
**Search query:** "${input}"`;
|
||||
|
||||
const title = encodeURIComponent(`[AI Skill] ${generatedSkill.title}`);
|
||||
const encodedBody = encodeURIComponent(body);
|
||||
const url = `https://github.com/rohitg00/skillkit/issues/new?title=${title}&body=${encodedBody}&labels=ai-generated,skill-submission`;
|
||||
|
||||
window.open(url, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
|
||||
function handleBack(): void {
|
||||
switch (viewMode) {
|
||||
case 'content':
|
||||
setViewMode('marketplace');
|
||||
setSelectedSkill(null);
|
||||
setSkillContent(null);
|
||||
break;
|
||||
case 'generated':
|
||||
setViewMode(marketplaceResults.length > 0 ? 'marketplace' : 'search');
|
||||
setGeneratedSkill(null);
|
||||
break;
|
||||
default:
|
||||
setViewMode('search');
|
||||
setMarketplaceResults([]);
|
||||
}
|
||||
}
|
||||
|
||||
function downloadSkillMd(): void {
|
||||
if (skillContent) {
|
||||
downloadContent(skillContent, 'SKILL.md');
|
||||
}
|
||||
}
|
||||
|
||||
function downloadGeneratedSkillMd(): void {
|
||||
if (generatedSkill) {
|
||||
downloadContent(generateSkillMd(generatedSkill), 'SKILL.md');
|
||||
}
|
||||
}
|
||||
|
||||
// Focus input only after user interaction, not on initial page load
|
||||
useEffect(() => {
|
||||
if (status === LoadingState.SUCCESS && inputRef.current) {
|
||||
inputRef.current.focus({ preventScroll: true });
|
||||
}
|
||||
}, [status]);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 py-8">
|
||||
<div className="mb-6">
|
||||
<h2 className="text-xl font-bold text-white mb-1 font-sans">Skill Finder</h2>
|
||||
<p className="text-zinc-400 font-mono text-xs">
|
||||
Search the marketplace or generate new skills with AI.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSearch} className="mb-6">
|
||||
<div className="flex flex-col sm:flex-row gap-3">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
placeholder="e.g., React hooks, TypeScript, Next.js..."
|
||||
className="flex-1 bg-surface border border-zinc-700 text-white px-4 py-3 focus:ring-2 focus:ring-white focus:border-transparent outline-none font-mono text-sm placeholder-zinc-600"
|
||||
disabled={status === LoadingState.LOADING}
|
||||
/>
|
||||
<Button type="submit" isLoading={status === LoadingState.LOADING} className="sm:w-auto w-full">
|
||||
SEARCH
|
||||
</Button>
|
||||
</div>
|
||||
{error && <p className="mt-2 text-red-400 font-mono text-xs">{error}</p>}
|
||||
</form>
|
||||
|
||||
{viewMode !== 'search' && status !== LoadingState.LOADING && (
|
||||
<button
|
||||
onClick={handleBack}
|
||||
className="mb-6 text-zinc-400 hover:text-white font-mono text-sm flex items-center gap-2 transition-colors"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
Back
|
||||
</button>
|
||||
)}
|
||||
|
||||
{viewMode === 'marketplace' && status === LoadingState.SUCCESS && (
|
||||
<div className="animate-fade-in-up">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h3 className="text-lg font-mono text-zinc-300">
|
||||
Found {marketplaceResults.length} skill{marketplaceResults.length !== 1 ? 's' : ''} in marketplace
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 mb-8">
|
||||
{marketplaceResults.map((skill) => (
|
||||
<Card
|
||||
key={skill.id}
|
||||
className="hover:border-zinc-500 cursor-pointer transition-all"
|
||||
onClick={() => handleViewSkill(skill)}
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex-1">
|
||||
<h4 className="text-lg font-semibold text-white mb-1">{skill.name}</h4>
|
||||
<p className="text-zinc-400 text-sm mb-2">{skill.description || 'No description'}</p>
|
||||
<div className="flex items-center gap-2 text-xs text-zinc-500 font-mono">
|
||||
<span>{skill.source}</span>
|
||||
</div>
|
||||
</div>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-zinc-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</div>
|
||||
{skill.tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mt-3">
|
||||
{skill.tags.slice(0, 5).map((tag, idx) => (
|
||||
<span key={idx} className="text-xs bg-zinc-900 text-zinc-500 px-2 py-0.5 border border-zinc-800">
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-zinc-800 pt-6">
|
||||
<p className="text-zinc-500 font-mono text-sm mb-4">
|
||||
Don't see what you need? Generate a custom skill with AI.
|
||||
</p>
|
||||
<Button onClick={handleGenerateWithAI} isLoading={status === LoadingState.LOADING}>
|
||||
GENERATE WITH AI
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{viewMode === 'search' && status === LoadingState.SUCCESS && marketplaceResults.length === 0 && input && (
|
||||
<div className="animate-fade-in-up text-center py-4">
|
||||
<div className="text-zinc-500 font-mono text-sm mb-4">
|
||||
No skills found for "{input}" in the marketplace.
|
||||
</div>
|
||||
<Button onClick={handleGenerateWithAI}>
|
||||
GENERATE WITH AI
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{viewMode === 'content' && selectedSkill && (
|
||||
<div className="animate-fade-in-up">
|
||||
<div className="flex items-start justify-between mb-6 border-b border-zinc-800 pb-6">
|
||||
<div>
|
||||
<h3 className="text-2xl font-bold text-white mb-2">{selectedSkill.name}</h3>
|
||||
<p className="text-zinc-400 font-mono text-sm mb-2">{selectedSkill.description}</p>
|
||||
<div className="flex items-center gap-2 text-xs text-zinc-500 font-mono">
|
||||
<span>{selectedSkill.source}</span>
|
||||
{selectedSkill.sourceUrl && (
|
||||
<>
|
||||
<span>•</span>
|
||||
<a href={selectedSkill.sourceUrl} target="_blank" rel="noreferrer" className="hover:text-white">
|
||||
View on GitHub
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{skillContent && (
|
||||
<button
|
||||
onClick={downloadSkillMd}
|
||||
className="flex items-center gap-2 bg-white text-black px-4 py-2 font-mono text-sm hover:bg-zinc-200 transition-colors shrink-0 ml-4"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
DOWNLOAD
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{status === LoadingState.LOADING ? (
|
||||
<div className="text-zinc-500 font-mono text-sm">Loading content...</div>
|
||||
) : skillContent ? (
|
||||
<pre className="bg-zinc-950 border border-zinc-800 p-6 overflow-x-auto text-sm max-h-[600px] overflow-y-auto">
|
||||
<code className="text-zinc-300 font-mono whitespace-pre-wrap">{skillContent}</code>
|
||||
</pre>
|
||||
) : (
|
||||
<div className="bg-zinc-950 border border-zinc-800 p-6">
|
||||
<p className="text-zinc-400 font-mono text-sm mb-4">
|
||||
Skill content not available for direct preview.
|
||||
</p>
|
||||
<a
|
||||
href={selectedSkill.sourceUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center gap-2 bg-zinc-800 text-white px-4 py-2 font-mono text-sm hover:bg-zinc-700 transition-colors"
|
||||
>
|
||||
View on GitHub
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-6 pt-6 border-t border-zinc-800">
|
||||
<p className="text-zinc-500 font-mono text-sm mb-3">Install with SkillKit:</p>
|
||||
<pre className="bg-zinc-950 border border-zinc-800 p-4 text-sm overflow-x-auto">
|
||||
<code className="text-zinc-300 font-mono text-xs sm:text-sm whitespace-nowrap">
|
||||
npx skillkit install {selectedSkill.id.split('/').slice(0, 2).join('/')}
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{viewMode === 'generated' && generatedSkill && (
|
||||
<div className="animate-fade-in-up">
|
||||
<div className="flex items-start justify-between mb-8 border-b border-zinc-800 pb-6">
|
||||
<div className="flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2 mb-2">
|
||||
<h3 className="text-xl sm:text-2xl font-bold text-white">{generatedSkill.title}</h3>
|
||||
<span className="text-xs font-mono text-zinc-500 bg-zinc-900 px-2 py-1 border border-zinc-800">
|
||||
v{generatedSkill.version}
|
||||
</span>
|
||||
<span className="text-xs font-mono text-purple-400 bg-purple-900/30 px-2 py-1 border border-purple-800/50">
|
||||
AI Generated
|
||||
</span>
|
||||
{isFromCache && (
|
||||
<span className="text-xs font-mono text-green-400 bg-green-900/30 px-2 py-1 border border-green-800/50">
|
||||
Cached
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-zinc-400 font-mono text-sm mb-4">{generatedSkill.description}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{generatedSkill.tags.map((tag, idx) => (
|
||||
<span key={idx} className="text-xs bg-zinc-900 text-zinc-400 px-2 py-1 border border-zinc-800">
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row gap-2 shrink-0 ml-4">
|
||||
<button
|
||||
onClick={downloadGeneratedSkillMd}
|
||||
className="flex items-center justify-center gap-2 bg-white text-black px-4 py-2 font-mono text-sm hover:bg-zinc-200 transition-colors"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
DOWNLOAD
|
||||
</button>
|
||||
<button
|
||||
onClick={submitToMarketplace}
|
||||
className="flex items-center justify-center gap-2 bg-purple-600 text-white px-4 py-2 font-mono text-sm hover:bg-purple-500 transition-colors"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
|
||||
</svg>
|
||||
SUBMIT
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Card className="mb-6">
|
||||
<h4 className="text-sm font-mono text-zinc-500 uppercase tracking-wider mb-2">When to Apply</h4>
|
||||
<p className="text-zinc-300">{generatedSkill.applicability}</p>
|
||||
{generatedSkill.filePatterns && generatedSkill.filePatterns.length > 0 && (
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
{generatedSkill.filePatterns.map((pattern, idx) => (
|
||||
<code key={idx} className="text-xs bg-zinc-900 text-zinc-300 px-2 py-1 border border-zinc-800">
|
||||
{pattern}
|
||||
</code>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<div className="flex border-b border-zinc-800 mb-6">
|
||||
{(['principles', 'patterns', 'antipatterns'] as const).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
onClick={() => setActiveTab(tab)}
|
||||
className={`px-6 py-3 font-mono text-sm uppercase tracking-wider transition-colors ${
|
||||
activeTab === tab
|
||||
? 'text-white border-b-2 border-white -mb-px'
|
||||
: 'text-zinc-500 hover:text-zinc-300'
|
||||
}`}
|
||||
>
|
||||
{tab === 'antipatterns' ? 'Anti-Patterns' : tab}
|
||||
<span className="ml-2 text-xs text-zinc-600">
|
||||
({tab === 'principles' ? generatedSkill.principles.length : tab === 'patterns' ? generatedSkill.patterns.length : generatedSkill.antiPatterns.length})
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{activeTab === 'principles' && generatedSkill.principles.map((principle, idx) => (
|
||||
<Card key={idx} className="hover:border-zinc-600 transition-colors">
|
||||
<div className="flex items-start justify-between gap-4 mb-2">
|
||||
<h4 className="text-lg font-semibold text-white">{principle.title}</h4>
|
||||
<PriorityBadge priority={principle.priority} />
|
||||
</div>
|
||||
<p className="text-zinc-400 leading-relaxed">{principle.description}</p>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{activeTab === 'patterns' && generatedSkill.patterns.map((pattern, idx) => (
|
||||
<Card key={idx} className="hover:border-zinc-600 transition-colors">
|
||||
<h4 className="text-lg font-semibold text-white mb-2">{pattern.name}</h4>
|
||||
<p className="text-zinc-400 mb-4">{pattern.description}</p>
|
||||
<pre className="bg-zinc-950 border border-zinc-800 p-4 overflow-x-auto text-sm">
|
||||
<code className="text-zinc-300 font-mono">{pattern.example}</code>
|
||||
</pre>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{activeTab === 'antipatterns' && generatedSkill.antiPatterns.map((ap, idx) => (
|
||||
<Card key={idx} className="hover:border-zinc-600 transition-colors border-red-900/30">
|
||||
<h4 className="text-lg font-semibold text-white mb-2">{ap.name}</h4>
|
||||
<p className="text-zinc-400 mb-4">{ap.description}</p>
|
||||
{ap.badExample && (
|
||||
<div className="mb-4">
|
||||
<div className="text-xs font-mono text-red-400 mb-1 uppercase">Bad</div>
|
||||
<pre className="bg-red-950/20 border border-red-900/30 p-4 overflow-x-auto text-sm">
|
||||
<code className="text-red-300 font-mono">{ap.badExample}</code>
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
{ap.goodExample && (
|
||||
<div>
|
||||
<div className="text-xs font-mono text-zinc-300 mb-1 uppercase">Good</div>
|
||||
<pre className="bg-zinc-900/50 border border-zinc-700 p-4 overflow-x-auto text-sm">
|
||||
<code className="text-zinc-200 font-mono">{ap.goodExample}</code>
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{generatedSkill.references && generatedSkill.references.length > 0 && (
|
||||
<div className="mt-8 pt-6 border-t border-zinc-800">
|
||||
<h4 className="text-sm font-mono text-zinc-500 uppercase tracking-wider mb-3">References</h4>
|
||||
<ul className="space-y-1">
|
||||
{generatedSkill.references.map((ref, idx) => (
|
||||
<li key={idx}>
|
||||
<a
|
||||
href={ref}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-zinc-400 hover:text-white font-mono text-sm transition-colors"
|
||||
>
|
||||
{ref}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
import React, { useState, useCallback } from 'react';
|
||||
import { Card } from './Card';
|
||||
|
||||
type Mode = 'upload' | 'import';
|
||||
|
||||
interface SkillFormData {
|
||||
slug: string;
|
||||
displayName: string;
|
||||
description: string;
|
||||
version: string;
|
||||
tags: string;
|
||||
repoOwner: string;
|
||||
repoName: string;
|
||||
skillPath: string;
|
||||
authorGithub: string;
|
||||
skillContent: string;
|
||||
}
|
||||
|
||||
const INITIAL_FORM: SkillFormData = {
|
||||
slug: '',
|
||||
displayName: '',
|
||||
description: '',
|
||||
version: '1.0.0',
|
||||
tags: '',
|
||||
repoOwner: '',
|
||||
repoName: '',
|
||||
skillPath: '',
|
||||
authorGithub: '',
|
||||
skillContent: '',
|
||||
};
|
||||
|
||||
const TAG_SUGGESTIONS = [
|
||||
'react', 'typescript', 'nextjs', 'python', 'rust', 'go',
|
||||
'testing', 'api', 'database', 'devops', 'security', 'mobile',
|
||||
] as const;
|
||||
|
||||
const GITHUB_ICON = (
|
||||
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export function SkillSubmitForm(): React.ReactElement {
|
||||
const [mode, setMode] = useState<Mode>('import');
|
||||
const [form, setForm] = useState<SkillFormData>(INITIAL_FORM);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const [fileName, setFileName] = useState<string | null>(null);
|
||||
const [githubUrl, setGithubUrl] = useState('');
|
||||
const [isDetecting, setIsDetecting] = useState(false);
|
||||
const [detectError, setDetectError] = useState<string | null>(null);
|
||||
|
||||
function updateField(field: keyof SkillFormData, value: string): void {
|
||||
setForm(prev => {
|
||||
const updated = { ...prev, [field]: value };
|
||||
if (field === 'displayName' && !prev.slug) {
|
||||
updated.slug = value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
function addTag(tag: string): void {
|
||||
const currentTags = form.tags.split(',').map(t => t.trim()).filter(Boolean);
|
||||
if (!currentTags.includes(tag)) {
|
||||
updateField('tags', [...currentTags, tag].join(', '));
|
||||
}
|
||||
}
|
||||
|
||||
function parseSkillContent(content: string): void {
|
||||
const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
|
||||
if (frontmatterMatch) {
|
||||
const fm = frontmatterMatch[1];
|
||||
const nameMatch = fm.match(/name:\s*["']?([^"'\n]+)["']?/);
|
||||
const descMatch = fm.match(/description:\s*["']?([^"'\n]+)["']?/);
|
||||
const tagsMatch = fm.match(/tags:\s*\[([^\]]+)\]/);
|
||||
const versionMatch = fm.match(/version:\s*["']?([^"'\n]+)["']?/);
|
||||
|
||||
if (nameMatch) updateField('displayName', nameMatch[1].trim());
|
||||
if (descMatch) updateField('description', descMatch[1].trim());
|
||||
if (versionMatch) updateField('version', versionMatch[1].trim());
|
||||
if (tagsMatch) {
|
||||
const tags = tagsMatch[1].replace(/["']/g, '').split(',').map(t => t.trim()).join(', ');
|
||||
updateField('tags', tags);
|
||||
}
|
||||
}
|
||||
updateField('skillContent', content);
|
||||
}
|
||||
|
||||
async function handleDetect(): Promise<void> {
|
||||
if (!githubUrl) return;
|
||||
|
||||
setIsDetecting(true);
|
||||
setDetectError(null);
|
||||
|
||||
try {
|
||||
const urlMatch = githubUrl.match(/github\.com\/([^\/]+)\/([^\/]+)(?:\/(?:tree|blob)\/[^\/]+\/(.+))?/);
|
||||
|
||||
if (!urlMatch) {
|
||||
throw new Error('Invalid GitHub URL');
|
||||
}
|
||||
|
||||
const [, owner, repo, path = ''] = urlMatch;
|
||||
|
||||
const apiUrl = `https://api.github.com/repos/${owner}/${repo}`;
|
||||
const response = await fetch(apiUrl);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Repository not found or not public');
|
||||
}
|
||||
|
||||
const repoData = await response.json();
|
||||
|
||||
updateField('repoOwner', owner);
|
||||
updateField('repoName', repo);
|
||||
updateField('authorGithub', owner);
|
||||
updateField('displayName', repoData.name.replace(/-/g, ' ').replace(/\b\w/g, (c: string) => c.toUpperCase()));
|
||||
updateField('description', repoData.description || '');
|
||||
|
||||
const slug = path ? path.split('/').filter(Boolean).pop() || repo : repo;
|
||||
updateField('slug', slug.toLowerCase().replace(/[^a-z0-9-]/g, '-'));
|
||||
|
||||
if (repoData.topics && repoData.topics.length > 0) {
|
||||
updateField('tags', repoData.topics.slice(0, 5).join(', '));
|
||||
} else {
|
||||
const inferredTags: string[] = [];
|
||||
const nameLC = (repo + ' ' + (repoData.description || '')).toLowerCase();
|
||||
if (nameLC.includes('react')) inferredTags.push('react');
|
||||
if (nameLC.includes('typescript') || nameLC.includes('ts')) inferredTags.push('typescript');
|
||||
if (nameLC.includes('python')) inferredTags.push('python');
|
||||
if (nameLC.includes('skill')) inferredTags.push('skills');
|
||||
if (inferredTags.length > 0) {
|
||||
updateField('tags', inferredTags.join(', '));
|
||||
}
|
||||
}
|
||||
|
||||
updateField('skillContent', `[Linked from GitHub: ${owner}/${repo}]`);
|
||||
updateField('skillPath', path || '/');
|
||||
|
||||
} catch (err) {
|
||||
setDetectError(err instanceof Error ? err.message : 'Detection failed');
|
||||
} finally {
|
||||
setIsDetecting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const handleDragOver = useCallback(function(e: React.DragEvent): void {
|
||||
e.preventDefault();
|
||||
setIsDragging(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeave = useCallback(function(e: React.DragEvent): void {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
}, []);
|
||||
|
||||
const processMarkdownFile = useCallback(function(file: File): void {
|
||||
setFileName(file.name);
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
parseSkillContent(event.target?.result as string);
|
||||
};
|
||||
reader.readAsText(file);
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback(function(e: React.DragEvent): void {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
const mdFile = files.find(f => f.name.endsWith('.md'));
|
||||
|
||||
if (mdFile) {
|
||||
processMarkdownFile(mdFile);
|
||||
}
|
||||
}, [processMarkdownFile]);
|
||||
|
||||
function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>): void {
|
||||
const file = e.target.files?.[0];
|
||||
if (file && file.name.endsWith('.md')) {
|
||||
processMarkdownFile(file);
|
||||
}
|
||||
}
|
||||
|
||||
const validation = {
|
||||
slug: !form.slug ? 'Slug is required.' : null,
|
||||
displayName: !form.displayName ? 'Display name is required.' : null,
|
||||
content: mode === 'upload' && !form.skillContent ? 'Upload a SKILL.md file.' : null,
|
||||
repo: mode === 'import' && (!form.repoOwner || !form.repoName) ? 'Click Detect to import repo.' : null,
|
||||
tags: !form.tags ? 'Add at least one tag.' : null,
|
||||
};
|
||||
|
||||
const isImported = mode === 'import' && form.repoOwner && form.repoName;
|
||||
const errors = Object.values(validation).filter(Boolean);
|
||||
const isValid = errors.length === 0;
|
||||
const tagsArray = form.tags.split(',').map(t => t.trim()).filter(Boolean);
|
||||
|
||||
function generateIssueUrl(): string {
|
||||
const skillId = form.repoOwner && form.repoName
|
||||
? `${form.repoOwner}/${form.repoName}/${form.slug}`
|
||||
: `community/${form.authorGithub || 'anonymous'}/${form.slug}`;
|
||||
|
||||
const jsonEntry = JSON.stringify({
|
||||
id: skillId,
|
||||
name: form.displayName,
|
||||
description: form.description || '',
|
||||
source: `${form.repoOwner}/${form.repoName}`,
|
||||
tags: tagsArray,
|
||||
author: form.authorGithub || form.repoOwner
|
||||
}, null, 2);
|
||||
|
||||
const title = isImported
|
||||
? encodeURIComponent(`[Import] ${form.repoOwner}/${form.repoName}`)
|
||||
: encodeURIComponent(`[Skill] ${form.displayName}`);
|
||||
|
||||
const bodyContent = isImported
|
||||
? `## 📦 Import Request: ${form.repoOwner}/${form.repoName}
|
||||
|
||||
### Repository
|
||||
🔗 https://github.com/${form.repoOwner}/${form.repoName}
|
||||
|
||||
### Add to \`marketplace/skills.json\`
|
||||
|
||||
\`\`\`json
|
||||
${jsonEntry}
|
||||
\`\`\`
|
||||
|
||||
### Checklist for Maintainer
|
||||
- [ ] Verify repository is public
|
||||
- [ ] Add JSON entry to \`marketplace/skills.json\`
|
||||
|
||||
---
|
||||
**Submitted by:** @${form.authorGithub || 'anonymous'}
|
||||
**Owner:** @${form.repoOwner} (retains all rights)`
|
||||
: `## 📤 Skill Upload: ${form.displayName}
|
||||
|
||||
### Add to \`marketplace/skills.json\`
|
||||
|
||||
\`\`\`json
|
||||
${jsonEntry}
|
||||
\`\`\`
|
||||
|
||||
### SKILL.md Content
|
||||
|
||||
<details>
|
||||
<summary>Click to expand</summary>
|
||||
|
||||
\`\`\`markdown
|
||||
${form.skillContent.slice(0, 4000)}${form.skillContent.length > 4000 ? '\n...(truncated)' : ''}
|
||||
\`\`\`
|
||||
|
||||
</details>
|
||||
|
||||
### Checklist for Maintainer
|
||||
- [ ] Review SKILL.md content
|
||||
- [ ] Add JSON entry to \`marketplace/skills.json\`
|
||||
|
||||
---
|
||||
**Author:** @${form.authorGithub || 'anonymous'}`;
|
||||
|
||||
const body = encodeURIComponent(bodyContent);
|
||||
const labels = isImported ? 'skill-import' : 'skill-submission';
|
||||
return `https://github.com/rohitg00/skillkit/issues/new?title=${title}&body=${body}&labels=${labels}`;
|
||||
}
|
||||
|
||||
function handleSubmitClick(e: React.MouseEvent): void {
|
||||
e.preventDefault();
|
||||
if (isValid) {
|
||||
const url = generateIssueUrl();
|
||||
window.open(url, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex border-b border-zinc-800">
|
||||
<button
|
||||
onClick={() => setMode('import')}
|
||||
className={`px-6 py-3 font-mono text-sm transition-colors ${
|
||||
mode === 'import'
|
||||
? 'text-white border-b-2 border-white -mb-px'
|
||||
: 'text-zinc-500 hover:text-zinc-300'
|
||||
}`}
|
||||
>
|
||||
Import from GitHub
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setMode('upload')}
|
||||
className={`px-6 py-3 font-mono text-sm transition-colors ${
|
||||
mode === 'upload'
|
||||
? 'text-white border-b-2 border-white -mb-px'
|
||||
: 'text-zinc-500 hover:text-zinc-300'
|
||||
}`}
|
||||
>
|
||||
Upload File
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<div className="space-y-6">
|
||||
{mode === 'import' && (
|
||||
<Card>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<label className="text-sm text-zinc-400">GitHub URL</label>
|
||||
<span className="text-xs text-zinc-600">Repo, tree path, or blob</span>
|
||||
</div>
|
||||
<div className="flex gap-3 mt-2">
|
||||
<input
|
||||
type="text"
|
||||
value={githubUrl}
|
||||
onChange={(e) => setGithubUrl(e.target.value)}
|
||||
placeholder="https://github.com/owner/repo"
|
||||
className="flex-1 bg-zinc-900 border border-zinc-700 text-white px-4 py-2.5 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
|
||||
/>
|
||||
<button
|
||||
onClick={handleDetect}
|
||||
disabled={isDetecting || !githubUrl}
|
||||
className={`px-5 py-2.5 font-mono text-sm transition-colors ${
|
||||
isDetecting || !githubUrl
|
||||
? 'bg-zinc-800 text-zinc-600 cursor-not-allowed'
|
||||
: 'bg-white text-black hover:bg-zinc-200'
|
||||
}`}
|
||||
>
|
||||
{isDetecting ? 'Detecting...' : 'Detect'}
|
||||
</button>
|
||||
</div>
|
||||
{detectError && (
|
||||
<p className="text-red-400 text-xs mt-2 font-mono">{detectError}</p>
|
||||
)}
|
||||
{isImported && (
|
||||
<p className="text-zinc-300 text-xs mt-2 font-mono flex items-center gap-1">
|
||||
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
Repository detected - {form.repoOwner}/{form.repoName}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-zinc-600 text-xs mt-3">
|
||||
Public repos only. We link to the original - owner retains all rights.
|
||||
</p>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{mode === 'upload' && (
|
||||
<Card
|
||||
className={`transition-colors ${isDragging ? 'border-white bg-zinc-900' : ''}`}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<div className="text-center py-6">
|
||||
<div className="mb-3">
|
||||
<svg className="w-8 h-8 mx-auto text-zinc-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-zinc-400 text-sm mb-1">
|
||||
{fileName ? (
|
||||
<span className="text-white">{fileName}</span>
|
||||
) : (
|
||||
'Drop SKILL.md here'
|
||||
)}
|
||||
</p>
|
||||
<p className="text-zinc-600 text-xs mb-3">or</p>
|
||||
<label className="inline-block cursor-pointer">
|
||||
<span className="bg-zinc-800 hover:bg-zinc-700 text-white px-4 py-2 text-sm font-mono transition-colors">
|
||||
Choose file
|
||||
</span>
|
||||
<input
|
||||
type="file"
|
||||
accept=".md"
|
||||
onChange={handleFileSelect}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-1.5">Slug</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.slug}
|
||||
onChange={(e) => updateField('slug', e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
|
||||
placeholder="my-skill"
|
||||
className="w-full bg-zinc-900 border border-zinc-700 text-white px-3 py-2 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-1.5">Display name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.displayName}
|
||||
onChange={(e) => updateField('displayName', e.target.value)}
|
||||
placeholder="My Skill"
|
||||
className="w-full bg-zinc-900 border border-zinc-700 text-white px-3 py-2 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-1.5">Version</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.version}
|
||||
onChange={(e) => updateField('version', e.target.value)}
|
||||
placeholder="1.0.0"
|
||||
className="w-full bg-zinc-900 border border-zinc-700 text-white px-3 py-2 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-1.5">Tags</label>
|
||||
<input
|
||||
type="text"
|
||||
value={form.tags}
|
||||
onChange={(e) => updateField('tags', e.target.value)}
|
||||
placeholder="react, typescript"
|
||||
className="w-full bg-zinc-900 border border-zinc-700 text-white px-3 py-2 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{TAG_SUGGESTIONS.map((tag) => (
|
||||
<button
|
||||
key={tag}
|
||||
type="button"
|
||||
onClick={() => addTag(tag)}
|
||||
className="text-xs text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 px-2 py-0.5 border border-zinc-800 transition-colors"
|
||||
>
|
||||
+{tag}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<h4 className="text-sm text-zinc-400 mb-4">Preview</h4>
|
||||
<div className="bg-zinc-950 border border-zinc-800 p-4">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div>
|
||||
<h5 className="text-white font-semibold">
|
||||
{form.displayName || 'Skill Name'}
|
||||
</h5>
|
||||
<p className="text-zinc-500 text-sm mt-1">
|
||||
{form.description || 'No description'}
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-xs font-mono text-zinc-600 bg-zinc-900 px-2 py-1">
|
||||
v{form.version}
|
||||
</span>
|
||||
</div>
|
||||
{(form.repoOwner || form.authorGithub) && (
|
||||
<div className="flex items-center gap-2 text-xs text-zinc-600 font-mono mb-3">
|
||||
{form.repoOwner && form.repoName && <span>{form.repoOwner}/{form.repoName}</span>}
|
||||
{form.authorGithub && (
|
||||
<>
|
||||
{form.repoOwner && <span>•</span>}
|
||||
<span>@{form.authorGithub}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{tagsArray.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{tagsArray.map((tag, i) => (
|
||||
<span key={i} className="text-xs bg-zinc-900 text-zinc-500 px-2 py-0.5 border border-zinc-800">
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{isImported ? (
|
||||
<Card className="border-blue-900/50">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<div className="w-8 h-8 bg-blue-900/30 border border-blue-800 flex items-center justify-center">
|
||||
<svg className="w-4 h-4 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="text-sm text-white font-medium">Linked Repository</h4>
|
||||
<p className="text-xs text-zinc-500">Skills hosted by @{form.repoOwner}</p>
|
||||
</div>
|
||||
</div>
|
||||
<a
|
||||
href={`https://github.com/${form.repoOwner}/${form.repoName}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-sm text-blue-400 hover:text-blue-300 font-mono flex items-center gap-2"
|
||||
>
|
||||
github.com/{form.repoOwner}/{form.repoName}
|
||||
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
|
||||
</svg>
|
||||
</a>
|
||||
</Card>
|
||||
) : form.skillContent && !form.skillContent.startsWith('[Linked') ? (
|
||||
<Card>
|
||||
<h4 className="text-sm text-zinc-400 mb-3">SKILL.md</h4>
|
||||
<pre className="bg-zinc-950 border border-zinc-800 p-3 text-xs font-mono text-zinc-400 max-h-48 overflow-auto">
|
||||
{form.skillContent.slice(0, 1000)}
|
||||
{form.skillContent.length > 1000 && '\n...'}
|
||||
</pre>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{errors.length > 0 && (
|
||||
<div className="space-y-1 text-xs font-mono text-yellow-500">
|
||||
{errors.map((error, i) => (
|
||||
<div key={i} className="flex items-center gap-1">
|
||||
<span className="text-yellow-600">•</span> {error}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSubmitClick}
|
||||
disabled={!isValid}
|
||||
className={`flex items-center justify-center gap-3 w-full py-4 font-mono text-sm transition-all ${
|
||||
isValid
|
||||
? 'bg-white text-black hover:bg-zinc-200'
|
||||
: 'bg-zinc-800 text-zinc-600 cursor-not-allowed'
|
||||
}`}
|
||||
>
|
||||
{GITHUB_ICON}
|
||||
{isImported ? 'Import to marketplace' : 'Publish skill'}
|
||||
</button>
|
||||
|
||||
<p className="text-xs text-zinc-600 text-center font-mono">
|
||||
{isImported
|
||||
? 'Links to original repo → Owner retains rights'
|
||||
: 'Opens GitHub issue → We review → Added to marketplace'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import React from 'react';
|
||||
|
||||
interface TerminalProps {
|
||||
title?: string;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface CodeBlockProps {
|
||||
code: string;
|
||||
language?: string;
|
||||
}
|
||||
|
||||
interface CommandProps {
|
||||
cmd: string;
|
||||
comment?: string;
|
||||
}
|
||||
|
||||
export function Terminal({ title = 'bash', children, className = '' }: TerminalProps): React.ReactElement {
|
||||
return (
|
||||
<div className={`rounded-lg overflow-hidden border border-zinc-800 bg-[#09090b] shadow-2xl ${className}`}>
|
||||
<div className="flex items-center justify-between px-4 py-2 border-b border-zinc-800 bg-zinc-900/50">
|
||||
<div className="flex space-x-2">
|
||||
<div className="w-3 h-3 rounded-full bg-zinc-700"></div>
|
||||
<div className="w-3 h-3 rounded-full bg-zinc-700"></div>
|
||||
<div className="w-3 h-3 rounded-full bg-zinc-700"></div>
|
||||
</div>
|
||||
<div className="text-xs text-zinc-500 font-mono">{title}</div>
|
||||
<div className="w-10"></div>
|
||||
</div>
|
||||
<div className="p-4 font-mono text-sm overflow-x-auto">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CodeBlock({ code }: CodeBlockProps): React.ReactElement {
|
||||
return (
|
||||
<pre className="text-zinc-300 font-mono text-sm leading-relaxed whitespace-pre-wrap">
|
||||
{code}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
export function Command({ cmd, comment }: CommandProps): React.ReactElement {
|
||||
return (
|
||||
<div className="mb-2">
|
||||
<div className="flex text-zinc-100">
|
||||
<span className="text-zinc-500 mr-2">$</span>
|
||||
<span>{cmd}</span>
|
||||
</div>
|
||||
{comment && <div className="text-zinc-500 text-xs mt-1 ml-4"># {comment}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "SkillKit Marketplace",
|
||||
"description": "Schema for SkillKit marketplace skills index",
|
||||
"type": "object",
|
||||
"required": ["version", "skills"],
|
||||
"properties": {
|
||||
"version": {
|
||||
"type": "integer",
|
||||
"description": "Schema version number"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"description": "Last update date (YYYY-MM-DD)"
|
||||
},
|
||||
"skills": {
|
||||
"type": "array",
|
||||
"description": "List of skills in the marketplace",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Skill"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Skill": {
|
||||
"type": "object",
|
||||
"required": ["id", "name", "source", "tags"],
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_-]+$",
|
||||
"description": "Unique identifier: owner/repo/skill-name"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 100,
|
||||
"description": "Human-readable skill name"
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"maxLength": 500,
|
||||
"description": "Brief description of the skill"
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+$",
|
||||
"description": "GitHub repository: owner/repo"
|
||||
},
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z0-9-]+$"
|
||||
},
|
||||
"minItems": 1,
|
||||
"maxItems": 10,
|
||||
"description": "Tags for categorization (lowercase, hyphenated)"
|
||||
},
|
||||
"author": {
|
||||
"type": "string",
|
||||
"description": "Skill author name or GitHub username"
|
||||
},
|
||||
"version": {
|
||||
"type": "string",
|
||||
"pattern": "^\\d+\\.\\d+\\.\\d+$",
|
||||
"description": "Semantic version (e.g., 1.0.0)"
|
||||
},
|
||||
"agents": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"claude-code",
|
||||
"cursor",
|
||||
"codex",
|
||||
"gemini-cli",
|
||||
"opencode",
|
||||
"antigravity",
|
||||
"amp",
|
||||
"clawdbot",
|
||||
"droid",
|
||||
"github-copilot",
|
||||
"goose",
|
||||
"kilo",
|
||||
"kiro-cli",
|
||||
"roo",
|
||||
"trae",
|
||||
"windsurf",
|
||||
"universal"
|
||||
]
|
||||
},
|
||||
"description": "Compatible AI agents (omit for universal compatibility)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Single source of truth: marketplace/skills.json
|
||||
import skillsData from '../../../marketplace/skills.json';
|
||||
|
||||
export interface IndexedSkill {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
source: string;
|
||||
sourceUrl: string;
|
||||
rawUrl: string;
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
function buildSkillIndex(): IndexedSkill[] {
|
||||
return skillsData.skills.map(skill => {
|
||||
const sourceParts = skill.source?.split('/') || [];
|
||||
const owner = sourceParts[0] || 'unknown';
|
||||
const repo = sourceParts[1] || 'unknown';
|
||||
const skillSlug = skill.id.split('/').pop() || skill.name.toLowerCase().replace(/\s+/g, '-');
|
||||
|
||||
return {
|
||||
id: skill.id,
|
||||
name: skill.name,
|
||||
description: skill.description || '',
|
||||
source: skill.source || '',
|
||||
sourceUrl: owner !== 'unknown' ? `https://github.com/${skill.source}` : '',
|
||||
rawUrl: owner !== 'unknown' && repo !== 'unknown'
|
||||
? `https://raw.githubusercontent.com/${owner}/${repo}/main/skills/${skillSlug}/SKILL.md`
|
||||
: '',
|
||||
tags: skill.tags || [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export const SKILLS_INDEX: IndexedSkill[] = buildSkillIndex();
|
||||
|
||||
export function searchSkills(query: string): IndexedSkill[] {
|
||||
const q = query.toLowerCase().trim();
|
||||
if (!q) return [];
|
||||
|
||||
return SKILLS_INDEX.filter(skill =>
|
||||
skill.name.toLowerCase().includes(q) ||
|
||||
skill.description.toLowerCase().includes(q) ||
|
||||
skill.tags.some(tag => tag.toLowerCase().includes(q))
|
||||
).slice(0, 20);
|
||||
}
|
||||
|
||||
export function getSkillsByTag(tag: string): IndexedSkill[] {
|
||||
return SKILLS_INDEX.filter(skill =>
|
||||
skill.tags.some(t => t.toLowerCase() === tag.toLowerCase())
|
||||
);
|
||||
}
|
||||
|
||||
export function getAllTags(): string[] {
|
||||
const tags = new Set<string>();
|
||||
SKILLS_INDEX.forEach(skill => skill.tags.forEach(tag => tags.add(tag)));
|
||||
return Array.from(tags).sort();
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" class="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>SkillKit - Universal Skills for AI Coding Agents</title>
|
||||
<meta name="description" content="Portable, reusable skills that work across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more AI coding agents.">
|
||||
|
||||
<!-- Open Graph -->
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="https://skillkit.dev/">
|
||||
<meta property="og:title" content="SkillKit - Universal Skills for AI Coding Agents">
|
||||
<meta property="og:description" content="Portable, reusable skills that work across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more AI coding agents.">
|
||||
<meta property="og:image" content="/og-image.png">
|
||||
|
||||
<!-- Twitter -->
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<meta name="twitter:title" content="SkillKit - Universal Skills for AI Coding Agents">
|
||||
<meta name="twitter:description" content="Portable, reusable skills that work across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more AI coding agents.">
|
||||
<meta name="twitter:image" content="/og-image.png">
|
||||
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<script>
|
||||
tailwind.config = {
|
||||
darkMode: 'class',
|
||||
theme: {
|
||||
screens: {
|
||||
'xs': '475px',
|
||||
'sm': '640px',
|
||||
'md': '768px',
|
||||
'lg': '1024px',
|
||||
'xl': '1280px',
|
||||
'2xl': '1536px',
|
||||
},
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter', 'sans-serif'],
|
||||
mono: ['JetBrains Mono', 'monospace'],
|
||||
},
|
||||
colors: {
|
||||
background: '#000000',
|
||||
surface: '#09090b',
|
||||
border: '#27272a',
|
||||
highlight: '#ffffff',
|
||||
},
|
||||
animation: {
|
||||
'cursor-blink': 'blink 1s step-end infinite',
|
||||
},
|
||||
keyframes: {
|
||||
blink: {
|
||||
'0%, 100%': { opacity: '1' },
|
||||
'50%': { opacity: '0' },
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<style>
|
||||
body {
|
||||
background-color: #000000;
|
||||
color: #e4e4e7;
|
||||
font-family: 'Inter', sans-serif;
|
||||
}
|
||||
h1, h2, h3, h4, h5, h6, .font-mono {
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
}
|
||||
::selection {
|
||||
background-color: #ffffff;
|
||||
color: #000000;
|
||||
}
|
||||
::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
background: #000000;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #27272a;
|
||||
border: 1px solid #000000;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: #3f3f46;
|
||||
}
|
||||
|
||||
.terminal-scanline {
|
||||
background: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,0) 50%, rgba(0,0,0,0.1) 50%, rgba(0,0,0,0.1));
|
||||
background-size: 100% 4px;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
pointer-events: none;
|
||||
z-index: 10;
|
||||
opacity: 0.1;
|
||||
}
|
||||
</style>
|
||||
<script type="importmap">
|
||||
{
|
||||
"imports": {
|
||||
"react/": "https://esm.sh/react@^19.2.3/",
|
||||
"react": "https://esm.sh/react@^19.2.3",
|
||||
"@google/genai": "https://esm.sh/@google/genai@^1.38.0",
|
||||
"react-dom/": "https://esm.sh/react-dom@^19.2.3/"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/index.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
|
||||
const rootElement = document.getElementById('root');
|
||||
if (!rootElement) {
|
||||
throw new Error("Could not find root element to mount to");
|
||||
}
|
||||
|
||||
const root = ReactDOM.createRoot(rootElement);
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "SkillKit",
|
||||
"description": "Supercharge Every AI Coding Agent. Translate, manage, and sync skills across Claude, Cursor, Windsurf, and 17+ agents.",
|
||||
"requestFramePermissions": []
|
||||
}
|
||||
Generated
+2709
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "skillkit",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^19.2.3",
|
||||
"@google/genai": "^1.38.0",
|
||||
"react-dom": "^19.2.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.14.0",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"typescript": "~5.8.2",
|
||||
"vite": "^6.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>SkillKit</title>
|
||||
<script type="text/javascript">
|
||||
// Single Page Apps for GitHub Pages
|
||||
// MIT License
|
||||
// https://github.com/rafgraph/spa-github-pages
|
||||
var pathSegmentsToKeep = 1;
|
||||
var l = window.location;
|
||||
l.replace(
|
||||
l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
|
||||
l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
|
||||
l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
|
||||
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
|
||||
l.hash
|
||||
);
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 437 B |
@@ -0,0 +1,4 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<rect width="32" height="32" fill="#000000"/>
|
||||
<rect x="8" y="8" width="16" height="16" fill="#ffffff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 176 B |
Binary file not shown.
|
After Width: | Height: | Size: 158 KiB |
@@ -0,0 +1,124 @@
|
||||
import { GoogleGenAI, Type, Schema } from "@google/genai";
|
||||
import { AgentSkill } from "../types";
|
||||
|
||||
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
|
||||
|
||||
const agentSkillSchema: Schema = {
|
||||
type: Type.OBJECT,
|
||||
properties: {
|
||||
name: { type: Type.STRING, description: "Skill name in slug format (e.g., 'react-best-practices')" },
|
||||
title: { type: Type.STRING, description: "Human readable title" },
|
||||
description: { type: Type.STRING, description: "Brief description of what this skill teaches AI agents" },
|
||||
version: { type: Type.STRING, description: "Semantic version (e.g., '1.0.0')" },
|
||||
tags: {
|
||||
type: Type.ARRAY,
|
||||
items: { type: Type.STRING },
|
||||
description: "Tags for categorization"
|
||||
},
|
||||
applicability: { type: Type.STRING, description: "When the AI agent should apply this skill (e.g., 'Apply when working with React components')" },
|
||||
principles: {
|
||||
type: Type.ARRAY,
|
||||
items: {
|
||||
type: Type.OBJECT,
|
||||
properties: {
|
||||
title: { type: Type.STRING },
|
||||
description: { type: Type.STRING, description: "Detailed instruction for the AI agent" },
|
||||
priority: { type: Type.STRING, description: "must, should, or may" }
|
||||
},
|
||||
required: ["title", "description", "priority"]
|
||||
},
|
||||
description: "Core principles and guidelines (5-8 items)"
|
||||
},
|
||||
patterns: {
|
||||
type: Type.ARRAY,
|
||||
items: {
|
||||
type: Type.OBJECT,
|
||||
properties: {
|
||||
name: { type: Type.STRING },
|
||||
description: { type: Type.STRING },
|
||||
example: { type: Type.STRING, description: "Code example demonstrating the pattern" },
|
||||
language: { type: Type.STRING, description: "Programming language for syntax highlighting" }
|
||||
},
|
||||
required: ["name", "description", "example"]
|
||||
},
|
||||
description: "Code patterns with examples (3-5 items)"
|
||||
},
|
||||
antiPatterns: {
|
||||
type: Type.ARRAY,
|
||||
items: {
|
||||
type: Type.OBJECT,
|
||||
properties: {
|
||||
name: { type: Type.STRING },
|
||||
description: { type: Type.STRING },
|
||||
badExample: { type: Type.STRING, description: "Code showing what NOT to do" },
|
||||
goodExample: { type: Type.STRING, description: "Code showing the correct approach" }
|
||||
},
|
||||
required: ["name", "description"]
|
||||
},
|
||||
description: "Anti-patterns to avoid (2-4 items)"
|
||||
},
|
||||
filePatterns: {
|
||||
type: Type.ARRAY,
|
||||
items: { type: Type.STRING },
|
||||
description: "Glob patterns for files this skill applies to (e.g., '*.tsx', 'src/components/**')"
|
||||
},
|
||||
references: {
|
||||
type: Type.ARRAY,
|
||||
items: { type: Type.STRING },
|
||||
description: "Links to official documentation or resources"
|
||||
}
|
||||
},
|
||||
required: ["name", "title", "description", "version", "tags", "applicability", "principles", "patterns", "antiPatterns"]
|
||||
};
|
||||
|
||||
export const generateAgentSkill = async (topic: string): Promise<AgentSkill> => {
|
||||
const sanitizedTopic = topic?.trim().slice(0, 500) || '';
|
||||
if (!sanitizedTopic) {
|
||||
throw new Error("Topic is required");
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await ai.models.generateContent({
|
||||
model: "gemini-2.0-flash",
|
||||
contents: `Create a comprehensive AI coding agent skill for: "${sanitizedTopic}"
|
||||
|
||||
This skill will be used by AI coding assistants (like Claude Code, Cursor, GitHub Copilot) to provide better code suggestions and follow best practices.
|
||||
|
||||
The skill should include:
|
||||
1. Clear principles that tell the AI WHAT to do and WHEN
|
||||
2. Code patterns with REAL, WORKING examples (not pseudocode)
|
||||
3. Anti-patterns showing common mistakes and how to fix them
|
||||
4. Specific file patterns where this skill applies
|
||||
|
||||
Make the instructions actionable and specific. The AI agent should be able to directly apply these guidelines when writing code.
|
||||
|
||||
Focus on practical, production-ready patterns used in modern development.`,
|
||||
config: {
|
||||
responseMimeType: "application/json",
|
||||
responseSchema: agentSkillSchema,
|
||||
systemInstruction: `You are an expert software architect creating AI agent skills.
|
||||
Your skills are used by AI coding assistants to write better code.
|
||||
|
||||
Guidelines:
|
||||
- Write instructions as commands to the AI (e.g., "Always use...", "Never...", "Prefer...")
|
||||
- Include REAL code examples, not pseudocode
|
||||
- Be specific and actionable
|
||||
- Focus on modern best practices (2024+)
|
||||
- Include edge cases and error handling patterns
|
||||
- Make principles enforceable and testable`
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.text) {
|
||||
throw new Error("No response from Gemini.");
|
||||
}
|
||||
|
||||
const data = JSON.parse(response.text) as AgentSkill;
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error("Gemini API Error:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const generateLearningPath: (topic: string) => Promise<AgentSkill> = generateAgentSkill;
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"module": "ESNext",
|
||||
"lib": [
|
||||
"ES2022",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"skipLibCheck": true,
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"moduleResolution": "bundler",
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"allowJs": true,
|
||||
"jsx": "react-jsx",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./*"
|
||||
]
|
||||
},
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
export interface LearningStep {
|
||||
title: string;
|
||||
description: string;
|
||||
duration: string;
|
||||
keyConcepts: string[];
|
||||
}
|
||||
|
||||
export interface LearningPath {
|
||||
skill: string;
|
||||
description: string;
|
||||
steps: LearningStep[];
|
||||
}
|
||||
|
||||
export interface GenerateSkillResponse {
|
||||
learningPath: LearningPath;
|
||||
}
|
||||
|
||||
export enum LoadingState {
|
||||
IDLE = 'IDLE',
|
||||
LOADING = 'LOADING',
|
||||
SUCCESS = 'SUCCESS',
|
||||
ERROR = 'ERROR'
|
||||
}
|
||||
|
||||
export interface AgentSkill {
|
||||
name: string;
|
||||
title: string;
|
||||
description: string;
|
||||
version: string;
|
||||
tags: string[];
|
||||
applicability: string;
|
||||
principles: SkillPrinciple[];
|
||||
patterns: SkillPattern[];
|
||||
antiPatterns: SkillAntiPattern[];
|
||||
filePatterns?: string[];
|
||||
references?: string[];
|
||||
}
|
||||
|
||||
export interface SkillPrinciple {
|
||||
title: string;
|
||||
description: string;
|
||||
priority: 'must' | 'should' | 'may';
|
||||
}
|
||||
|
||||
export interface SkillPattern {
|
||||
name: string;
|
||||
description: string;
|
||||
example: string;
|
||||
language?: string;
|
||||
}
|
||||
|
||||
export interface SkillAntiPattern {
|
||||
name: string;
|
||||
description: string;
|
||||
badExample?: string;
|
||||
goodExample?: string;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"buildCommand": "npm run build",
|
||||
"outputDirectory": "dist",
|
||||
"installCommand": "npm install",
|
||||
"framework": "vite"
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import path from 'path';
|
||||
import { defineConfig, loadEnv } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, '.', '');
|
||||
return {
|
||||
base: '/',
|
||||
server: {
|
||||
port: 3000,
|
||||
host: '0.0.0.0',
|
||||
},
|
||||
plugins: [react()],
|
||||
define: {
|
||||
'process.env.API_KEY': JSON.stringify(env.GEMINI_API_KEY),
|
||||
'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY)
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, '.'),
|
||||
}
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
}
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,458 @@
|
||||
/**
|
||||
* E2E Tests: Commands, Settings, and Advanced Features
|
||||
*
|
||||
* Tests for: command generate/export/merge, settings, memory, audit, ai, cicd
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
describe('E2E: Slash Commands', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'commands-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'command-skill', {
|
||||
description: 'A skill for testing slash command generation',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit command generate', () => {
|
||||
it('should generate slash commands from skills', async () => {
|
||||
const result = await runCli(['command', 'generate'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('command') ||
|
||||
output.includes('generate') ||
|
||||
output.includes('slash') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate commands for specific agent', async () => {
|
||||
const result = await runCli(['command', 'generate', '--agent', 'claude-code'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should generate from natural language prompt', async () => {
|
||||
const result = await runCli(
|
||||
['command', 'generate', '--prompt', 'Create a command to run tests'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit command export', () => {
|
||||
it('should export generated commands', async () => {
|
||||
// Generate first
|
||||
await runCli(['command', 'generate'], { cwd: testDir });
|
||||
|
||||
const outputPath = join(testDir, 'commands-export');
|
||||
const result = await runCli(['command', 'export', '--output', outputPath], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should export in different formats', async () => {
|
||||
await runCli(['command', 'generate'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['command', 'export', '--format', 'json'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit command merge', () => {
|
||||
it('should merge multiple command files', async () => {
|
||||
// Create two command files
|
||||
mkdirSync(join(testDir, 'commands'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(testDir, 'commands', 'cmd1.json'),
|
||||
JSON.stringify({ commands: [{ name: 'test1' }] }, null, 2)
|
||||
);
|
||||
writeFileSync(
|
||||
join(testDir, 'commands', 'cmd2.json'),
|
||||
JSON.stringify({ commands: [{ name: 'test2' }] }, null, 2)
|
||||
);
|
||||
|
||||
const result = await runCli(
|
||||
[
|
||||
'command',
|
||||
'merge',
|
||||
join(testDir, 'commands', 'cmd1.json'),
|
||||
join(testDir, 'commands', 'cmd2.json'),
|
||||
],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Settings Management', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'settings-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit settings', () => {
|
||||
it('should show current settings', async () => {
|
||||
const result = await runCli(['settings'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('setting') ||
|
||||
output.includes('config') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should set a configuration value', async () => {
|
||||
const result = await runCli(['settings', '--set', 'defaultAgent=claude-code'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should get a specific setting', async () => {
|
||||
await runCli(['settings', '--set', 'testKey=testValue'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['settings', '--get', 'testKey'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should unset a configuration value', async () => {
|
||||
await runCli(['settings', '--set', 'removeKey=value'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['settings', '--unset', 'removeKey'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['settings', '--json'], { cwd: testDir });
|
||||
if (result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should reset all settings', async () => {
|
||||
const result = await runCli(['settings', '--reset'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Memory System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'memory-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit memory', () => {
|
||||
it('should show memory status', async () => {
|
||||
const result = await runCli(['memory'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('memory') ||
|
||||
output.includes('session') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should store observation', async () => {
|
||||
const result = await runCli(['memory', 'store', '--observation', 'User prefers TypeScript'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should retrieve memories', async () => {
|
||||
await runCli(['memory', 'store', '--observation', 'Test observation for retrieval'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['memory', 'retrieve'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should clear memory', async () => {
|
||||
const result = await runCli(['memory', 'clear'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should compress memory', async () => {
|
||||
// Store some memories
|
||||
await runCli(['memory', 'store', '--observation', 'Observation 1'], { cwd: testDir });
|
||||
await runCli(['memory', 'store', '--observation', 'Observation 2'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['memory', 'compress'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['memory', '--json'], { cwd: testDir });
|
||||
if (result.stdout.trim().startsWith('{') || result.stdout.trim().startsWith('[')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Audit System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'audit-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'audit-skill', {
|
||||
description: 'A skill for testing audit logging',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit audit', () => {
|
||||
it('should show audit log', async () => {
|
||||
// Perform some actions to generate audit entries
|
||||
await runCli(['list'], { cwd: testDir });
|
||||
await runCli(['sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['audit'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('audit') ||
|
||||
output.includes('log') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should filter audit by date range', async () => {
|
||||
const result = await runCli(['audit', '--since', '2024-01-01'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should filter audit by action type', async () => {
|
||||
const result = await runCli(['audit', '--action', 'sync'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should export audit log', async () => {
|
||||
const outputPath = join(testDir, 'audit-export.json');
|
||||
const result = await runCli(['audit', '--export', outputPath], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should clear audit log', async () => {
|
||||
const result = await runCli(['audit', '--clear'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: AI Features', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'ai-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit ai', () => {
|
||||
it('should show AI status', async () => {
|
||||
const result = await runCli(['ai'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('ai') ||
|
||||
output.includes('API') ||
|
||||
output.includes('status') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should configure AI provider', async () => {
|
||||
const result = await runCli(['ai', 'configure', '--provider', 'openai'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should test AI connection', async () => {
|
||||
const result = await runCli(['ai', 'test'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: CI/CD Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'cicd-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, '.git'), { recursive: true });
|
||||
writeFileSync(join(testDir, '.git', 'config'), '[core]');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit cicd init', () => {
|
||||
it('should generate GitHub Actions workflow', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'github'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('cicd') ||
|
||||
output.includes('github') ||
|
||||
output.includes('workflow') ||
|
||||
output.includes('created') ||
|
||||
testFileExists(testDir, '.github', 'workflows') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate GitLab CI config', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'gitlab'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should generate CircleCI config', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'circleci'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --dry-run', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'github', '--dry-run'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should handle unknown provider gracefully', async () => {
|
||||
const result = await runCli(['cicd', 'init', '--provider', 'unknown-ci'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('unknown') ||
|
||||
output.includes('not supported') ||
|
||||
output.includes('error') ||
|
||||
!result.success ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Workflow Commands', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'workflow-test',
|
||||
version: '1.0.0',
|
||||
scripts: {
|
||||
test: 'echo "test passed"',
|
||||
build: 'echo "build completed"',
|
||||
},
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit workflow-create', () => {
|
||||
it('should create a new workflow', async () => {
|
||||
const result = await runCli(['workflow-create', '--name', 'test-workflow'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should create workflow with steps', async () => {
|
||||
const result = await runCli(
|
||||
['workflow-create', '--name', 'stepped-workflow', '--steps', 'build,test,deploy'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit workflow-list', () => {
|
||||
it('should list available workflows', async () => {
|
||||
const result = await runCli(['workflow-list'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit workflow-run', () => {
|
||||
it('should run a workflow', async () => {
|
||||
await runCli(['workflow-create', '--name', 'runnable-workflow'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['workflow-run', 'runnable-workflow'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should run workflow with --dry-run', async () => {
|
||||
const result = await runCli(['workflow-run', 'test', '--dry-run'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
/**
|
||||
* E2E Tests: Core CLI Commands
|
||||
*
|
||||
* Tests for: init, list, install, enable, disable, remove, update, sync, read, validate
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
createTestProject,
|
||||
readTestFile,
|
||||
testFileExists,
|
||||
writeTestFile,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
describe('E2E: Core CLI Commands', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit --version', () => {
|
||||
it('should display version number', async () => {
|
||||
const result = await runCli(['--version']);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.stdout).toMatch(/\d+\.\d+\.\d+/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit --help', () => {
|
||||
it('should display help information', async () => {
|
||||
const result = await runCli(['--help']);
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.stdout).toContain('skillkit');
|
||||
});
|
||||
|
||||
it('should list available commands', async () => {
|
||||
const result = await runCli(['--help']);
|
||||
expect(result.stdout + result.stderr).toMatch(/init|list|install|sync/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit init', () => {
|
||||
it('should initialize skillkit in a new project', async () => {
|
||||
const result = await runCli(['init'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Check for concrete successful outcome - any of these directories
|
||||
const hasSkillsDir = testFileExists(testDir, 'skills');
|
||||
const hasSkillkitDir = testFileExists(testDir, '.skillkit');
|
||||
const hasClaudeSkills = testFileExists(testDir, '.claude/skills');
|
||||
const hasAgentSkills = testFileExists(testDir, '.agent/skills');
|
||||
const hasAnyDir = hasSkillsDir || hasSkillkitDir || hasClaudeSkills || hasAgentSkills;
|
||||
|
||||
// Either a directory was created OR the command completed successfully with output
|
||||
if (!hasAnyDir && result.exitCode !== 0) {
|
||||
// Fail with debugging info
|
||||
expect.fail(`Init failed. Exit code: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasAnyDir || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should create skills directory structure', async () => {
|
||||
const result = await runCli(['init'], { cwd: testDir });
|
||||
|
||||
// Verify expected structure actually exists - any of these directories
|
||||
const hasSkillsDir = testFileExists(testDir, 'skills');
|
||||
const hasSkillkitDir = testFileExists(testDir, '.skillkit');
|
||||
const hasClaudeSkills = testFileExists(testDir, '.claude/skills');
|
||||
const hasAgentSkills = testFileExists(testDir, '.agent/skills');
|
||||
const hasAnySkillDir = hasSkillsDir || hasSkillkitDir || hasClaudeSkills || hasAgentSkills;
|
||||
|
||||
// Strict assertion - init should create at least one directory
|
||||
if (!hasAnySkillDir) {
|
||||
const output = result.stdout + result.stderr;
|
||||
expect.fail(`Init did not create expected directories.\nExit code: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasAnySkillDir).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit list', () => {
|
||||
it('should list no skills in empty project', async () => {
|
||||
const result = await runCli(['list'], { cwd: testDir });
|
||||
// Should complete without error even if no skills
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should list discovered skills', async () => {
|
||||
// Create some test skills
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'my-skill');
|
||||
createTestSkill(skillsDir, 'another-skill');
|
||||
|
||||
const result = await runCli(['list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should find the skills or report none
|
||||
expect(output.includes('my-skill') || output.includes('skill') || output.includes('0')).toBe(
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
it('should support --json output format', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'json-test-skill');
|
||||
|
||||
const result = await runCli(['list', '--json'], { cwd: testDir });
|
||||
// If JSON format is supported, output should be parseable
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit read', () => {
|
||||
it('should read skill content', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'readable-skill', {
|
||||
content: 'This skill has specific content for reading.',
|
||||
});
|
||||
|
||||
const result = await runCli(['read', 'readable-skill'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should either show the skill or report not found
|
||||
expect(
|
||||
output.includes('readable-skill') ||
|
||||
output.includes('specific content') ||
|
||||
output.includes('not found') ||
|
||||
output.includes('No skill')
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle non-existent skill gracefully', async () => {
|
||||
const result = await runCli(['read', 'nonexistent-skill'], { cwd: testDir });
|
||||
// Should not crash, may report error
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit validate', () => {
|
||||
it('should validate a correct skill', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
const skillPath = createTestSkill(skillsDir, 'valid-skill', {
|
||||
description: 'A properly formatted skill with sufficient description length for validation',
|
||||
});
|
||||
|
||||
const result = await runCli(['validate', skillPath], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(output.includes('valid') || output.includes('success') || result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should report errors for invalid skill', async () => {
|
||||
const skillDir = join(testDir, 'invalid-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
// Create skill without frontmatter
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), '# No Frontmatter\n\nJust content.');
|
||||
|
||||
const result = await runCli(['validate', skillDir], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should report validation issues
|
||||
expect(
|
||||
output.includes('error') ||
|
||||
output.includes('invalid') ||
|
||||
output.includes('missing') ||
|
||||
!result.success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should validate skill with all Agent Skills spec fields', async () => {
|
||||
const skillDir = join(testDir, 'full-spec-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(skillDir, 'SKILL.md'),
|
||||
`---
|
||||
name: full-spec-skill
|
||||
description: A skill that uses all Agent Skills specification fields for complete validation testing
|
||||
license: MIT
|
||||
compatibility: Node.js 18+, requires npm
|
||||
allowed-tools: Bash(npm:*) Read Write Edit
|
||||
metadata:
|
||||
author: test-org
|
||||
version: "1.0.0"
|
||||
tags:
|
||||
- testing
|
||||
- e2e
|
||||
---
|
||||
|
||||
# Full Spec Skill
|
||||
|
||||
This skill uses all available frontmatter fields.
|
||||
`
|
||||
);
|
||||
|
||||
const result = await runCli(['validate', skillDir], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should complete validation - either valid or show specific validation messages
|
||||
expect(
|
||||
result.success ||
|
||||
output.includes('valid') ||
|
||||
output.includes('full-spec-skill') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit enable/disable', () => {
|
||||
it('should enable a skill', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'toggle-skill');
|
||||
|
||||
const result = await runCli(['enable', 'toggle-skill'], { cwd: testDir });
|
||||
// Command should complete
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should disable a skill', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'toggle-skill');
|
||||
|
||||
// First enable, then disable
|
||||
await runCli(['enable', 'toggle-skill'], { cwd: testDir });
|
||||
const result = await runCli(['disable', 'toggle-skill'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit sync', () => {
|
||||
it('should sync skills to agent config', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'sync-test-skill');
|
||||
|
||||
const result = await runCli(['sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should attempt sync operation
|
||||
expect(
|
||||
output.includes('sync') ||
|
||||
output.includes('claude') ||
|
||||
output.includes('skill') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit status', () => {
|
||||
it('should show current skillkit status', async () => {
|
||||
const result = await runCli(['status'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should show some status information
|
||||
expect(
|
||||
output.includes('status') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('agent') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit remove', () => {
|
||||
it('should remove an installed skill', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'removable-skill');
|
||||
|
||||
// First ensure it exists
|
||||
expect(testFileExists(testDir, 'skills', 'removable-skill', 'SKILL.md')).toBe(true);
|
||||
|
||||
const result = await runCli(['remove', 'removable-skill'], { cwd: testDir });
|
||||
// Command should complete
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,285 @@
|
||||
/**
|
||||
* E2E Test CLI Runner
|
||||
* Executes skillkit CLI commands and captures output for testing
|
||||
*/
|
||||
|
||||
import { spawn, execFileSync } from 'node:child_process';
|
||||
import { join, resolve, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { mkdirSync, rmSync, existsSync, writeFileSync, readFileSync, mkdtempSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
// ESM-compatible __dirname equivalent
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
|
||||
export interface CliResult {
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
exitCode: number;
|
||||
success: boolean;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
export interface RunOptions {
|
||||
cwd?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
timeout?: number;
|
||||
input?: string;
|
||||
}
|
||||
|
||||
const ROOT_DIR = resolve(__dirname, '../..');
|
||||
const CLI_PATH = join(ROOT_DIR, 'apps/skillkit/dist/cli.js');
|
||||
|
||||
/**
|
||||
* Run a skillkit CLI command and capture the result
|
||||
*/
|
||||
export async function runCli(args: string[], options: RunOptions = {}): Promise<CliResult> {
|
||||
const startTime = Date.now();
|
||||
const cwd = options.cwd || ROOT_DIR;
|
||||
const timeout = options.timeout || 30000;
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn('node', [CLI_PATH, ...args], {
|
||||
cwd,
|
||||
env: { ...process.env, ...options.env, NO_COLOR: '1', FORCE_COLOR: '0' },
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
let killed = false;
|
||||
|
||||
const timeoutId = setTimeout(() => {
|
||||
killed = true;
|
||||
child.kill('SIGTERM');
|
||||
}, timeout);
|
||||
|
||||
child.stdout?.on('data', (data) => {
|
||||
stdout += data.toString();
|
||||
});
|
||||
|
||||
child.stderr?.on('data', (data) => {
|
||||
stderr += data.toString();
|
||||
});
|
||||
|
||||
if (options.input) {
|
||||
child.stdin?.write(options.input);
|
||||
child.stdin?.end();
|
||||
}
|
||||
|
||||
child.on('close', (code) => {
|
||||
clearTimeout(timeoutId);
|
||||
const duration = Date.now() - startTime;
|
||||
const exitCode = killed ? -1 : (code ?? 1);
|
||||
resolve({
|
||||
stdout,
|
||||
stderr,
|
||||
exitCode,
|
||||
success: exitCode === 0,
|
||||
duration,
|
||||
});
|
||||
});
|
||||
|
||||
child.on('error', (err) => {
|
||||
clearTimeout(timeoutId);
|
||||
const duration = Date.now() - startTime;
|
||||
resolve({
|
||||
stdout,
|
||||
stderr: stderr + err.message,
|
||||
exitCode: 1,
|
||||
success: false,
|
||||
duration,
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Run skillkit CLI synchronously (for simpler tests)
|
||||
* Uses execFileSync to avoid shell injection vulnerabilities
|
||||
*/
|
||||
export function runCliSync(args: string[], options: RunOptions = {}): CliResult {
|
||||
const startTime = Date.now();
|
||||
const cwd = options.cwd || ROOT_DIR;
|
||||
|
||||
try {
|
||||
const result = execFileSync('node', [CLI_PATH, ...args], {
|
||||
cwd,
|
||||
env: { ...process.env, ...options.env, NO_COLOR: '1', FORCE_COLOR: '0' },
|
||||
encoding: 'utf-8',
|
||||
timeout: options.timeout || 30000,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: result,
|
||||
stderr: '',
|
||||
exitCode: 0,
|
||||
success: true,
|
||||
duration: Date.now() - startTime,
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
stdout: error.stdout || '',
|
||||
stderr: error.stderr || error.message,
|
||||
exitCode: error.status || 1,
|
||||
success: false,
|
||||
duration: Date.now() - startTime,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a temporary test directory
|
||||
*/
|
||||
export function createTestDir(prefix = 'skillkit-e2e-'): string {
|
||||
return mkdtempSync(join(tmpdir(), prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up a test directory
|
||||
*/
|
||||
export function cleanupTestDir(dir: string): void {
|
||||
if (existsSync(dir)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a test skill in a directory
|
||||
*/
|
||||
export function createTestSkill(
|
||||
dir: string,
|
||||
name: string,
|
||||
options: {
|
||||
description?: string;
|
||||
content?: string;
|
||||
additionalFrontmatter?: Record<string, unknown>;
|
||||
} = {}
|
||||
): string {
|
||||
const skillDir = join(dir, name);
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
|
||||
const frontmatter: Record<string, unknown> = {
|
||||
name,
|
||||
description: options.description || `Test skill: ${name} for E2E testing`,
|
||||
...options.additionalFrontmatter,
|
||||
};
|
||||
|
||||
const frontmatterStr = Object.entries(frontmatter)
|
||||
.map(([key, value]) => {
|
||||
if (typeof value === 'object') {
|
||||
return `${key}:\n${Object.entries(value as Record<string, unknown>)
|
||||
.map(([k, v]) => ` ${k}: ${JSON.stringify(v)}`)
|
||||
.join('\n')}`;
|
||||
}
|
||||
return `${key}: ${value}`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
const content = `---
|
||||
${frontmatterStr}
|
||||
---
|
||||
|
||||
# ${name}
|
||||
|
||||
${options.content || `This is a test skill named ${name}.`}
|
||||
`;
|
||||
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), content);
|
||||
return skillDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a test project with common setup
|
||||
*/
|
||||
export function createTestProject(options: {
|
||||
withSkills?: boolean;
|
||||
skillCount?: number;
|
||||
withGit?: boolean;
|
||||
projectType?: 'node' | 'python' | 'rust' | 'go';
|
||||
} = {}): { dir: string; cleanup: () => void } {
|
||||
const dir = createTestDir();
|
||||
|
||||
if (options.withGit) {
|
||||
mkdirSync(join(dir, '.git'), { recursive: true });
|
||||
writeFileSync(join(dir, '.git', 'config'), '[core]\n\trepositoryformatversion = 0');
|
||||
}
|
||||
|
||||
if (options.projectType === 'node') {
|
||||
writeFileSync(
|
||||
join(dir, 'package.json'),
|
||||
JSON.stringify({ name: 'test-project', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
} else if (options.projectType === 'python') {
|
||||
writeFileSync(join(dir, 'requirements.txt'), 'pytest>=7.0.0\n');
|
||||
} else if (options.projectType === 'rust') {
|
||||
writeFileSync(join(dir, 'Cargo.toml'), '[package]\nname = "test"\nversion = "0.1.0"');
|
||||
} else if (options.projectType === 'go') {
|
||||
writeFileSync(join(dir, 'go.mod'), 'module test\n\ngo 1.21');
|
||||
}
|
||||
|
||||
if (options.withSkills) {
|
||||
const skillsDir = join(dir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
// Use nullish coalescing to respect explicit 0
|
||||
const count = options.skillCount ?? 3;
|
||||
for (let i = 1; i <= count; i++) {
|
||||
createTestSkill(skillsDir, `test-skill-${i}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
dir,
|
||||
cleanup: () => cleanupTestDir(dir),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read file content from test directory
|
||||
*/
|
||||
export function readTestFile(dir: string, ...paths: string[]): string {
|
||||
return readFileSync(join(dir, ...paths), 'utf-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file exists in test directory
|
||||
*/
|
||||
export function testFileExists(dir: string, ...paths: string[]): boolean {
|
||||
return existsSync(join(dir, ...paths));
|
||||
}
|
||||
|
||||
/**
|
||||
* Write file in test directory
|
||||
*/
|
||||
export function writeTestFile(dir: string, path: string, content: string): void {
|
||||
const fullPath = join(dir, path);
|
||||
mkdirSync(join(fullPath, '..'), { recursive: true });
|
||||
writeFileSync(fullPath, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert CLI output contains expected text
|
||||
*/
|
||||
export function assertContains(result: CliResult, expected: string, message?: string): void {
|
||||
const combined = result.stdout + result.stderr;
|
||||
if (!combined.includes(expected)) {
|
||||
throw new Error(
|
||||
message || `Expected output to contain "${expected}"\nActual output:\n${combined}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert CLI output matches regex
|
||||
*/
|
||||
export function assertMatches(result: CliResult, pattern: RegExp, message?: string): void {
|
||||
const combined = result.stdout + result.stderr;
|
||||
if (!pattern.test(combined)) {
|
||||
throw new Error(
|
||||
message || `Expected output to match ${pattern}\nActual output:\n${combined}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* E2E Test Helpers - Barrel Export
|
||||
*/
|
||||
|
||||
export * from './cli-runner.js';
|
||||
@@ -0,0 +1,400 @@
|
||||
/**
|
||||
* E2E Tests: Hooks System and Agent Orchestration
|
||||
*
|
||||
* Tests for: hook register/list/trigger/remove, orchestrator commands
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
// Available hook events
|
||||
const HOOK_EVENTS = [
|
||||
'pre-commit',
|
||||
'post-commit',
|
||||
'file-change',
|
||||
'build',
|
||||
'test',
|
||||
'deploy',
|
||||
] as const;
|
||||
|
||||
describe('E2E: Hooks System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
// Create a git repo structure for commit hooks
|
||||
mkdirSync(join(testDir, '.git', 'hooks'), { recursive: true });
|
||||
writeFileSync(join(testDir, '.git', 'config'), '[core]\n\trepositoryformatversion = 0');
|
||||
// Create project files
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'hooks-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
// Create a skill that can be triggered
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'hookable-skill', {
|
||||
description: 'A skill that can be triggered by hooks for E2E testing',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit hook register', () => {
|
||||
it('should register a pre-commit hook', async () => {
|
||||
const result = await runCli(
|
||||
['hook', 'register', '--event', 'pre-commit', '--skill', 'hookable-skill'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Must have meaningful output about the registration
|
||||
const hasRelevantOutput =
|
||||
output.includes('register') ||
|
||||
output.includes('hook') ||
|
||||
output.includes('pre-commit') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Hook registration failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should register hooks for all event types', async () => {
|
||||
for (const event of HOOK_EVENTS) {
|
||||
const result = await runCli(
|
||||
['hook', 'register', '--event', event, '--skill', 'hookable-skill'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
// Fail explicitly on timeout (-1 exit code)
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
// Command should complete (exit code 0 or 1 for expected behavior)
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('should register hook with custom name', async () => {
|
||||
const result = await runCli(
|
||||
[
|
||||
'hook',
|
||||
'register',
|
||||
'--event',
|
||||
'test',
|
||||
'--skill',
|
||||
'hookable-skill',
|
||||
'--name',
|
||||
'my-test-hook',
|
||||
],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
// Fail explicitly on timeout
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
// Command should complete successfully or with expected exit
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should register hook with condition', async () => {
|
||||
const result = await runCli(
|
||||
[
|
||||
'hook',
|
||||
'register',
|
||||
'--event',
|
||||
'file-change',
|
||||
'--skill',
|
||||
'hookable-skill',
|
||||
'--pattern',
|
||||
'*.ts',
|
||||
],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
// Fail explicitly on timeout
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should handle invalid event gracefully', async () => {
|
||||
const result = await runCli(
|
||||
['hook', 'register', '--event', 'invalid-event', '--skill', 'hookable-skill'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should either fail or show an error message
|
||||
const showsError =
|
||||
output.includes('invalid') ||
|
||||
output.includes('unknown') ||
|
||||
output.includes('error') ||
|
||||
!result.success;
|
||||
|
||||
expect(showsError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit hook list', () => {
|
||||
it('should list registered hooks', async () => {
|
||||
// Register a hook first
|
||||
await runCli(['hook', 'register', '--event', 'build', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show hooks or indicate none
|
||||
const hasRelevantOutput =
|
||||
output.includes('hook') ||
|
||||
output.includes('build') ||
|
||||
output.includes('hookable-skill') ||
|
||||
output.includes('No');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Hook list failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['hook', 'list', '--json'], { cwd: testDir });
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should filter by event type', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'test', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'list', '--event', 'test'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit hook trigger', () => {
|
||||
it('should trigger a hook manually', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'test', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'trigger', 'test'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Fail explicitly on timeout
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
|
||||
// Should show trigger-related output
|
||||
const hasRelevantOutput =
|
||||
output.includes('trigger') ||
|
||||
output.includes('test') ||
|
||||
output.includes('hook') ||
|
||||
output.includes('executed');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Hook trigger failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should trigger with --dry-run', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'deploy', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'trigger', 'deploy', '--dry-run'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should handle missing hook gracefully', async () => {
|
||||
const result = await runCli(['hook', 'trigger', 'nonexistent-event'], { cwd: testDir });
|
||||
// Fail explicitly on timeout, should complete without crashing
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit hook remove', () => {
|
||||
it('should remove a registered hook', async () => {
|
||||
// Register then remove
|
||||
await runCli(
|
||||
['hook', 'register', '--event', 'build', '--skill', 'hookable-skill', '--name', 'my-hook'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
const result = await runCli(['hook', 'remove', 'my-hook'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show removal confirmation
|
||||
const hasRelevantOutput =
|
||||
output.includes('remove') ||
|
||||
output.includes('my-hook') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Hook remove failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should remove all hooks for an event', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'test', '--skill', 'hookable-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
|
||||
const result = await runCli(['hook', 'remove', '--event', 'test', '--all'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Agent Orchestration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'orchestration-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'orchestrated-skill', {
|
||||
description: 'A skill for testing multi-agent orchestration features',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('multi-agent sync', () => {
|
||||
it('should sync to multiple agents simultaneously', async () => {
|
||||
const result = await runCli(['sync', '--agents', 'claude-code,cursor,windsurf'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should sync to all supported agents', async () => {
|
||||
const result = await runCli(['sync', '--all-agents'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('team orchestration', () => {
|
||||
it('should configure team with leader and teammates', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(
|
||||
['team', 'init', '--leader', 'claude-code', '--teammates', 'cursor,windsurf'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should delegate tasks to team members', async () => {
|
||||
await runCli(['team', 'init', '--leader', 'claude-code'], { cwd: testDir });
|
||||
|
||||
// This tests the delegation feature if available
|
||||
const result = await runCli(['team', 'sync', '--delegate'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('workflow integration', () => {
|
||||
it('should trigger hooks during workflow execution', async () => {
|
||||
// Register a build hook
|
||||
await runCli(
|
||||
['hook', 'register', '--event', 'build', '--skill', 'orchestrated-skill'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
// Run workflow that triggers build
|
||||
const result = await runCli(['workflow', 'run', 'build'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should chain multiple hooks in sequence', async () => {
|
||||
await runCli(['hook', 'register', '--event', 'test', '--skill', 'orchestrated-skill'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
await runCli(
|
||||
['hook', 'register', '--event', 'build', '--skill', 'orchestrated-skill', '--after', 'test'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
const result = await runCli(['hook', 'trigger', 'test', '--chain'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Hook + Skill Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
mkdirSync(join(testDir, '.git', 'hooks'), { recursive: true });
|
||||
writeFileSync(join(testDir, '.git', 'config'), '[core]');
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
|
||||
// Create a skill with specific trigger configuration
|
||||
const skillDir = join(testDir, 'skills', 'auto-trigger-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(skillDir, 'SKILL.md'),
|
||||
`---
|
||||
name: auto-trigger-skill
|
||||
description: A skill that auto-triggers on specific events for E2E testing
|
||||
triggers:
|
||||
- event: pre-commit
|
||||
- event: file-change
|
||||
pattern: "*.ts"
|
||||
---
|
||||
|
||||
# Auto-Trigger Skill
|
||||
|
||||
This skill automatically activates on:
|
||||
- Pre-commit hooks
|
||||
- TypeScript file changes
|
||||
`
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should auto-register hooks from skill metadata', async () => {
|
||||
const result = await runCli(['hook', 'auto-register'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should detect and apply skill triggers', async () => {
|
||||
const result = await runCli(['sync', '--with-hooks'], { cwd: testDir });
|
||||
expect(result.exitCode).not.toBe(-1);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,424 @@
|
||||
/**
|
||||
* E2E Tests: Methodology and Plan System
|
||||
*
|
||||
* Tests for: methodology list/load/apply/validate, plan create/validate/execute/list/status
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
writeTestFile,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
// Available methodology packs
|
||||
const METHODOLOGY_PACKS = [
|
||||
'agile',
|
||||
'tdd',
|
||||
'devops',
|
||||
'security-first',
|
||||
'documentation-first',
|
||||
] as const;
|
||||
|
||||
describe('E2E: Methodology Framework', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
// Create a basic project structure
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'test-project', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'src'), { recursive: true });
|
||||
writeFileSync(join(testDir, 'src', 'index.ts'), 'export const main = () => {};\n');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit methodology list', () => {
|
||||
it('should list available methodology packs', async () => {
|
||||
const result = await runCli(['methodology', 'list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Must complete successfully and show relevant output
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should contain methodology-related content
|
||||
const hasRelevantOutput =
|
||||
output.includes('methodology') ||
|
||||
output.includes('agile') ||
|
||||
output.includes('tdd') ||
|
||||
output.includes('No');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Methodology list failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['methodology', 'list', '--json'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should show methodology details with --verbose', async () => {
|
||||
const result = await runCli(['methodology', 'list', '--verbose'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit methodology install', () => {
|
||||
describe.each(METHODOLOGY_PACKS)('loading %s methodology', (pack) => {
|
||||
it(`should load ${pack} methodology pack`, async () => {
|
||||
const result = await runCli(['methodology', 'install', pack], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Command should complete
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should have relevant output
|
||||
const hasRelevantOutput =
|
||||
output.includes(pack) ||
|
||||
output.includes('installed') ||
|
||||
output.includes('success') ||
|
||||
output.includes('methodology');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Load ${pack} failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle unknown methodology gracefully', async () => {
|
||||
const result = await runCli(['methodology', 'install', 'nonexistent-methodology'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show error or fail
|
||||
const showsError =
|
||||
output.includes('not found') ||
|
||||
output.includes('unknown') ||
|
||||
output.includes('error') ||
|
||||
!result.success;
|
||||
|
||||
expect(showsError).toBe(true);
|
||||
});
|
||||
|
||||
it('should load multiple methodologies', async () => {
|
||||
const result = await runCli(['methodology', 'install', 'tdd', 'security-first'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit methodology sync', () => {
|
||||
it('should sync installed methodology to project', async () => {
|
||||
// Install a methodology first
|
||||
await runCli(['methodology', 'install', 'tdd'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['methodology', 'sync'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('sync') ||
|
||||
output.includes('tdd') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Sync methodology failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should sync specific methodology', async () => {
|
||||
const result = await runCli(['methodology', 'sync', 'agile'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit methodology info', () => {
|
||||
it('should show methodology information', async () => {
|
||||
await runCli(['methodology', 'install', 'tdd'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['methodology', 'info', 'tdd'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('info') ||
|
||||
output.includes('tdd') ||
|
||||
output.includes('methodology') ||
|
||||
output.includes('description');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Methodology info failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should show info for specific methodology', async () => {
|
||||
const result = await runCli(['methodology', 'info', 'security-first'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Plan System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'plan-test-project', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, 'src'), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit plan create', () => {
|
||||
it('should create a new plan', async () => {
|
||||
const result = await runCli(['plan', 'create', '--name', 'test-plan'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('plan') ||
|
||||
output.includes('test-plan') ||
|
||||
output.includes('created');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan create failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should create plan with description', async () => {
|
||||
const result = await runCli(
|
||||
['plan', 'create', '--name', 'described-plan', '--description', 'A test plan for E2E'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should create plan from template', async () => {
|
||||
const result = await runCli(
|
||||
['plan', 'create', '--name', 'template-plan', '--template', 'feature'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should create plan with steps', async () => {
|
||||
const result = await runCli(
|
||||
[
|
||||
'plan',
|
||||
'create',
|
||||
'--name',
|
||||
'stepped-plan',
|
||||
'--steps',
|
||||
'Step 1: Setup,Step 2: Implement,Step 3: Test',
|
||||
],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plan templates', () => {
|
||||
it('should list available plan templates', async () => {
|
||||
const result = await runCli(['plan', 'templates'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('template') ||
|
||||
output.includes('plan') ||
|
||||
output.includes('available') ||
|
||||
output.includes('No');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan templates failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['plan', 'templates', '--json'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plan validate', () => {
|
||||
it('should validate plan structure', async () => {
|
||||
// Create a plan
|
||||
await runCli(['plan', 'create', '--name', 'validate-plan'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plan', 'validate', 'validate-plan'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('valid') ||
|
||||
output.includes('validate') ||
|
||||
output.includes('plan');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan validate failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should report validation errors', async () => {
|
||||
// Create an invalid plan file manually
|
||||
const plansDir = join(testDir, '.skillkit', 'plans');
|
||||
mkdirSync(plansDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(plansDir, 'invalid-plan.json'),
|
||||
JSON.stringify({ name: 'invalid' }) // Missing required fields
|
||||
);
|
||||
|
||||
const result = await runCli(['plan', 'validate', 'invalid-plan'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plan generate', () => {
|
||||
it('should generate a plan from a template', async () => {
|
||||
const result = await runCli(['plan', 'generate', '--template', 'feature'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('generate') ||
|
||||
output.includes('plan') ||
|
||||
output.includes('template') ||
|
||||
output.includes('feature');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan generate failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plan execute', () => {
|
||||
it('should execute a plan', async () => {
|
||||
await runCli(['plan', 'create', '--name', 'exec-plan'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plan', 'execute', 'exec-plan'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('execute') ||
|
||||
output.includes('plan') ||
|
||||
output.includes('exec-plan') ||
|
||||
output.includes('running');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Plan execute failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should execute with --dry-run', async () => {
|
||||
await runCli(['plan', 'create', '--name', 'dry-run-plan'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plan', 'execute', 'dry-run-plan', '--dry-run'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should execute specific step', async () => {
|
||||
await runCli(
|
||||
['plan', 'create', '--name', 'step-plan', '--steps', 'Step1,Step2,Step3'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
const result = await runCli(['plan', 'execute', 'step-plan', '--step', '1'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Methodology + Plan Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'integration-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should create plan based on methodology', async () => {
|
||||
// Load TDD methodology
|
||||
await runCli(['methodology', 'install', 'tdd'], { cwd: testDir });
|
||||
|
||||
// Create plan using TDD approach
|
||||
const result = await runCli(
|
||||
['plan', 'create', '--name', 'tdd-feature-plan', '--methodology', 'tdd'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should validate plan against methodology constraints', async () => {
|
||||
await runCli(['methodology', 'install', 'security-first'], { cwd: testDir });
|
||||
await runCli(['plan', 'create', '--name', 'secure-plan'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plan', 'validate', 'secure-plan', '--methodology'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,271 @@
|
||||
/**
|
||||
* E2E Tests: Onboarding UI
|
||||
*
|
||||
* Tests for the new @clack/prompts based CLI onboarding experience
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
describe('E2E: Onboarding UI', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit init --list', () => {
|
||||
it('should display agents with icons', async () => {
|
||||
const result = await runCli(['init', '--list']);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show agent icons
|
||||
expect(output).toContain('Claude Code');
|
||||
expect(output).toContain('Cursor');
|
||||
expect(output).toContain('Codex');
|
||||
|
||||
// Should show Skills dir info
|
||||
expect(output).toContain('Skills dir');
|
||||
expect(output).toContain('Config');
|
||||
|
||||
// Should complete successfully
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('should display all 17 agents', async () => {
|
||||
const result = await runCli(['init', '--list']);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
const agents = [
|
||||
'Claude Code',
|
||||
'Cursor',
|
||||
'Codex',
|
||||
'Gemini',
|
||||
'OpenCode',
|
||||
'Copilot',
|
||||
'Windsurf',
|
||||
'Droid',
|
||||
'Goose',
|
||||
'Amp',
|
||||
'Kilo',
|
||||
'Kiro',
|
||||
'Roo',
|
||||
'Trae',
|
||||
'Antigravity',
|
||||
'Clawdbot',
|
||||
'Universal',
|
||||
];
|
||||
|
||||
for (const agent of agents) {
|
||||
expect(output.toLowerCase()).toContain(agent.toLowerCase());
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit install --list', () => {
|
||||
it('should list skills with visual formatting', async () => {
|
||||
// Create a test repo-like structure
|
||||
const skillsDir = join(testDir, 'test-skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'skill-one');
|
||||
createTestSkill(skillsDir, 'skill-two');
|
||||
|
||||
const result = await runCli(['install', testDir, '--list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show skills found
|
||||
expect(output.toLowerCase()).toMatch(/skill|found|available/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit marketplace', () => {
|
||||
it('should display marketplace header', async () => {
|
||||
const result = await runCli(['marketplace', '--json']);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// JSON output should contain marketplace data
|
||||
if (result.success) {
|
||||
try {
|
||||
const data = JSON.parse(result.stdout.trim().split('\n').pop() || '{}');
|
||||
expect(data).toHaveProperty('totalSkills');
|
||||
expect(data).toHaveProperty('sources');
|
||||
} catch {
|
||||
// Non-JSON output is also acceptable
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should show popular tags with progress bars', async () => {
|
||||
const result = await runCli(['marketplace', 'tags', '--json']);
|
||||
|
||||
if (result.success && result.stdout.trim().startsWith('[')) {
|
||||
const tags = JSON.parse(result.stdout);
|
||||
expect(Array.isArray(tags)).toBe(true);
|
||||
if (tags.length > 0) {
|
||||
expect(tags[0]).toHaveProperty('tag');
|
||||
expect(tags[0]).toHaveProperty('count');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit sync', () => {
|
||||
it('should sync with formatted output', async () => {
|
||||
// Create skills to sync
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'sync-skill-1');
|
||||
createTestSkill(skillsDir, 'sync-skill-2');
|
||||
|
||||
const result = await runCli(['sync', '--agent', 'claude-code', '-y'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show sync operation
|
||||
expect(output.toLowerCase()).toMatch(/sync|skill|claude/);
|
||||
});
|
||||
|
||||
it('should show skill status indicators', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'enabled-skill');
|
||||
|
||||
const result = await runCli(['sync', '--agent', 'claude-code', '-y'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should complete without error
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit recommend', () => {
|
||||
it('should show project analysis with spinner', async () => {
|
||||
// Create a node project
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'test-project', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
|
||||
const result = await runCli(['recommend', '--quiet'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show some output about recommendations or project
|
||||
expect(
|
||||
output.toLowerCase().includes('project') ||
|
||||
output.toLowerCase().includes('skill') ||
|
||||
output.toLowerCase().includes('recommend') ||
|
||||
output.toLowerCase().includes('index') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should format scores with progress bars', async () => {
|
||||
// Create a TypeScript project
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({
|
||||
name: 'test-project',
|
||||
dependencies: { typescript: '^5.0.0' },
|
||||
}, null, 2)
|
||||
);
|
||||
writeFileSync(join(testDir, 'tsconfig.json'), '{}');
|
||||
|
||||
const result = await runCli(['recommend', '--json'], { cwd: testDir });
|
||||
|
||||
if (result.success && result.stdout.includes('"recommendations"')) {
|
||||
const data = JSON.parse(result.stdout);
|
||||
expect(data).toHaveProperty('recommendations');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Non-interactive mode', () => {
|
||||
it('should work with --yes flag', async () => {
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'test-skill');
|
||||
|
||||
const result = await runCli(['sync', '--agent', 'claude-code', '-y'], { cwd: testDir });
|
||||
// Should complete without prompting
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should work with --quiet flag', async () => {
|
||||
const result = await runCli(['init', '--list', '-q']);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should still show content but without extra formatting
|
||||
expect(output).toContain('Claude Code');
|
||||
});
|
||||
|
||||
it('should work with --json flag', async () => {
|
||||
const result = await runCli(['marketplace', '--json']);
|
||||
|
||||
// Should output valid JSON
|
||||
if (result.success) {
|
||||
const jsonLine = result.stdout.trim().split('\n').pop() || '';
|
||||
if (jsonLine.startsWith('{') || jsonLine.startsWith('[')) {
|
||||
expect(() => JSON.parse(jsonLine)).not.toThrow();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error handling', () => {
|
||||
it('should show formatted errors', async () => {
|
||||
const result = await runCli(['install', 'nonexistent-source-12345']);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should show some error message
|
||||
expect(
|
||||
output.toLowerCase().includes('error') ||
|
||||
output.toLowerCase().includes('fail') ||
|
||||
output.toLowerCase().includes('not found') ||
|
||||
!result.success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle missing skills gracefully', async () => {
|
||||
const result = await runCli(['read', 'nonexistent-skill'], { cwd: testDir });
|
||||
// Should not crash
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Visual elements', () => {
|
||||
it('should use Unicode symbols in output', async () => {
|
||||
const result = await runCli(['init', '--list']);
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should contain Unicode agent icons (any of the defined icons)
|
||||
const unicodePatterns = [
|
||||
/[\u2500-\u257F]/, // Box drawing
|
||||
/[\u25A0-\u25FF]/, // Geometric shapes
|
||||
/[\u2700-\u27BF]/, // Dingbats
|
||||
];
|
||||
|
||||
const hasUnicode = unicodePatterns.some(pattern => pattern.test(output));
|
||||
// Unicode support depends on terminal, so just check it doesn't crash
|
||||
expect(result.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle narrow terminal gracefully', async () => {
|
||||
// Even with narrow output, should not crash
|
||||
const result = await runCli(['init', '--list'], {
|
||||
env: { COLUMNS: '40' },
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,397 @@
|
||||
/**
|
||||
* E2E Tests: Plugin System
|
||||
*
|
||||
* Tests for: plugin list/install/uninstall/enable/disable/info
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
testFileExists,
|
||||
writeTestFile,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
describe('E2E: Plugin System', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'plugin-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
// Create .skillkit directory for plugin storage
|
||||
mkdirSync(join(testDir, '.skillkit', 'plugins'), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit plugin list', () => {
|
||||
it('should list installed plugins', async () => {
|
||||
const result = await runCli(['plugin', 'list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('plugin') ||
|
||||
output.includes('No') ||
|
||||
output.includes('installed') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const result = await runCli(['plugin', 'list', '--json'], { cwd: testDir });
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it('should show available plugins from marketplace', async () => {
|
||||
const result = await runCli(['plugin', 'list', '--available'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should filter enabled/disabled plugins', async () => {
|
||||
const result = await runCli(['plugin', 'list', '--enabled'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plugin install', () => {
|
||||
it('should install plugin from local path', async () => {
|
||||
// Create a mock plugin
|
||||
const pluginDir = join(testDir, 'my-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'my-plugin',
|
||||
version: '1.0.0',
|
||||
description: 'A test plugin for E2E testing',
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
writeFileSync(join(pluginDir, 'index.js'), 'module.exports = { init: () => {} };');
|
||||
|
||||
const result = await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('install') ||
|
||||
output.includes('my-plugin') ||
|
||||
output.includes('success') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should install plugin from npm-style name', async () => {
|
||||
// This may fail if plugin doesn't exist, but shouldn't crash
|
||||
const result = await runCli(['plugin', 'install', 'skillkit-plugin-example'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should handle non-existent plugin gracefully', async () => {
|
||||
const result = await runCli(['plugin', 'install', 'nonexistent-plugin-12345'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('not found') ||
|
||||
output.includes('error') ||
|
||||
output.includes('fail') ||
|
||||
!result.success ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should install with --force option', async () => {
|
||||
const pluginDir = join(testDir, 'force-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'force-plugin', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
|
||||
// Install twice with force
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
const result = await runCli(['plugin', 'install', pluginDir, '--force'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plugin uninstall', () => {
|
||||
it('should uninstall an installed plugin', async () => {
|
||||
// First install a plugin
|
||||
const pluginDir = join(testDir, 'uninstall-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'uninstall-plugin', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
// Then uninstall
|
||||
const result = await runCli(['plugin', 'uninstall', 'uninstall-plugin'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('uninstall') ||
|
||||
output.includes('remove') ||
|
||||
output.includes('success') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle uninstalling non-installed plugin gracefully', async () => {
|
||||
const result = await runCli(['plugin', 'uninstall', 'not-installed-plugin'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plugin enable/disable', () => {
|
||||
beforeEach(async () => {
|
||||
// Install a test plugin
|
||||
const pluginDir = join(testDir, 'toggle-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'toggle-plugin', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
});
|
||||
|
||||
it('should enable a disabled plugin', async () => {
|
||||
// First disable
|
||||
await runCli(['plugin', 'disable', 'toggle-plugin'], { cwd: testDir });
|
||||
|
||||
// Then enable
|
||||
const result = await runCli(['plugin', 'enable', 'toggle-plugin'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('enable') ||
|
||||
output.includes('toggle-plugin') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should disable an enabled plugin', async () => {
|
||||
const result = await runCli(['plugin', 'disable', 'toggle-plugin'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('disable') ||
|
||||
output.includes('toggle-plugin') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit plugin info', () => {
|
||||
it('should show plugin information', async () => {
|
||||
// Install a plugin first
|
||||
const pluginDir = join(testDir, 'info-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'info-plugin',
|
||||
version: '2.0.0',
|
||||
description: 'A plugin with detailed info for testing',
|
||||
author: 'Test Author',
|
||||
homepage: 'https://example.com',
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plugin', 'info', 'info-plugin'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('info-plugin') ||
|
||||
output.includes('2.0.0') ||
|
||||
output.includes('info') ||
|
||||
output.includes('description') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle non-existent plugin info gracefully', async () => {
|
||||
const result = await runCli(['plugin', 'info', 'nonexistent-plugin'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
const pluginDir = join(testDir, 'json-info-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'json-info-plugin', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plugin', 'info', 'json-info-plugin', '--json'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
if (result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Plugin Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'plugin-integration', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
mkdirSync(join(testDir, '.skillkit', 'plugins'), { recursive: true });
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should load plugin skills into skill list', async () => {
|
||||
// Create a plugin with skills
|
||||
const pluginDir = join(testDir, 'skills-plugin');
|
||||
mkdirSync(join(pluginDir, 'skills', 'plugin-skill'), { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'skills-plugin',
|
||||
version: '1.0.0',
|
||||
skills: ['skills/plugin-skill'],
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
writeFileSync(
|
||||
join(pluginDir, 'skills', 'plugin-skill', 'SKILL.md'),
|
||||
`---
|
||||
name: plugin-skill
|
||||
description: A skill provided by a plugin for E2E testing
|
||||
---
|
||||
|
||||
# Plugin Skill
|
||||
`
|
||||
);
|
||||
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
// List should include plugin skill
|
||||
const result = await runCli(['list'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should handle plugin hooks', async () => {
|
||||
// Create a plugin with hooks
|
||||
const pluginDir = join(testDir, 'hooks-plugin');
|
||||
mkdirSync(pluginDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(pluginDir, 'plugin.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'hooks-plugin',
|
||||
version: '1.0.0',
|
||||
hooks: {
|
||||
'pre-sync': 'echo "pre-sync from plugin"',
|
||||
'post-sync': 'echo "post-sync from plugin"',
|
||||
},
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
|
||||
await runCli(['plugin', 'install', pluginDir], { cwd: testDir });
|
||||
|
||||
// Sync should trigger plugin hooks
|
||||
const result = await runCli(['sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should respect plugin priority order', async () => {
|
||||
// Create two plugins with different priorities
|
||||
const plugin1Dir = join(testDir, 'priority-plugin-1');
|
||||
const plugin2Dir = join(testDir, 'priority-plugin-2');
|
||||
|
||||
mkdirSync(plugin1Dir, { recursive: true });
|
||||
mkdirSync(plugin2Dir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(plugin1Dir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'priority-plugin-1', version: '1.0.0', priority: 10 }, null, 2)
|
||||
);
|
||||
writeFileSync(
|
||||
join(plugin2Dir, 'plugin.json'),
|
||||
JSON.stringify({ name: 'priority-plugin-2', version: '1.0.0', priority: 20 }, null, 2)
|
||||
);
|
||||
|
||||
await runCli(['plugin', 'install', plugin1Dir], { cwd: testDir });
|
||||
await runCli(['plugin', 'install', plugin2Dir], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['plugin', 'list'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Marketplace Integration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'marketplace-test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit marketplace', () => {
|
||||
it('should list marketplace skills', async () => {
|
||||
const result = await runCli(['marketplace'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('marketplace') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('available') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should search marketplace', async () => {
|
||||
const result = await runCli(['marketplace', '--search', 'typescript'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should filter by category', async () => {
|
||||
const result = await runCli(['marketplace', '--category', 'testing'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should show skill details', async () => {
|
||||
const result = await runCli(['marketplace', '--info', 'some-skill'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,333 @@
|
||||
/**
|
||||
* E2E Tests: Team Collaboration Features
|
||||
*
|
||||
* Tests for: team init, team share, team import, team list, team sync, team remove, team bundle-*
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, existsSync, readFileSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
writeTestFile,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
describe('E2E: Team Collaboration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
// Create base project structure
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'team-skill-one', {
|
||||
description: 'First skill for team collaboration testing',
|
||||
});
|
||||
createTestSkill(join(testDir, 'skills'), 'team-skill-two', {
|
||||
description: 'Second skill for team collaboration testing',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit team init', () => {
|
||||
it('should initialize team configuration', async () => {
|
||||
const result = await runCli(['team', 'init'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Must complete successfully and show relevant output
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should initialize team structure or report status
|
||||
const hasRelevantOutput =
|
||||
output.includes('team') ||
|
||||
output.includes('init') ||
|
||||
output.includes('created') ||
|
||||
testFileExists(testDir, '.skillkit/team.json') ||
|
||||
testFileExists(testDir, '.skillkit');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team init failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should create team configuration file', async () => {
|
||||
const result = await runCli(
|
||||
['team', 'init', '--name', 'test-team', '--registry', 'local'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
|
||||
// Check for team config in various possible locations
|
||||
const hasTeamConfig =
|
||||
testFileExists(testDir, '.skillkit/team.json') ||
|
||||
testFileExists(testDir, '.skillkit/team.yaml') ||
|
||||
testFileExists(testDir, 'team.json') ||
|
||||
testFileExists(testDir, '.skillkit');
|
||||
|
||||
// Strict assertion - either created config or command succeeded
|
||||
if (!hasTeamConfig && result.exitCode !== 0) {
|
||||
const output = result.stdout + result.stderr;
|
||||
expect.fail(`Team init did not create config. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasTeamConfig || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should accept team name option', async () => {
|
||||
const result = await runCli(['team', 'init', '--name', 'test-team'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team list', () => {
|
||||
it('should list team skills', async () => {
|
||||
// Initialize team first
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'list'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should list skills or indicate none
|
||||
const hasRelevantOutput =
|
||||
output.includes('skill') ||
|
||||
output.includes('team') ||
|
||||
output.includes('No') ||
|
||||
output.includes('empty');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team list failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
const result = await runCli(['team', 'list', '--json'], { cwd: testDir });
|
||||
|
||||
if (result.stdout.trim().startsWith('[') || result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team share', () => {
|
||||
it('should share a skill with team', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
// Should share skill or report status
|
||||
const hasRelevantOutput =
|
||||
output.includes('share') ||
|
||||
output.includes('team-skill-one') ||
|
||||
output.includes('success') ||
|
||||
output.includes('added');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team share failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should share multiple skills', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'share', 'team-skill-one', 'team-skill-two'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should handle non-existent skill gracefully', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'share', 'nonexistent-skill'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
// Should report error or warning about missing skill
|
||||
const showsError =
|
||||
output.includes('not found') ||
|
||||
output.includes('error') ||
|
||||
output.includes('No') ||
|
||||
!result.success;
|
||||
|
||||
expect(showsError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team sync', () => {
|
||||
it('should sync team skills', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'sync'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('sync') ||
|
||||
output.includes('team') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team sync failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
|
||||
it('should sync with specific agent', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team remove', () => {
|
||||
it('should remove a shared skill from team', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(['team', 'remove', 'team-skill-one'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('remove') ||
|
||||
output.includes('team-skill-one') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team remove failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team import', () => {
|
||||
it('should import skills from team bundle', async () => {
|
||||
// Create a mock team bundle
|
||||
const bundleDir = join(testDir, 'team-bundle');
|
||||
mkdirSync(bundleDir, { recursive: true });
|
||||
createTestSkill(bundleDir, 'imported-skill', {
|
||||
description: 'A skill to be imported from a team bundle file',
|
||||
});
|
||||
|
||||
const result = await runCli(['team', 'import', bundleDir], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
|
||||
const hasRelevantOutput =
|
||||
output.includes('import') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('success');
|
||||
|
||||
if (!hasRelevantOutput && result.exitCode !== 0) {
|
||||
expect.fail(`Team import failed. Exit: ${result.exitCode}\nOutput: ${output}`);
|
||||
}
|
||||
|
||||
expect(hasRelevantOutput || result.exitCode === 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit team bundle-*', () => {
|
||||
it('should create team bundle (bundle-create)', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
|
||||
const bundlePath = join(testDir, 'my-bundle.skillkit');
|
||||
const result = await runCli(['team', 'bundle-create', '--output', bundlePath], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should list bundle contents (bundle-list)', async () => {
|
||||
// Create a bundle first
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
const bundlePath = join(testDir, 'test-bundle.skillkit');
|
||||
await runCli(['team', 'bundle-create', '--output', bundlePath], { cwd: testDir });
|
||||
|
||||
// Now list it
|
||||
const result = await runCli(['team', 'bundle-list', bundlePath], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should extract bundle (bundle-extract)', async () => {
|
||||
// Create bundle
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
await runCli(['team', 'share', 'team-skill-one'], { cwd: testDir });
|
||||
const bundlePath = join(testDir, 'extract-bundle.skillkit');
|
||||
await runCli(['team', 'bundle-create', '--output', bundlePath], { cwd: testDir });
|
||||
|
||||
// Extract to new location
|
||||
const extractDir = join(testDir, 'extracted');
|
||||
const result = await runCli(['team', 'bundle-extract', bundlePath, '--output', extractDir], {
|
||||
cwd: testDir,
|
||||
});
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Team Orchestration', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
mkdirSync(join(testDir, 'skills'), { recursive: true });
|
||||
createTestSkill(join(testDir, 'skills'), 'orchestration-skill', {
|
||||
description: 'A skill for testing multi-agent team orchestration features',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should configure team roles', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
// Configure team with roles
|
||||
const result = await runCli(['team', 'init', '--role', 'leader:claude-code'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should support multi-agent configuration', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
const result = await runCli(
|
||||
['team', 'init', '--agents', 'claude-code,cursor,github-copilot'],
|
||||
{ cwd: testDir }
|
||||
);
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should handle team task delegation', async () => {
|
||||
await runCli(['team', 'init'], { cwd: testDir });
|
||||
|
||||
// This tests the orchestration task feature if available
|
||||
const result = await runCli(['team', 'sync', '--all-agents'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeLessThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,345 @@
|
||||
/**
|
||||
* E2E Tests: Skill Translation Commands
|
||||
*
|
||||
* Tests for: translate, context, recommend
|
||||
* Validates translation to all 17 supported agents
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { join } from 'node:path';
|
||||
import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
|
||||
import {
|
||||
runCli,
|
||||
createTestDir,
|
||||
cleanupTestDir,
|
||||
createTestSkill,
|
||||
testFileExists,
|
||||
} from './helpers/cli-runner.js';
|
||||
|
||||
// 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 Translation', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
// Create a skill for translation tests
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'translation-test', {
|
||||
description: 'A skill designed for testing translation across multiple AI coding agents',
|
||||
content: `## Usage
|
||||
|
||||
Run this command to test the skill:
|
||||
|
||||
\`\`\`bash
|
||||
npm test
|
||||
\`\`\`
|
||||
|
||||
## Features
|
||||
|
||||
- Feature A: Does something useful
|
||||
- Feature B: Does something else
|
||||
`,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
describe('skillkit translate', () => {
|
||||
it('should translate skill to claude-code format', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'claude-code'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should complete translation or show relevant output
|
||||
expect(
|
||||
output.includes('claude') ||
|
||||
output.includes('translate') ||
|
||||
output.includes('CLAUDE.md') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should translate skill to cursor format', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'cursor'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('cursor') ||
|
||||
output.includes('.cursorrules') ||
|
||||
output.includes('translate') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should translate skill to windsurf format', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'windsurf'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('windsurf') ||
|
||||
output.includes('.windsurfrules') ||
|
||||
output.includes('translate') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should translate skill to github-copilot format', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'github-copilot'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('copilot') ||
|
||||
output.includes('.github') ||
|
||||
output.includes('translate') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should support universal format for all agents', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'universal'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
// Test all agents can at least attempt translation
|
||||
describe.each(SUPPORTED_AGENTS)('translation to %s', (agent) => {
|
||||
it(`should handle translation to ${agent}`, async () => {
|
||||
const result = await runCli(['translate', '--agent', agent], { cwd: testDir });
|
||||
// Should not crash - either succeeds or reports error gracefully
|
||||
expect(result.exitCode).toBeDefined();
|
||||
expect(typeof result.stdout).toBe('string');
|
||||
expect(typeof result.stderr).toBe('string');
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle unknown agent gracefully', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'nonexistent-agent'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should report error about unknown agent
|
||||
expect(
|
||||
output.toLowerCase().includes('unknown') ||
|
||||
output.toLowerCase().includes('not supported') ||
|
||||
output.toLowerCase().includes('invalid') ||
|
||||
output.toLowerCase().includes('error') ||
|
||||
!result.success
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should translate with --output option', async () => {
|
||||
const outputPath = join(testDir, 'translated-output');
|
||||
mkdirSync(outputPath, { recursive: true });
|
||||
|
||||
const result = await runCli(['translate', '--agent', 'claude-code', '--output', outputPath], {
|
||||
cwd: testDir,
|
||||
});
|
||||
// Command should complete
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should translate with --dry-run option', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'cursor', '--dry-run'], {
|
||||
cwd: testDir,
|
||||
});
|
||||
const output = result.stdout + result.stderr;
|
||||
// Dry run should show what would be done without making changes
|
||||
expect(result.exitCode !== undefined || output.length > 0).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit context', () => {
|
||||
it('should detect project context', async () => {
|
||||
// Create a Node.js project
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'test-project',
|
||||
version: '1.0.0',
|
||||
dependencies: { express: '^4.18.0' },
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
|
||||
const result = await runCli(['context'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should detect the project type
|
||||
expect(
|
||||
output.includes('node') ||
|
||||
output.includes('javascript') ||
|
||||
output.includes('typescript') ||
|
||||
output.includes('context') ||
|
||||
output.includes('project') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Python project', async () => {
|
||||
// Create a Python project
|
||||
writeFileSync(join(testDir, 'requirements.txt'), 'flask>=2.0.0\npytest>=7.0.0\n');
|
||||
writeFileSync(join(testDir, 'main.py'), 'print("Hello")\n');
|
||||
|
||||
const result = await runCli(['context'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('python') || output.includes('context') || result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Rust project', async () => {
|
||||
// Create a Rust project
|
||||
writeFileSync(
|
||||
join(testDir, 'Cargo.toml'),
|
||||
'[package]\nname = "test"\nversion = "0.1.0"\nedition = "2021"'
|
||||
);
|
||||
|
||||
const result = await runCli(['context'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('rust') || output.includes('context') || result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Go project', async () => {
|
||||
// Create a Go project
|
||||
writeFileSync(join(testDir, 'go.mod'), 'module example.com/test\n\ngo 1.21');
|
||||
|
||||
const result = await runCli(['context'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
expect(
|
||||
output.includes('go') || output.includes('context') || result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should support --json output', async () => {
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
|
||||
const result = await runCli(['context', '--json'], { cwd: testDir });
|
||||
// If JSON is supported, should be parseable
|
||||
if (result.stdout.trim().startsWith('{')) {
|
||||
expect(() => JSON.parse(result.stdout)).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('skillkit recommend', () => {
|
||||
it('should recommend skills for a project', async () => {
|
||||
// Create a Node.js project with common patterns
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: 'web-app',
|
||||
version: '1.0.0',
|
||||
dependencies: {
|
||||
express: '^4.18.0',
|
||||
typescript: '^5.0.0',
|
||||
jest: '^29.0.0',
|
||||
},
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
|
||||
const result = await runCli(['recommend'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Should provide recommendations or indicate none available
|
||||
expect(
|
||||
output.includes('recommend') ||
|
||||
output.includes('skill') ||
|
||||
output.includes('suggest') ||
|
||||
output.includes('No') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should handle empty project gracefully', async () => {
|
||||
const result = await runCli(['recommend'], { cwd: testDir });
|
||||
// Should not crash
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('should support --limit option', async () => {
|
||||
writeFileSync(
|
||||
join(testDir, 'package.json'),
|
||||
JSON.stringify({ name: 'test', version: '1.0.0' }, null, 2)
|
||||
);
|
||||
|
||||
const result = await runCli(['recommend', '--limit', '5'], { cwd: testDir });
|
||||
expect(result.exitCode).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('E2E: Agent Config Generation', () => {
|
||||
let testDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
testDir = createTestDir();
|
||||
const skillsDir = join(testDir, 'skills');
|
||||
mkdirSync(skillsDir, { recursive: true });
|
||||
createTestSkill(skillsDir, 'config-test-skill', {
|
||||
description: 'A skill for testing agent configuration generation across all agents',
|
||||
additionalFrontmatter: {
|
||||
'allowed-tools': 'Bash(npm:*) Read Write Edit',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanupTestDir(testDir);
|
||||
});
|
||||
|
||||
it('should generate valid claude-code config (CLAUDE.md)', async () => {
|
||||
const result = await runCli(['sync', '--agent', 'claude-code'], { cwd: testDir });
|
||||
// Check if CLAUDE.md was created or would be created
|
||||
const claudeMdExists = testFileExists(testDir, 'CLAUDE.md');
|
||||
expect(result.exitCode !== undefined || claudeMdExists).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate valid cursor config (.cursorrules)', async () => {
|
||||
const result = await runCli(['sync', '--agent', 'cursor'], { cwd: testDir });
|
||||
const cursorRulesExists = testFileExists(testDir, '.cursorrules');
|
||||
expect(result.exitCode !== undefined || cursorRulesExists).toBe(true);
|
||||
});
|
||||
|
||||
it('should generate valid windsurf config (.windsurfrules)', async () => {
|
||||
const result = await runCli(['sync', '--agent', 'windsurf'], { cwd: testDir });
|
||||
const windsurfRulesExists = testFileExists(testDir, '.windsurfrules');
|
||||
expect(result.exitCode !== undefined || windsurfRulesExists).toBe(true);
|
||||
});
|
||||
|
||||
it('should preserve allowed-tools in translation', async () => {
|
||||
const result = await runCli(['translate', '--agent', 'claude-code'], { cwd: testDir });
|
||||
const output = result.stdout + result.stderr;
|
||||
// Output or generated file should mention tools
|
||||
expect(
|
||||
output.includes('tool') ||
|
||||
output.includes('Bash') ||
|
||||
output.includes('permission') ||
|
||||
result.exitCode !== undefined
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": false,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"types": ["node", "vitest/globals"]
|
||||
},
|
||||
"include": ["**/*.ts"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
include: ['**/*.e2e.test.ts'],
|
||||
testTimeout: 60000, // E2E tests need more time
|
||||
hookTimeout: 30000,
|
||||
retry: 1, // Retry failed tests once for flaky network/fs operations
|
||||
sequence: {
|
||||
shuffle: false, // Run tests in order for debugging
|
||||
},
|
||||
pool: 'forks', // Use forks for better isolation
|
||||
poolOptions: {
|
||||
forks: {
|
||||
singleFork: false,
|
||||
isolate: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@skillkit/core': resolve(__dirname, '../packages/core/src/index.ts'),
|
||||
'@skillkit/agents': resolve(__dirname, '../packages/agents/src/index.ts'),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
# Contributing Skills to SkillKit Marketplace
|
||||
|
||||
## How to Add Your Skill
|
||||
|
||||
1. Fork this repository
|
||||
2. Add your skill to `marketplace/skills.json`
|
||||
3. Submit a Pull Request
|
||||
|
||||
## Skill Format
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "your-username/your-repo/skill-name",
|
||||
"name": "Your Skill Name",
|
||||
"description": "Brief description of what the skill does",
|
||||
"source": "your-username/your-repo",
|
||||
"tags": ["tag1", "tag2"]
|
||||
}
|
||||
```
|
||||
|
||||
## Field Reference
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `id` | Yes | Unique identifier: `owner/repo/skill-name` |
|
||||
| `name` | Yes | Human-readable name (max 100 chars) |
|
||||
| `description` | No | Brief description (max 500 chars) |
|
||||
| `source` | Yes | GitHub repository: `owner/repo` |
|
||||
| `tags` | Yes | 1-10 lowercase tags for categorization |
|
||||
| `author` | No | Your name or GitHub username |
|
||||
| `version` | No | Semantic version (e.g., `1.0.0`) |
|
||||
| `agents` | No | Compatible agents (omit for universal) |
|
||||
|
||||
## Skill Repository Structure
|
||||
|
||||
Your skill repository should contain a `SKILL.md` file:
|
||||
|
||||
```text
|
||||
your-repo/
|
||||
├── skills/
|
||||
│ └── skill-name/
|
||||
│ └── SKILL.md
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## SKILL.md Format
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: "skill-name"
|
||||
description: "What this skill does"
|
||||
version: "1.0.0"
|
||||
tags: ["tag1", "tag2"]
|
||||
globs: ["**/*.tsx", "**/*.ts"]
|
||||
---
|
||||
|
||||
# Skill Title
|
||||
|
||||
Instructions for AI agents...
|
||||
|
||||
## Principles
|
||||
|
||||
- Principle 1
|
||||
- Principle 2
|
||||
|
||||
## Patterns
|
||||
|
||||
### Pattern Name
|
||||
|
||||
Description and examples...
|
||||
```
|
||||
|
||||
## Guidelines
|
||||
|
||||
- **Be specific**: Skills should focus on one topic
|
||||
- **Include examples**: Code examples help AI agents understand patterns
|
||||
- **Test your skill**: Verify it works with at least one agent
|
||||
- **Keep it updated**: Maintain compatibility with latest agent versions
|
||||
|
||||
## Supported Agents
|
||||
|
||||
Skills can target specific agents or be universal:
|
||||
|
||||
- `claude-code` - Anthropic Claude Code
|
||||
- `cursor` - Cursor IDE
|
||||
- `codex` - OpenAI Codex CLI
|
||||
- `gemini-cli` - Google Gemini CLI
|
||||
- `windsurf` - Codeium Windsurf
|
||||
- `github-copilot` - GitHub Copilot
|
||||
- `universal` - All agents
|
||||
|
||||
## Questions?
|
||||
|
||||
Open an issue or join our Discord community.
|
||||
@@ -0,0 +1,99 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "SkillKit Marketplace",
|
||||
"description": "Schema for SkillKit marketplace skills index",
|
||||
"type": "object",
|
||||
"required": ["version", "skills"],
|
||||
"properties": {
|
||||
"version": {
|
||||
"type": "integer",
|
||||
"description": "Schema version number"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"description": "Last update date (YYYY-MM-DD)"
|
||||
},
|
||||
"skills": {
|
||||
"type": "array",
|
||||
"description": "List of skills in the marketplace",
|
||||
"items": {
|
||||
"$ref": "#/definitions/Skill"
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"Skill": {
|
||||
"type": "object",
|
||||
"required": ["id", "name", "source", "tags"],
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_-]+$",
|
||||
"description": "Unique identifier: owner/repo/skill-name"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 100,
|
||||
"description": "Human-readable skill name"
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"maxLength": 500,
|
||||
"description": "Brief description of the skill"
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+$",
|
||||
"description": "GitHub repository: owner/repo"
|
||||
},
|
||||
"tags": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z0-9-]+$"
|
||||
},
|
||||
"minItems": 1,
|
||||
"maxItems": 10,
|
||||
"description": "Tags for categorization (lowercase, hyphenated)"
|
||||
},
|
||||
"author": {
|
||||
"type": "string",
|
||||
"description": "Skill author name or GitHub username"
|
||||
},
|
||||
"version": {
|
||||
"type": "string",
|
||||
"pattern": "^\\d+\\.\\d+\\.\\d+$",
|
||||
"description": "Semantic version (e.g., 1.0.0)"
|
||||
},
|
||||
"agents": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"claude-code",
|
||||
"cursor",
|
||||
"codex",
|
||||
"gemini-cli",
|
||||
"opencode",
|
||||
"antigravity",
|
||||
"amp",
|
||||
"clawdbot",
|
||||
"droid",
|
||||
"github-copilot",
|
||||
"goose",
|
||||
"kilo",
|
||||
"kiro-cli",
|
||||
"roo",
|
||||
"trae",
|
||||
"windsurf",
|
||||
"universal"
|
||||
]
|
||||
},
|
||||
"description": "Compatible AI agents (omit for universal compatibility)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+125561
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "SkillKit Sources",
|
||||
"description": "Schema for curated skill repository sources",
|
||||
"type": "object",
|
||||
"required": ["version", "sources"],
|
||||
"properties": {
|
||||
"$schema": {
|
||||
"type": "string",
|
||||
"description": "Schema reference"
|
||||
},
|
||||
"version": {
|
||||
"type": "integer",
|
||||
"description": "Schema version"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"description": "Last update date"
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "Description of this file"
|
||||
},
|
||||
"sources": {
|
||||
"type": "array",
|
||||
"description": "List of curated skill sources",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["source", "name"],
|
||||
"properties": {
|
||||
"source": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+$",
|
||||
"description": "GitHub owner/repo format"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Display name for the source"
|
||||
},
|
||||
"official": {
|
||||
"type": "boolean",
|
||||
"description": "Whether this is an official source"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"$schema": "./sources-schema.json",
|
||||
"version": 1,
|
||||
"updatedAt": "2026-01-26",
|
||||
"description": "Curated skill repository sources - THE SINGLE SOURCE OF TRUTH",
|
||||
"sources": [
|
||||
{ "source": "anthropics/skills", "name": "Anthropic Official", "official": true },
|
||||
{ "source": "vercel-labs/agent-skills", "name": "Vercel Labs", "official": true },
|
||||
{ "source": "expo/skills", "name": "Expo / React Native", "official": true },
|
||||
{ "source": "remotion-dev/skills", "name": "Remotion Video", "official": true },
|
||||
{ "source": "supabase/agent-skills", "name": "Supabase", "official": true },
|
||||
{ "source": "stripe/ai", "name": "Stripe Payments", "official": true },
|
||||
{ "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": "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" }
|
||||
]
|
||||
}
|
||||
Generated
+109
-1823
File diff suppressed because it is too large
Load Diff
+7
-2
@@ -1,15 +1,19 @@
|
||||
{
|
||||
"name": "skillkit-monorepo",
|
||||
"version": "1.5.0",
|
||||
"version": "1.7.2",
|
||||
"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",
|
||||
"test:e2e": "vitest run --config e2e/vitest.config.ts",
|
||||
"test:e2e:watch": "vitest --config e2e/vitest.config.ts",
|
||||
"test:all": "pnpm test && pnpm test:e2e",
|
||||
"typecheck": "turbo run typecheck",
|
||||
"lint": "turbo run lint",
|
||||
"clean": "rm -rf node_modules packages/*/node_modules apps/*/node_modules packages/*/dist apps/*/dist"
|
||||
@@ -50,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.5.0",
|
||||
"version": "1.7.4",
|
||||
"description": "Agent adapters for SkillKit - supports 17+ AI coding agents",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { ClawdbotAdapter } from '../clawdbot.js';
|
||||
import type { Skill } from '@skillkit/core';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
// Mock filesystem functions
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('ClawdbotAdapter', () => {
|
||||
let adapter: ClawdbotAdapter;
|
||||
const mockExistsSync = vi.mocked(existsSync);
|
||||
|
||||
beforeEach(() => {
|
||||
adapter = new ClawdbotAdapter();
|
||||
mockExistsSync.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('configuration', () => {
|
||||
it('should have correct type', () => {
|
||||
expect(adapter.type).toBe('clawdbot');
|
||||
});
|
||||
|
||||
it('should have correct name', () => {
|
||||
expect(adapter.name).toBe('Clawdbot');
|
||||
});
|
||||
|
||||
it('should have correct skillsDir', () => {
|
||||
expect(adapter.skillsDir).toBe('.clawdbot/skills');
|
||||
});
|
||||
|
||||
it('should have correct configFile', () => {
|
||||
expect(adapter.configFile).toBe('AGENTS.md');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateConfig', () => {
|
||||
it('should return empty string for no enabled skills', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'test-skill',
|
||||
enabled: false,
|
||||
path: '/path/to/skill',
|
||||
content: '# Test',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
expect(config).toBe('');
|
||||
});
|
||||
|
||||
it('should generate config with enabled skills', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'test-skill',
|
||||
description: 'A test skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill',
|
||||
content: '# Test',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<skills_system priority="1">');
|
||||
expect(config).toContain('## Available Skills');
|
||||
expect(config).toContain('<name>test-skill</name>');
|
||||
expect(config).toContain('<description>A test skill</description>');
|
||||
expect(config).toContain('skillkit read <skill-name>');
|
||||
});
|
||||
|
||||
it('should generate config with multiple skills', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'skill-1',
|
||||
description: 'First skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill1',
|
||||
content: '# Skill 1',
|
||||
},
|
||||
{
|
||||
name: 'skill-2',
|
||||
description: 'Second skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill2',
|
||||
content: '# Skill 2',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<name>skill-1</name>');
|
||||
expect(config).toContain('<name>skill-2</name>');
|
||||
expect(config).toContain('<description>First skill</description>');
|
||||
expect(config).toContain('<description>Second skill</description>');
|
||||
});
|
||||
|
||||
it('should filter out disabled skills', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'enabled-skill',
|
||||
enabled: true,
|
||||
path: '/path/to/enabled',
|
||||
content: '# Enabled',
|
||||
},
|
||||
{
|
||||
name: 'disabled-skill',
|
||||
enabled: false,
|
||||
path: '/path/to/disabled',
|
||||
content: '# Disabled',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('enabled-skill');
|
||||
expect(config).not.toContain('disabled-skill');
|
||||
});
|
||||
|
||||
it('should include usage notes', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'test-skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill',
|
||||
content: '# Test',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<usage>');
|
||||
expect(config).toContain('When users ask you to perform tasks');
|
||||
expect(config).toContain('How to use skills:');
|
||||
expect(config).toContain('- Invoke:');
|
||||
expect(config).toContain('Usage notes:');
|
||||
});
|
||||
|
||||
it('should include available_skills section', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'test-skill',
|
||||
enabled: true,
|
||||
path: '/path/to/skill',
|
||||
content: '# Test',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<available_skills>');
|
||||
expect(config).toContain('</available_skills>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseConfig', () => {
|
||||
it('should parse skill names from config', () => {
|
||||
const config = `
|
||||
<skills_system>
|
||||
<available_skills>
|
||||
<skill>
|
||||
<name>skill-1</name>
|
||||
<description>Test skill 1</description>
|
||||
</skill>
|
||||
<skill>
|
||||
<name>skill-2</name>
|
||||
<description>Test skill 2</description>
|
||||
</skill>
|
||||
</available_skills>
|
||||
</skills_system>
|
||||
`;
|
||||
|
||||
const skillNames = adapter.parseConfig(config);
|
||||
|
||||
expect(skillNames).toEqual(['skill-1', 'skill-2']);
|
||||
});
|
||||
|
||||
it('should return empty array for no skills', () => {
|
||||
const config = '<skills_system></skills_system>';
|
||||
|
||||
const skillNames = adapter.parseConfig(config);
|
||||
|
||||
expect(skillNames).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle whitespace in skill names', () => {
|
||||
const config = `
|
||||
<skill>
|
||||
<name> skill-with-spaces </name>
|
||||
</skill>
|
||||
`;
|
||||
|
||||
const skillNames = adapter.parseConfig(config);
|
||||
|
||||
expect(skillNames).toEqual(['skill-with-spaces']);
|
||||
});
|
||||
|
||||
it('should handle multiple name tags', () => {
|
||||
const config = `
|
||||
<name>skill-1</name>
|
||||
<name>skill-2</name>
|
||||
<name>skill-3</name>
|
||||
`;
|
||||
|
||||
const skillNames = adapter.parseConfig(config);
|
||||
|
||||
expect(skillNames).toEqual(['skill-1', 'skill-2', 'skill-3']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getInvokeCommand', () => {
|
||||
it('should return correct invoke command', () => {
|
||||
const command = adapter.getInvokeCommand('test-skill');
|
||||
|
||||
expect(command).toBe('skillkit read test-skill');
|
||||
});
|
||||
|
||||
it('should work with skill names containing hyphens', () => {
|
||||
const command = adapter.getInvokeCommand('my-test-skill');
|
||||
|
||||
expect(command).toBe('skillkit read my-test-skill');
|
||||
});
|
||||
|
||||
it('should work with skill names containing underscores', () => {
|
||||
const command = adapter.getInvokeCommand('my_test_skill');
|
||||
|
||||
expect(command).toBe('skillkit read my_test_skill');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isDetected', () => {
|
||||
it('should detect Clawdbot from workspace skills directory', async () => {
|
||||
mockExistsSync.mockImplementation((path) => {
|
||||
return path === join(process.cwd(), 'skills');
|
||||
});
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Clawdbot from global directory', async () => {
|
||||
mockExistsSync.mockImplementation((path) => {
|
||||
return path === join(homedir(), '.clawdbot');
|
||||
});
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(true);
|
||||
});
|
||||
|
||||
it('should detect Clawdbot from config file', async () => {
|
||||
mockExistsSync.mockImplementation((path) => {
|
||||
return path === join(process.cwd(), 'clawdbot.json');
|
||||
});
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(true);
|
||||
});
|
||||
|
||||
it('should not detect Clawdbot when no indicators present', async () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(false);
|
||||
});
|
||||
|
||||
it('should detect when multiple indicators are present', async () => {
|
||||
mockExistsSync.mockReturnValue(true);
|
||||
|
||||
const detected = await adapter.isDetected();
|
||||
|
||||
expect(detected).toBe(true);
|
||||
});
|
||||
|
||||
it('should check all expected paths', async () => {
|
||||
mockExistsSync.mockReturnValue(false);
|
||||
|
||||
await adapter.isDetected();
|
||||
|
||||
expect(mockExistsSync).toHaveBeenCalledWith(join(process.cwd(), 'skills'));
|
||||
expect(mockExistsSync).toHaveBeenCalledWith(join(homedir(), '.clawdbot'));
|
||||
expect(mockExistsSync).toHaveBeenCalledWith(join(process.cwd(), 'clawdbot.json'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('integration', () => {
|
||||
it('should work end-to-end with typical workflow', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'react-patterns',
|
||||
description: 'React best practices',
|
||||
enabled: true,
|
||||
path: '/skills/react-patterns',
|
||||
content: '# React Patterns\n\nBest practices...',
|
||||
},
|
||||
{
|
||||
name: 'typescript-strict',
|
||||
description: 'TypeScript strict mode',
|
||||
enabled: true,
|
||||
path: '/skills/typescript-strict',
|
||||
content: '# TypeScript Strict\n\nUse strict mode...',
|
||||
},
|
||||
];
|
||||
|
||||
// Generate config
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
// Parse config
|
||||
const parsedSkills = adapter.parseConfig(config);
|
||||
|
||||
// Verify round-trip
|
||||
expect(parsedSkills).toEqual(['react-patterns', 'typescript-strict']);
|
||||
|
||||
// Get invoke commands
|
||||
const command1 = adapter.getInvokeCommand('react-patterns');
|
||||
const command2 = adapter.getInvokeCommand('typescript-strict');
|
||||
|
||||
expect(command1).toBe('skillkit read react-patterns');
|
||||
expect(command2).toBe('skillkit read typescript-strict');
|
||||
});
|
||||
|
||||
it('should preserve skill order during generation and parsing', () => {
|
||||
const skills: Skill[] = [
|
||||
{ name: 'a-skill', enabled: true, path: '/a', content: '' },
|
||||
{ name: 'z-skill', enabled: true, path: '/z', content: '' },
|
||||
{ name: 'm-skill', enabled: true, path: '/m', content: '' },
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
const parsed = adapter.parseConfig(config);
|
||||
|
||||
expect(parsed).toEqual(['a-skill', 'z-skill', 'm-skill']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should handle empty skills array', () => {
|
||||
const config = adapter.generateConfig([]);
|
||||
expect(config).toBe('');
|
||||
});
|
||||
|
||||
it('should handle skills without descriptions', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'no-desc-skill',
|
||||
enabled: true,
|
||||
path: '/path',
|
||||
content: '# No description',
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<name>no-desc-skill</name>');
|
||||
expect(config).toContain('<description></description>');
|
||||
});
|
||||
|
||||
it('should handle special characters in skill names', () => {
|
||||
const command = adapter.getInvokeCommand('skill-with-special_chars.123');
|
||||
|
||||
expect(command).toBe('skillkit read skill-with-special_chars.123');
|
||||
});
|
||||
|
||||
it('should handle empty config string during parsing', () => {
|
||||
const parsed = adapter.parseConfig('');
|
||||
|
||||
expect(parsed).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle malformed XML during parsing', () => {
|
||||
const config = '<name>skill-1<name>broken</name>';
|
||||
|
||||
const parsed = adapter.parseConfig(config);
|
||||
|
||||
// Should still extract valid names
|
||||
expect(parsed).toContain('broken');
|
||||
});
|
||||
});
|
||||
|
||||
describe('metadata handling', () => {
|
||||
it('should include skill metadata in generated config', () => {
|
||||
const skills: Skill[] = [
|
||||
{
|
||||
name: 'meta-skill',
|
||||
description: 'Has metadata',
|
||||
enabled: true,
|
||||
path: '/path',
|
||||
content: '# Meta',
|
||||
metadata: {
|
||||
version: '1.0.0',
|
||||
author: 'Test Author',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
expect(config).toContain('<name>meta-skill</name>');
|
||||
expect(config).toContain('<description>Has metadata</description>');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -20,7 +20,8 @@ export function createSkillXml(skill: Skill): string {
|
||||
</skill>`;
|
||||
}
|
||||
|
||||
export function escapeXml(text: string): string {
|
||||
export function escapeXml(text: string | undefined): string {
|
||||
if (!text) return '';
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
|
||||
@@ -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);
|
||||
@@ -68,7 +71,8 @@ ${skillsXml}
|
||||
async isDetected(): Promise<boolean> {
|
||||
const projectSkills = join(process.cwd(), 'skills');
|
||||
const globalClawdbot = join(homedir(), '.clawdbot');
|
||||
const clawdbotConfig = join(process.cwd(), 'clawdbot.json');
|
||||
|
||||
return existsSync(globalClawdbot) || (existsSync(projectSkills) && existsSync(join(process.cwd(), '.clawdbot')));
|
||||
return existsSync(projectSkills) || existsSync(globalClawdbot) || existsSync(clawdbotConfig);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.5.0",
|
||||
"version": "1.7.4",
|
||||
"description": "CLI commands for SkillKit",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
@@ -21,6 +21,7 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^0.11.0",
|
||||
"@skillkit/core": "workspace:*",
|
||||
"@skillkit/agents": "workspace:*",
|
||||
"@skillkit/tui": "workspace:*",
|
||||
@@ -29,6 +30,7 @@
|
||||
"got": "^14.4.1",
|
||||
"isomorphic-git": "^1.27.1",
|
||||
"ora": "^8.1.0",
|
||||
"picocolors": "^1.1.1",
|
||||
"yaml": "^2.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
/**
|
||||
* Unit Tests: Onboarding Module
|
||||
*
|
||||
* Tests for the CLI onboarding experience components
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { existsSync, mkdirSync, rmSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { mkdtempSync } from 'node:fs';
|
||||
|
||||
describe('Onboarding Module', () => {
|
||||
describe('theme', () => {
|
||||
it('should export agent icons', async () => {
|
||||
const { AGENT_ICONS, AGENT_NAMES } = await import('../onboarding/theme.js');
|
||||
|
||||
expect(AGENT_ICONS).toBeDefined();
|
||||
expect(AGENT_ICONS['claude-code']).toBe('\u27c1'); // ⟁
|
||||
expect(AGENT_ICONS['cursor']).toBe('\u25eb'); // ◫
|
||||
expect(AGENT_ICONS['codex']).toBe('\u25ce'); // ◎
|
||||
|
||||
expect(AGENT_NAMES).toBeDefined();
|
||||
expect(AGENT_NAMES['claude-code']).toBe('Claude Code');
|
||||
expect(AGENT_NAMES['cursor']).toBe('Cursor');
|
||||
});
|
||||
|
||||
it('should export symbols', async () => {
|
||||
const { symbols } = await import('../onboarding/theme.js');
|
||||
|
||||
expect(symbols).toBeDefined();
|
||||
expect(symbols.stepPending).toBe('\u25cb'); // ○
|
||||
expect(symbols.stepActive).toBe('\u25cf'); // ●
|
||||
expect(symbols.success).toBe('\u2713'); // ✓
|
||||
expect(symbols.error).toBe('\u2717'); // ✗
|
||||
});
|
||||
|
||||
it('should export color utilities', async () => {
|
||||
const { colors } = await import('../onboarding/theme.js');
|
||||
|
||||
expect(colors).toBeDefined();
|
||||
expect(typeof colors.accent).toBe('function');
|
||||
expect(typeof colors.primary).toBe('function');
|
||||
expect(typeof colors.success).toBe('function');
|
||||
expect(typeof colors.error).toBe('function');
|
||||
});
|
||||
|
||||
it('should format agent with icon', async () => {
|
||||
const { formatAgent, getAgentIcon } = await import('../onboarding/theme.js');
|
||||
|
||||
const formatted = formatAgent('claude-code');
|
||||
expect(formatted).toContain('\u27c1'); // ⟁
|
||||
expect(formatted).toContain('Claude Code');
|
||||
|
||||
const icon = getAgentIcon('cursor');
|
||||
expect(icon).toBe('\u25eb'); // ◫
|
||||
});
|
||||
|
||||
it('should generate progress bars', async () => {
|
||||
const { progressBar } = await import('../onboarding/theme.js');
|
||||
|
||||
const bar50 = progressBar(50, 100, 10);
|
||||
expect(bar50).toContain('\u2588'); // █ (filled)
|
||||
expect(bar50).toContain('\u2591'); // ░ (empty)
|
||||
expect(bar50.length).toBe(10);
|
||||
|
||||
const bar100 = progressBar(100, 100, 6);
|
||||
expect(bar100).toBe('\u2588'.repeat(6));
|
||||
|
||||
const bar0 = progressBar(0, 100, 6);
|
||||
expect(bar0).toBe('\u2591'.repeat(6));
|
||||
});
|
||||
|
||||
it('should format score with visual bar', async () => {
|
||||
const { formatScore } = await import('../onboarding/theme.js');
|
||||
|
||||
const score = formatScore(75);
|
||||
expect(score).toContain('75%');
|
||||
expect(score).toContain('\u2588'); // progress bar
|
||||
});
|
||||
});
|
||||
|
||||
describe('logo', () => {
|
||||
it('should export logo functions', async () => {
|
||||
const { getLogo, getFullLogo, getCompactLogo, getMinimalLogo, getHeader, getDivider } =
|
||||
await import('../onboarding/logo.js');
|
||||
|
||||
expect(typeof getLogo).toBe('function');
|
||||
expect(typeof getFullLogo).toBe('function');
|
||||
expect(typeof getCompactLogo).toBe('function');
|
||||
expect(typeof getMinimalLogo).toBe('function');
|
||||
expect(typeof getHeader).toBe('function');
|
||||
expect(typeof getDivider).toBe('function');
|
||||
});
|
||||
|
||||
it('should generate full logo with version', async () => {
|
||||
const { getFullLogo } = await import('../onboarding/logo.js');
|
||||
|
||||
const logo = getFullLogo('1.7.2', 17);
|
||||
// Full logo uses block characters (███), not literal text
|
||||
expect(logo).toContain('\u2588'); // █ block character
|
||||
expect(logo).toContain('v1.7.2');
|
||||
expect(logo).toContain('17 agents');
|
||||
});
|
||||
|
||||
it('should generate compact logo', async () => {
|
||||
const { getCompactLogo } = await import('../onboarding/logo.js');
|
||||
|
||||
const logo = getCompactLogo('1.7.2');
|
||||
// Compact logo has spaced letters: S K I L L K I T
|
||||
expect(logo).toContain('S K I L L K I T');
|
||||
expect(logo).toContain('v1.7.2');
|
||||
});
|
||||
|
||||
it('should generate minimal logo', async () => {
|
||||
const { getMinimalLogo } = await import('../onboarding/logo.js');
|
||||
|
||||
const logo = getMinimalLogo('1.7.2');
|
||||
expect(logo).toContain('SKILLKIT');
|
||||
expect(logo).toContain('\u25c7'); // ◇ diamond
|
||||
});
|
||||
|
||||
it('should generate header', async () => {
|
||||
const { getHeader } = await import('../onboarding/logo.js');
|
||||
|
||||
const header = getHeader('Test Title');
|
||||
expect(header).toContain('SkillKit');
|
||||
expect(header).toContain('Test Title');
|
||||
});
|
||||
|
||||
it('should generate divider', async () => {
|
||||
const { getDivider } = await import('../onboarding/logo.js');
|
||||
|
||||
const divider = getDivider(20);
|
||||
expect(divider).toContain('\u2500'); // ─
|
||||
});
|
||||
});
|
||||
|
||||
describe('preferences', () => {
|
||||
let testDir: string;
|
||||
let originalHome: string | undefined;
|
||||
let originalUserProfile: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
testDir = mkdtempSync(join(tmpdir(), 'skillkit-prefs-test-'));
|
||||
originalHome = process.env.HOME;
|
||||
originalUserProfile = process.env.USERPROFILE;
|
||||
process.env.HOME = testDir;
|
||||
process.env.USERPROFILE = testDir;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (existsSync(testDir)) {
|
||||
rmSync(testDir, { recursive: true, force: true });
|
||||
}
|
||||
if (originalHome === undefined) {
|
||||
delete process.env.HOME;
|
||||
} else {
|
||||
process.env.HOME = originalHome;
|
||||
}
|
||||
if (originalUserProfile === undefined) {
|
||||
delete process.env.USERPROFILE;
|
||||
} else {
|
||||
process.env.USERPROFILE = originalUserProfile;
|
||||
}
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it('should export preference functions', async () => {
|
||||
const {
|
||||
loadPreferences,
|
||||
savePreferences,
|
||||
isOnboardingComplete,
|
||||
completeOnboarding,
|
||||
saveLastAgents,
|
||||
getLastAgents,
|
||||
saveInstallMethod,
|
||||
getInstallMethod,
|
||||
} = await import('../onboarding/preferences.js');
|
||||
|
||||
expect(typeof loadPreferences).toBe('function');
|
||||
expect(typeof savePreferences).toBe('function');
|
||||
expect(typeof isOnboardingComplete).toBe('function');
|
||||
expect(typeof completeOnboarding).toBe('function');
|
||||
expect(typeof saveLastAgents).toBe('function');
|
||||
expect(typeof getLastAgents).toBe('function');
|
||||
expect(typeof saveInstallMethod).toBe('function');
|
||||
expect(typeof getInstallMethod).toBe('function');
|
||||
});
|
||||
|
||||
it('should return default preferences when file does not exist', async () => {
|
||||
const { loadPreferences } = await import('../onboarding/preferences.js');
|
||||
|
||||
const prefs = loadPreferences();
|
||||
expect(prefs).toBeDefined();
|
||||
expect(prefs.onboardingComplete).toBe(false);
|
||||
expect(prefs.lastSelectedAgents).toEqual([]);
|
||||
expect(prefs.defaultInstallMethod).toBe('symlink');
|
||||
});
|
||||
});
|
||||
|
||||
describe('summary', () => {
|
||||
it('should export summary functions', async () => {
|
||||
const {
|
||||
showInstallSummary,
|
||||
showNextSteps,
|
||||
showAgentSummary,
|
||||
showProjectSummary,
|
||||
showSyncSummary,
|
||||
showSkillList,
|
||||
showMarketplaceInfo,
|
||||
} = await import('../onboarding/summary.js');
|
||||
|
||||
expect(typeof showInstallSummary).toBe('function');
|
||||
expect(typeof showNextSteps).toBe('function');
|
||||
expect(typeof showAgentSummary).toBe('function');
|
||||
expect(typeof showProjectSummary).toBe('function');
|
||||
expect(typeof showSyncSummary).toBe('function');
|
||||
expect(typeof showSkillList).toBe('function');
|
||||
expect(typeof showMarketplaceInfo).toBe('function');
|
||||
});
|
||||
});
|
||||
|
||||
describe('prompts', () => {
|
||||
it('should export prompt functions', async () => {
|
||||
const {
|
||||
isCancel,
|
||||
intro,
|
||||
outro,
|
||||
cancel,
|
||||
note,
|
||||
log,
|
||||
step,
|
||||
success,
|
||||
warn,
|
||||
error,
|
||||
spinner,
|
||||
text,
|
||||
password,
|
||||
confirm,
|
||||
select,
|
||||
agentMultiselect,
|
||||
skillMultiselect,
|
||||
stepTrail,
|
||||
selectInstallMethod,
|
||||
} = await import('../onboarding/prompts.js');
|
||||
|
||||
expect(typeof isCancel).toBe('function');
|
||||
expect(typeof intro).toBe('function');
|
||||
expect(typeof outro).toBe('function');
|
||||
expect(typeof cancel).toBe('function');
|
||||
expect(typeof note).toBe('function');
|
||||
expect(typeof log).toBe('function');
|
||||
expect(typeof step).toBe('function');
|
||||
expect(typeof success).toBe('function');
|
||||
expect(typeof warn).toBe('function');
|
||||
expect(typeof error).toBe('function');
|
||||
expect(typeof spinner).toBe('function');
|
||||
expect(typeof text).toBe('function');
|
||||
expect(typeof password).toBe('function');
|
||||
expect(typeof confirm).toBe('function');
|
||||
expect(typeof select).toBe('function');
|
||||
expect(typeof agentMultiselect).toBe('function');
|
||||
expect(typeof skillMultiselect).toBe('function');
|
||||
expect(typeof stepTrail).toBe('function');
|
||||
expect(typeof selectInstallMethod).toBe('function');
|
||||
});
|
||||
|
||||
it('should generate step trail', async () => {
|
||||
const { stepTrail } = await import('../onboarding/prompts.js');
|
||||
|
||||
const trail = stepTrail([
|
||||
{ label: 'Step 1', status: 'complete' },
|
||||
{ label: 'Step 2', status: 'active' },
|
||||
{ label: 'Step 3', status: 'pending' },
|
||||
]);
|
||||
|
||||
expect(trail).toContain('Step 1');
|
||||
expect(trail).toContain('Step 2');
|
||||
expect(trail).toContain('Step 3');
|
||||
expect(trail).toContain('\u25cf'); // ● (filled circle)
|
||||
expect(trail).toContain('\u25cb'); // ○ (empty circle)
|
||||
});
|
||||
});
|
||||
|
||||
describe('index exports', () => {
|
||||
it('should re-export all modules', async () => {
|
||||
const onboarding = await import('../onboarding/index.js');
|
||||
|
||||
// Theme exports
|
||||
expect(onboarding.AGENT_ICONS).toBeDefined();
|
||||
expect(onboarding.AGENT_NAMES).toBeDefined();
|
||||
expect(onboarding.symbols).toBeDefined();
|
||||
expect(onboarding.colors).toBeDefined();
|
||||
expect(onboarding.formatAgent).toBeDefined();
|
||||
expect(onboarding.getAgentIcon).toBeDefined();
|
||||
expect(onboarding.progressBar).toBeDefined();
|
||||
expect(onboarding.formatScore).toBeDefined();
|
||||
|
||||
// Logo exports
|
||||
expect(onboarding.getLogo).toBeDefined();
|
||||
expect(onboarding.getHeader).toBeDefined();
|
||||
expect(onboarding.getDivider).toBeDefined();
|
||||
|
||||
// Prompts exports
|
||||
expect(onboarding.isCancel).toBeDefined();
|
||||
expect(onboarding.spinner).toBeDefined();
|
||||
expect(onboarding.agentMultiselect).toBeDefined();
|
||||
expect(onboarding.skillMultiselect).toBeDefined();
|
||||
|
||||
// Summary exports
|
||||
expect(onboarding.showInstallSummary).toBeDefined();
|
||||
expect(onboarding.showNextSteps).toBeDefined();
|
||||
|
||||
// Preferences exports
|
||||
expect(onboarding.loadPreferences).toBeDefined();
|
||||
expect(onboarding.savePreferences).toBeDefined();
|
||||
|
||||
// Main functions
|
||||
expect(onboarding.welcome).toBeDefined();
|
||||
expect(onboarding.header).toBeDefined();
|
||||
expect(onboarding.showCompletion).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,13 @@ export { PlanCommand } from './plan.js';
|
||||
export { CommandCmd } from './command.js';
|
||||
export { AICommand } from './ai.js';
|
||||
export { AuditCommand } from './audit.js';
|
||||
export { PublishCommand } from './publish.js';
|
||||
export {
|
||||
AgentCommand,
|
||||
AgentListCommand,
|
||||
AgentShowCommand,
|
||||
AgentCreateCommand,
|
||||
AgentTranslateCommand,
|
||||
AgentSyncCommand,
|
||||
AgentValidateCommand,
|
||||
} from './agent.js';
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
import chalk from 'chalk';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { Command, Option } from 'clipanion';
|
||||
import type { AgentType } from '@skillkit/core';
|
||||
import { detectAgent, getAdapter, getAllAdapters } from '@skillkit/agents';
|
||||
import { initProject } from '../helpers.js';
|
||||
import {
|
||||
welcome,
|
||||
header,
|
||||
colors,
|
||||
symbols,
|
||||
formatAgent,
|
||||
isCancel,
|
||||
spinner,
|
||||
select,
|
||||
confirm,
|
||||
outro,
|
||||
cancel,
|
||||
step,
|
||||
note,
|
||||
showNextSteps,
|
||||
isOnboardingComplete,
|
||||
completeOnboarding,
|
||||
} from '../onboarding/index.js';
|
||||
|
||||
export class InitCommand extends Command {
|
||||
static override paths = [['init']];
|
||||
@@ -24,56 +43,147 @@ export class InitCommand extends Command {
|
||||
description: 'List supported agents',
|
||||
});
|
||||
|
||||
quiet = Option.Boolean('--quiet,-q', false, {
|
||||
description: 'Minimal output (no logo)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const isInteractive = process.stdin.isTTY;
|
||||
|
||||
// List mode
|
||||
if (this.list) {
|
||||
console.log(chalk.cyan('Supported agents:\n'));
|
||||
if (!this.quiet) {
|
||||
header('Supported Agents');
|
||||
}
|
||||
|
||||
const adapters = getAllAdapters();
|
||||
console.log('');
|
||||
|
||||
for (const adapter of adapters) {
|
||||
console.log(` ${chalk.green(adapter.type)}`);
|
||||
console.log(` Name: ${adapter.name}`);
|
||||
console.log(` Skills dir: ${adapter.skillsDir}`);
|
||||
console.log(` Config file: ${adapter.configFile}`);
|
||||
console.log();
|
||||
console.log(` ${formatAgent(adapter.type)}`);
|
||||
console.log(` ${colors.muted('Skills dir:')} ${adapter.skillsDir}`);
|
||||
console.log(` ${colors.muted('Config:')} ${adapter.configFile}`);
|
||||
console.log('');
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
// Show welcome for first-time users
|
||||
const isFirstRun = !isOnboardingComplete();
|
||||
if (isInteractive && isFirstRun && !this.quiet) {
|
||||
welcome();
|
||||
} else if (!this.quiet) {
|
||||
header('Initialize');
|
||||
}
|
||||
|
||||
let agentType: AgentType;
|
||||
const s = spinner();
|
||||
|
||||
if (this.agent) {
|
||||
// Use specified agent
|
||||
agentType = this.agent as AgentType;
|
||||
} else if (isInteractive) {
|
||||
// Auto-detect and let user confirm/change
|
||||
s.start('Detecting agent...');
|
||||
const detected = await detectAgent();
|
||||
s.stop(`Detected: ${formatAgent(detected)}`);
|
||||
|
||||
const allAgents = getAllAdapters().map(a => a.type);
|
||||
|
||||
// Let user confirm or select different agent
|
||||
const agentResult = await select({
|
||||
message: 'Initialize for which agent?',
|
||||
options: allAgents.map(a => ({
|
||||
value: a,
|
||||
label: formatAgent(a),
|
||||
hint: a === detected ? '(detected)' : undefined,
|
||||
})),
|
||||
initialValue: detected,
|
||||
});
|
||||
|
||||
if (isCancel(agentResult)) {
|
||||
cancel('Initialization cancelled');
|
||||
return 0;
|
||||
}
|
||||
|
||||
agentType = agentResult as AgentType;
|
||||
} else {
|
||||
console.log(chalk.dim('Auto-detecting agent...'));
|
||||
// Non-interactive: auto-detect
|
||||
s.start('Detecting agent...');
|
||||
agentType = await detectAgent();
|
||||
s.stop(`Detected: ${formatAgent(agentType)}`);
|
||||
}
|
||||
|
||||
const adapter = getAdapter(agentType);
|
||||
|
||||
console.log(chalk.cyan(`Initializing for ${adapter.name}...`));
|
||||
|
||||
// Initialize project
|
||||
s.start(`Initializing for ${adapter.name}...`);
|
||||
await initProject(agentType);
|
||||
s.stop(`Initialized for ${adapter.name}`);
|
||||
|
||||
console.log();
|
||||
console.log(chalk.green('Initialized successfully!'));
|
||||
console.log();
|
||||
console.log(chalk.dim('Created:'));
|
||||
console.log(chalk.dim(` - ${adapter.skillsDir}/ (skills directory)`));
|
||||
console.log(chalk.dim(` - skillkit.yaml (config file)`));
|
||||
console.log(chalk.dim(` - ${adapter.configFile} (agent config)`));
|
||||
console.log();
|
||||
console.log(chalk.cyan('Next steps:'));
|
||||
console.log(chalk.dim(' 1. Install skills: skillkit install owner/repo'));
|
||||
console.log(chalk.dim(' 2. Sync config: skillkit sync'));
|
||||
console.log(chalk.dim(' 3. Use skills: skillkit read <skill-name>'));
|
||||
// Show what was created
|
||||
note(
|
||||
[
|
||||
`${symbols.success} ${adapter.skillsDir}/ ${colors.muted('(skills directory)')}`,
|
||||
`${symbols.success} skillkit.yaml ${colors.muted('(config file)')}`,
|
||||
`${symbols.success} ${adapter.configFile} ${colors.muted('(agent config)')}`,
|
||||
].join('\n'),
|
||||
'Created'
|
||||
);
|
||||
|
||||
// Mark onboarding complete
|
||||
if (isFirstRun) {
|
||||
completeOnboarding();
|
||||
}
|
||||
|
||||
// Check for SKILL.md to offer publishing
|
||||
await this.checkAndPromptPublish();
|
||||
|
||||
outro('Initialization complete!');
|
||||
|
||||
showNextSteps({
|
||||
skillNames: [],
|
||||
agentTypes: [agentType],
|
||||
});
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Initialization failed'));
|
||||
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
|
||||
} catch (err) {
|
||||
console.log(colors.error('Initialization failed'));
|
||||
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async checkAndPromptPublish(): Promise<void> {
|
||||
if (!process.stdin.isTTY) return;
|
||||
|
||||
const skillMdLocations = [
|
||||
join(process.cwd(), 'SKILL.md'),
|
||||
join(process.cwd(), 'skills', 'SKILL.md'),
|
||||
join(process.cwd(), '.claude', 'skills', 'SKILL.md'),
|
||||
join(process.cwd(), '.cursor', 'skills', 'SKILL.md'),
|
||||
];
|
||||
|
||||
const foundSkillMd = skillMdLocations.find(loc => existsSync(loc));
|
||||
if (!foundSkillMd) return;
|
||||
|
||||
console.log('');
|
||||
step(`Found SKILL.md in your project`);
|
||||
|
||||
const publishResult = await confirm({
|
||||
message: 'Would you like to publish it to the SkillKit marketplace?',
|
||||
initialValue: false,
|
||||
});
|
||||
|
||||
if (isCancel(publishResult) || !publishResult) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log(colors.cyan('To publish your skill, run:'));
|
||||
console.log(` ${colors.bold(`skillkit publish ${foundSkillMd}`)}`);
|
||||
console.log('');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,35 @@
|
||||
import { existsSync, mkdirSync, cpSync, rmSync } from 'node:fs';
|
||||
import { existsSync, mkdirSync, cpSync, rmSync, symlinkSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { detectProvider, isLocalPath, getProvider } from '@skillkit/core';
|
||||
import type { SkillMetadata, GitProvider, AgentType } from '@skillkit/core';
|
||||
import { isPathInside } from '@skillkit/core';
|
||||
import { getAdapter, detectAgent } from '@skillkit/agents';
|
||||
import { getAdapter, detectAgent, getAllAdapters } from '@skillkit/agents';
|
||||
import { getInstallDir, saveSkillMetadata } from '../helpers.js';
|
||||
import {
|
||||
welcome,
|
||||
colors,
|
||||
symbols,
|
||||
formatAgent,
|
||||
getAgentIcon,
|
||||
isCancel,
|
||||
spinner,
|
||||
agentMultiselect,
|
||||
skillMultiselect,
|
||||
selectInstallMethod,
|
||||
confirm,
|
||||
outro,
|
||||
cancel,
|
||||
step,
|
||||
success,
|
||||
error,
|
||||
warn,
|
||||
showInstallSummary,
|
||||
showNextSteps,
|
||||
saveLastAgents,
|
||||
getLastAgents,
|
||||
type InstallResult,
|
||||
} from '../onboarding/index.js';
|
||||
|
||||
export class InstallCommand extends Command {
|
||||
static override paths = [['install'], ['i']];
|
||||
@@ -61,10 +83,20 @@ export class InstallCommand extends Command {
|
||||
description: 'Target specific agents (can specify multiple)',
|
||||
});
|
||||
|
||||
quiet = Option.Boolean('--quiet,-q', false, {
|
||||
description: 'Minimal output (no logo)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const spinner = ora();
|
||||
const isInteractive = process.stdin.isTTY && !this.skills && !this.all && !this.yes;
|
||||
const s = spinner();
|
||||
|
||||
try {
|
||||
// Show welcome logo for interactive mode
|
||||
if (isInteractive && !this.quiet) {
|
||||
welcome();
|
||||
}
|
||||
|
||||
let providerAdapter = detectProvider(this.source);
|
||||
|
||||
if (this.provider) {
|
||||
@@ -72,40 +104,42 @@ export class InstallCommand extends Command {
|
||||
}
|
||||
|
||||
if (!providerAdapter) {
|
||||
console.error(chalk.red(`Could not detect provider for: ${this.source}`));
|
||||
console.error(chalk.dim('Use --provider flag or specify source as:'));
|
||||
console.error(chalk.dim(' GitHub: owner/repo or https://github.com/owner/repo'));
|
||||
console.error(chalk.dim(' GitLab: gitlab:owner/repo or https://gitlab.com/owner/repo'));
|
||||
console.error(chalk.dim(' Bitbucket: bitbucket:owner/repo'));
|
||||
console.error(chalk.dim(' Local: ./path or ~/path'));
|
||||
error(`Could not detect provider for: ${this.source}`);
|
||||
console.log(colors.muted('Use --provider flag or specify source as:'));
|
||||
console.log(colors.muted(' GitHub: owner/repo or https://github.com/owner/repo'));
|
||||
console.log(colors.muted(' GitLab: gitlab:owner/repo or https://gitlab.com/owner/repo'));
|
||||
console.log(colors.muted(' Bitbucket: bitbucket:owner/repo'));
|
||||
console.log(colors.muted(' Local: ./path or ~/path'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
spinner.start(`Fetching from ${providerAdapter.name}...`);
|
||||
s.start(`Fetching from ${providerAdapter.name}...`);
|
||||
|
||||
const result = await providerAdapter.clone(this.source, '', { depth: 1 });
|
||||
|
||||
if (!result.success || !result.path) {
|
||||
spinner.fail(chalk.red(result.error || 'Failed to fetch source'));
|
||||
s.stop(colors.error(result.error || 'Failed to fetch source'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
spinner.succeed(`Found ${result.skills?.length || 0} skill(s)`);
|
||||
s.stop(`Found ${result.skills?.length || 0} skill(s)`);
|
||||
|
||||
const discoveredSkills = result.discoveredSkills || [];
|
||||
|
||||
// List mode - just show skills and exit
|
||||
if (this.list) {
|
||||
if (discoveredSkills.length === 0) {
|
||||
console.log(chalk.yellow('\nNo skills found in this repository'));
|
||||
warn('No skills found in this repository');
|
||||
} else {
|
||||
console.log(chalk.cyan('\nAvailable skills:\n'));
|
||||
console.log('');
|
||||
console.log(colors.bold('Available skills:'));
|
||||
console.log('');
|
||||
for (const skill of discoveredSkills) {
|
||||
console.log(` ${chalk.green(skill.name)}`);
|
||||
console.log(` ${colors.success(symbols.stepActive)} ${colors.primary(skill.name)}`);
|
||||
}
|
||||
console.log();
|
||||
console.log(chalk.dim(`Total: ${discoveredSkills.length} skill(s)`));
|
||||
console.log(chalk.dim('\nTo install specific skills: skillkit install <source> --skills=skill1,skill2'));
|
||||
console.log(chalk.dim('To install all skills: skillkit install <source> --all'));
|
||||
console.log('');
|
||||
console.log(colors.muted(`Total: ${discoveredSkills.length} skill(s)`));
|
||||
console.log(colors.muted('To install: skillkit install <source> --skills=skill1,skill2'));
|
||||
}
|
||||
|
||||
const cleanupPath = result.tempRoot || result.path;
|
||||
@@ -118,83 +152,165 @@ export class InstallCommand extends Command {
|
||||
|
||||
let skillsToInstall = discoveredSkills;
|
||||
|
||||
// Non-interactive: use --skills filter
|
||||
if (this.skills) {
|
||||
const requestedSkills = this.skills.split(',').map(s => s.trim());
|
||||
const available = discoveredSkills.map(s => s.name);
|
||||
const notFound = requestedSkills.filter(s => !available.includes(s));
|
||||
|
||||
if (notFound.length > 0) {
|
||||
console.error(chalk.red(`Skills not found: ${notFound.join(', ')}`));
|
||||
console.error(chalk.dim(`Available: ${available.join(', ')}`));
|
||||
error(`Skills not found: ${notFound.join(', ')}`);
|
||||
console.log(colors.muted(`Available: ${available.join(', ')}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
skillsToInstall = discoveredSkills.filter(s => requestedSkills.includes(s.name));
|
||||
} else if (this.all || this.yes) {
|
||||
skillsToInstall = discoveredSkills;
|
||||
} else {
|
||||
skillsToInstall = discoveredSkills;
|
||||
} else if (isInteractive && discoveredSkills.length > 1) {
|
||||
// Interactive skill selection
|
||||
step(`Source: ${colors.cyan(this.source)}`);
|
||||
|
||||
if (skillsToInstall.length > 0) {
|
||||
console.log(chalk.cyan('\nSkills to install:'));
|
||||
skillsToInstall.forEach(s => console.log(chalk.dim(` - ${s.name}`)));
|
||||
console.log();
|
||||
const skillResult = await skillMultiselect({
|
||||
message: 'Select skills to install',
|
||||
skills: discoveredSkills.map(s => ({ name: s.name })),
|
||||
initialValues: discoveredSkills.map(s => s.name),
|
||||
});
|
||||
|
||||
if (isCancel(skillResult)) {
|
||||
cancel('Installation cancelled');
|
||||
return 0;
|
||||
}
|
||||
|
||||
skillsToInstall = discoveredSkills.filter(s => (skillResult as string[]).includes(s.name));
|
||||
}
|
||||
|
||||
if (skillsToInstall.length === 0) {
|
||||
console.log(chalk.yellow('No skills to install'));
|
||||
warn('No skills to install');
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Determine target agents
|
||||
let targetAgents: AgentType[];
|
||||
|
||||
if (this.agent && this.agent.length > 0) {
|
||||
// Explicitly specified agents
|
||||
targetAgents = this.agent as AgentType[];
|
||||
} else if (isInteractive) {
|
||||
// Interactive agent selection
|
||||
const allAgentTypes = getAllAdapters().map(a => a.type);
|
||||
const detectedAgent = await detectAgent();
|
||||
|
||||
// Get last selected agents or use detected
|
||||
const lastAgents = getLastAgents();
|
||||
const initialAgents = lastAgents.length > 0
|
||||
? lastAgents.filter(a => allAgentTypes.includes(a as AgentType))
|
||||
: [detectedAgent];
|
||||
|
||||
const agentResult = await agentMultiselect({
|
||||
message: 'Install to which agents?',
|
||||
agents: allAgentTypes,
|
||||
initialValues: initialAgents,
|
||||
});
|
||||
|
||||
if (isCancel(agentResult)) {
|
||||
cancel('Installation cancelled');
|
||||
return 0;
|
||||
}
|
||||
|
||||
targetAgents = agentResult as AgentType[];
|
||||
|
||||
// Save selection for next time
|
||||
saveLastAgents(targetAgents);
|
||||
} else {
|
||||
// Non-interactive: use detected agent
|
||||
const detectedAgent = await detectAgent();
|
||||
targetAgents = [detectedAgent];
|
||||
}
|
||||
|
||||
// Interactive: select installation method
|
||||
let installMethod: 'symlink' | 'copy' = 'copy';
|
||||
|
||||
if (isInteractive && targetAgents.length > 1) {
|
||||
const methodResult = await selectInstallMethod({});
|
||||
|
||||
if (isCancel(methodResult)) {
|
||||
cancel('Installation cancelled');
|
||||
return 0;
|
||||
}
|
||||
|
||||
installMethod = methodResult as 'symlink' | 'copy';
|
||||
}
|
||||
|
||||
// Confirm installation
|
||||
if (isInteractive && !this.yes) {
|
||||
console.log('');
|
||||
const agentDisplay = targetAgents.length <= 3
|
||||
? targetAgents.map(formatAgent).join(', ')
|
||||
: `${targetAgents.slice(0, 2).map(formatAgent).join(', ')} +${targetAgents.length - 2} more`;
|
||||
|
||||
const confirmResult = await confirm({
|
||||
message: `Install ${skillsToInstall.length} skill(s) to ${agentDisplay}?`,
|
||||
initialValue: true,
|
||||
});
|
||||
|
||||
if (isCancel(confirmResult) || !confirmResult) {
|
||||
cancel('Installation cancelled');
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Perform installation
|
||||
let totalInstalled = 0;
|
||||
const installResults: { agent: string; dir: string; count: number }[] = [];
|
||||
const installResults: InstallResult[] = [];
|
||||
|
||||
for (const agentType of targetAgents) {
|
||||
const adapter = getAdapter(agentType);
|
||||
const installDir = getInstallDir(this.global, agentType);
|
||||
for (const skill of skillsToInstall) {
|
||||
const skillName = skill.name;
|
||||
const sourcePath = skill.path;
|
||||
const installedAgents: string[] = [];
|
||||
let primaryPath: string | null = null;
|
||||
|
||||
if (!existsSync(installDir)) {
|
||||
mkdirSync(installDir, { recursive: true });
|
||||
}
|
||||
for (const agentType of targetAgents) {
|
||||
const adapter = getAdapter(agentType);
|
||||
const installDir = getInstallDir(this.global, agentType);
|
||||
|
||||
if (targetAgents.length > 1) {
|
||||
console.log(chalk.cyan(`\nInstalling to ${adapter.name}...`));
|
||||
}
|
||||
if (!existsSync(installDir)) {
|
||||
mkdirSync(installDir, { recursive: true });
|
||||
}
|
||||
|
||||
let installed = 0;
|
||||
for (const skill of skillsToInstall) {
|
||||
const skillName = skill.name;
|
||||
const sourcePath = skill.path;
|
||||
const targetPath = join(installDir, skillName);
|
||||
|
||||
if (existsSync(targetPath) && !this.force) {
|
||||
console.log(chalk.yellow(` Skipping ${skillName} (already exists, use --force to overwrite)`));
|
||||
if (!this.quiet) {
|
||||
warn(`Skipping ${skillName} for ${adapter.name} (already exists, use --force)`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const securityRoot = result.tempRoot || result.path;
|
||||
if (!isPathInside(sourcePath, securityRoot)) {
|
||||
console.log(chalk.red(` Skipping ${skillName} (path traversal detected)`));
|
||||
error(`Skipping ${skillName} (path traversal detected)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
spinner.start(`Installing ${skillName}...`);
|
||||
const isSymlinkMode = installMethod === 'symlink' && targetAgents.length > 1;
|
||||
const useSymlink = isSymlinkMode && primaryPath !== null;
|
||||
|
||||
s.start(`Installing ${skillName} to ${adapter.name}${useSymlink ? ' (symlink)' : ''}...`);
|
||||
|
||||
try {
|
||||
if (existsSync(targetPath)) {
|
||||
rmSync(targetPath, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
cpSync(sourcePath, targetPath, { recursive: true, dereference: true });
|
||||
if (useSymlink && primaryPath) {
|
||||
symlinkSync(primaryPath, targetPath, 'dir');
|
||||
} else {
|
||||
cpSync(sourcePath, targetPath, { recursive: true, dereference: true });
|
||||
if (isSymlinkMode && primaryPath === null) {
|
||||
primaryPath = targetPath;
|
||||
}
|
||||
}
|
||||
|
||||
const metadata: SkillMetadata = {
|
||||
name: skillName,
|
||||
@@ -207,41 +323,66 @@ export class InstallCommand extends Command {
|
||||
};
|
||||
saveSkillMetadata(targetPath, metadata);
|
||||
|
||||
spinner.succeed(chalk.green(`Installed ${skillName}`));
|
||||
installed++;
|
||||
} catch (error) {
|
||||
spinner.fail(chalk.red(`Failed to install ${skillName}`));
|
||||
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
|
||||
installedAgents.push(agentType);
|
||||
s.stop(`Installed ${skillName} to ${adapter.name}${useSymlink ? ' (symlink)' : ''}`);
|
||||
} catch (err) {
|
||||
s.stop(colors.error(`Failed to install ${skillName} to ${adapter.name}`));
|
||||
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
|
||||
}
|
||||
}
|
||||
|
||||
totalInstalled += installed;
|
||||
installResults.push({ agent: adapter.name, dir: installDir, count: installed });
|
||||
if (installedAgents.length > 0) {
|
||||
totalInstalled++;
|
||||
installResults.push({
|
||||
skillName,
|
||||
method: installMethod,
|
||||
agents: installedAgents,
|
||||
path: join(getInstallDir(this.global, installedAgents[0] as AgentType), skillName),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup temp directory
|
||||
const cleanupPath = result.tempRoot || result.path;
|
||||
if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) {
|
||||
rmSync(cleanupPath, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
console.log();
|
||||
if (targetAgents.length > 1) {
|
||||
console.log(chalk.green(`Installed ${totalInstalled} skill(s) across ${targetAgents.length} agents:`));
|
||||
for (const r of installResults) {
|
||||
console.log(chalk.dim(` - ${r.agent}: ${r.count} skill(s) to ${r.dir}`));
|
||||
// Show summary
|
||||
if (totalInstalled > 0) {
|
||||
if (isInteractive) {
|
||||
showInstallSummary({
|
||||
totalSkills: totalInstalled,
|
||||
totalAgents: targetAgents.length,
|
||||
results: installResults,
|
||||
source: this.source,
|
||||
});
|
||||
|
||||
outro('Installation complete!');
|
||||
|
||||
if (!this.yes) {
|
||||
showNextSteps({
|
||||
skillNames: installResults.map(r => r.skillName),
|
||||
agentTypes: targetAgents,
|
||||
syncNeeded: true,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
success(`Installed ${totalInstalled} skill(s) to ${targetAgents.length} agent(s)`);
|
||||
for (const r of installResults) {
|
||||
console.log(colors.muted(` ${symbols.success} ${r.skillName} ${symbols.arrowRight} ${r.agents.map(getAgentIcon).join(' ')}`));
|
||||
}
|
||||
console.log('');
|
||||
console.log(colors.muted('Run `skillkit sync` to update agent configs'));
|
||||
}
|
||||
} else {
|
||||
console.log(chalk.green(`Installed ${totalInstalled} skill(s) to ${installResults[0]?.dir}`));
|
||||
}
|
||||
|
||||
if (!this.yes) {
|
||||
console.log(chalk.dim('\nRun `skillkit sync` to update your agent config'));
|
||||
warn('No skills were installed');
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail(chalk.red('Installation failed'));
|
||||
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
|
||||
} catch (err) {
|
||||
s.stop(colors.error('Installation failed'));
|
||||
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
createMarketplaceAggregator,
|
||||
type MarketplaceSearchOptions,
|
||||
} from '@skillkit/core';
|
||||
import {
|
||||
header,
|
||||
colors,
|
||||
spinner,
|
||||
warn,
|
||||
showMarketplaceInfo,
|
||||
showSkillList,
|
||||
progressBar,
|
||||
} from '../onboarding/index.js';
|
||||
|
||||
/**
|
||||
* Marketplace command - browse and install skills from the marketplace
|
||||
*/
|
||||
export class MarketplaceCommand extends Command {
|
||||
static override paths = [['marketplace'], ['market'], ['mp']];
|
||||
|
||||
@@ -51,6 +55,10 @@ export class MarketplaceCommand extends Command {
|
||||
description: 'Output as JSON',
|
||||
});
|
||||
|
||||
quiet = Option.Boolean('--quiet,-q', false, {
|
||||
description: 'Minimal output',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const marketplace = createMarketplaceAggregator();
|
||||
|
||||
@@ -73,11 +81,16 @@ export class MarketplaceCommand extends Command {
|
||||
}
|
||||
|
||||
private async browseMarketplace(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
const spinner = ora('Loading marketplace...').start();
|
||||
if (!this.quiet && !this.json) {
|
||||
header('Skill Marketplace');
|
||||
}
|
||||
|
||||
const s = spinner();
|
||||
s.start('Loading marketplace...');
|
||||
|
||||
try {
|
||||
const index = await marketplace.getIndex();
|
||||
spinner.stop();
|
||||
s.stop('Marketplace loaded');
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify({
|
||||
@@ -88,31 +101,31 @@ export class MarketplaceCommand extends Command {
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold('Skill Marketplace\n'));
|
||||
console.log(`Total skills: ${chalk.cyan(index.totalCount)}`);
|
||||
console.log(`Sources: ${chalk.cyan(index.sources.length)}`);
|
||||
console.log(`Last updated: ${chalk.dim(new Date(index.updatedAt).toLocaleString())}\n`);
|
||||
// Show marketplace info
|
||||
showMarketplaceInfo({
|
||||
totalSkills: index.totalCount,
|
||||
sourceCount: index.sources.length,
|
||||
lastUpdated: index.updatedAt,
|
||||
});
|
||||
|
||||
// Show featured skills
|
||||
console.log(colors.bold('Featured Skills:'));
|
||||
console.log('');
|
||||
|
||||
// Show sample skills
|
||||
console.log(chalk.bold('Featured Skills:\n'));
|
||||
const featured = index.skills.slice(0, 10);
|
||||
showSkillList(featured.map(skill => ({
|
||||
name: skill.name,
|
||||
description: skill.description,
|
||||
source: skill.source.name,
|
||||
})));
|
||||
|
||||
for (const skill of featured) {
|
||||
console.log(` ${chalk.cyan(skill.name)}`);
|
||||
if (skill.description) {
|
||||
console.log(` ${chalk.dim(skill.description.slice(0, 60))}${skill.description.length > 60 ? '...' : ''}`);
|
||||
}
|
||||
console.log(` ${chalk.dim(`Source: ${skill.source.name}`)}`);
|
||||
console.log();
|
||||
}
|
||||
|
||||
console.log(chalk.dim('Use "skillkit marketplace search <query>" to search for skills.'));
|
||||
console.log(chalk.dim('Use "skillkit marketplace tags" to see popular tags.'));
|
||||
console.log(colors.muted('Use "skillkit marketplace search <query>" to search for skills.'));
|
||||
console.log(colors.muted('Use "skillkit marketplace tags" to see popular tags.'));
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Failed to load marketplace');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
} catch (err) {
|
||||
s.stop(colors.error('Failed to load marketplace'));
|
||||
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -120,12 +133,16 @@ export class MarketplaceCommand extends Command {
|
||||
private async searchSkills(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
const query = this.query || this.action;
|
||||
|
||||
if (!this.quiet && !this.json) {
|
||||
header('Search Skills');
|
||||
}
|
||||
|
||||
// Validate and parse limit
|
||||
let limit = 20;
|
||||
if (this.limit) {
|
||||
const parsed = parseInt(this.limit, 10);
|
||||
if (isNaN(parsed) || parsed <= 0) {
|
||||
console.error(chalk.red('Invalid --limit value. Must be a positive number.'));
|
||||
console.log(colors.error('Invalid --limit value. Must be a positive number.'));
|
||||
return 1;
|
||||
}
|
||||
limit = parsed;
|
||||
@@ -137,7 +154,8 @@ export class MarketplaceCommand extends Command {
|
||||
.map((t) => t.trim())
|
||||
.filter((t) => t.length > 0);
|
||||
|
||||
const spinner = ora(`Searching for "${query}"...`).start();
|
||||
const s = spinner();
|
||||
s.start(`Searching for "${query}"...`);
|
||||
|
||||
try {
|
||||
const options: MarketplaceSearchOptions = {
|
||||
@@ -148,7 +166,7 @@ export class MarketplaceCommand extends Command {
|
||||
};
|
||||
|
||||
const result = await marketplace.search(options);
|
||||
spinner.stop();
|
||||
s.stop(`Found ${result.total} skill(s)`);
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(result));
|
||||
@@ -156,77 +174,94 @@ export class MarketplaceCommand extends Command {
|
||||
}
|
||||
|
||||
if (result.skills.length === 0) {
|
||||
console.log(chalk.yellow(`No skills found${query ? ` matching "${query}"` : ''}.`));
|
||||
warn(`No skills found${query ? ` matching "${query}"` : ''}.`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold(`Found ${result.total} skill(s):\n`));
|
||||
console.log('');
|
||||
console.log(colors.bold(`Found ${result.total} skill(s):`));
|
||||
console.log('');
|
||||
|
||||
for (const skill of result.skills) {
|
||||
console.log(`${chalk.cyan(skill.name)} ${chalk.dim(`(${skill.source.name})`)}`);
|
||||
if (skill.description) {
|
||||
console.log(` ${skill.description}`);
|
||||
}
|
||||
if (skill.tags.length > 0) {
|
||||
console.log(` Tags: ${chalk.dim(skill.tags.join(', '))}`);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
showSkillList(result.skills.map(skill => ({
|
||||
name: skill.name,
|
||||
description: skill.description,
|
||||
source: skill.source.name,
|
||||
})));
|
||||
|
||||
if (result.total > result.skills.length) {
|
||||
console.log(chalk.dim(`Showing ${result.skills.length} of ${result.total} results. Use --limit to see more.`));
|
||||
console.log(colors.muted(`Showing ${result.skills.length} of ${result.total} results. Use --limit to see more.`));
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Search failed');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
} catch (err) {
|
||||
s.stop(colors.error('Search failed'));
|
||||
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshIndex(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
const spinner = ora('Refreshing marketplace index...').start();
|
||||
if (!this.quiet) {
|
||||
header('Refresh Marketplace');
|
||||
}
|
||||
|
||||
const s = spinner();
|
||||
s.start('Refreshing marketplace index...');
|
||||
|
||||
try {
|
||||
const index = await marketplace.refresh();
|
||||
spinner.succeed(`Marketplace refreshed: ${index.totalCount} skills from ${index.sources.length} sources`);
|
||||
s.stop(`Refreshed: ${index.totalCount} skills from ${index.sources.length} sources`);
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Refresh failed');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
} catch (err) {
|
||||
s.stop(colors.error('Refresh failed'));
|
||||
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async showTags(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
const spinner = ora('Loading tags...').start();
|
||||
if (!this.quiet && !this.json) {
|
||||
header('Popular Tags');
|
||||
}
|
||||
|
||||
const s = spinner();
|
||||
s.start('Loading tags...');
|
||||
|
||||
try {
|
||||
const tags = await marketplace.getPopularTags(30);
|
||||
spinner.stop();
|
||||
s.stop('Tags loaded');
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(tags));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold('Popular Tags:\n'));
|
||||
console.log('');
|
||||
console.log(colors.bold('Popular Tags:'));
|
||||
console.log('');
|
||||
|
||||
const maxCount = Math.max(...tags.map(t => t.count));
|
||||
|
||||
for (const { tag, count } of tags) {
|
||||
const bar = '█'.repeat(Math.min(count, 20));
|
||||
console.log(` ${tag.padEnd(15)} ${chalk.cyan(bar)} ${count}`);
|
||||
const bar = progressBar(count, maxCount, 20);
|
||||
console.log(` ${tag.padEnd(15)} ${colors.dim(bar)} ${colors.muted(String(count))}`);
|
||||
}
|
||||
|
||||
console.log('');
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Failed to load tags');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
} catch (err) {
|
||||
s.stop(colors.error('Failed to load tags'));
|
||||
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async showSources(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
|
||||
if (!this.quiet && !this.json) {
|
||||
header('Skill Sources');
|
||||
}
|
||||
|
||||
const sources = marketplace.getSources();
|
||||
|
||||
if (this.json) {
|
||||
@@ -234,15 +269,18 @@ export class MarketplaceCommand extends Command {
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.bold('Skill Sources:\n'));
|
||||
console.log('');
|
||||
console.log(colors.bold('Skill Sources:'));
|
||||
console.log('');
|
||||
|
||||
for (const source of sources) {
|
||||
console.log(`${chalk.cyan(source.name)} ${source.official ? chalk.green('(official)') : ''}`);
|
||||
console.log(` ${chalk.dim(`${source.owner}/${source.repo}`)}`);
|
||||
const officialBadge = source.official ? colors.success(' (official)') : '';
|
||||
console.log(`${colors.cyan(source.name)}${officialBadge}`);
|
||||
console.log(` ${colors.muted(`${source.owner}/${source.repo}`)}`);
|
||||
if (source.description) {
|
||||
console.log(` ${source.description}`);
|
||||
}
|
||||
console.log();
|
||||
console.log('');
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join, basename, dirname } from 'node:path';
|
||||
import { execSync } from 'node:child_process';
|
||||
import chalk from 'chalk';
|
||||
import { Command, Option } from 'clipanion';
|
||||
|
||||
interface SkillFrontmatter {
|
||||
name?: string;
|
||||
description?: string;
|
||||
tags?: string[];
|
||||
version?: string;
|
||||
}
|
||||
|
||||
export class PublishCommand extends Command {
|
||||
static override paths = [['publish']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Publish your skill to the SkillKit marketplace',
|
||||
examples: [
|
||||
['Publish skill from current directory', '$0 publish'],
|
||||
['Publish skill from specific path', '$0 publish ./my-skill'],
|
||||
['Publish with custom name', '$0 publish --name my-awesome-skill'],
|
||||
],
|
||||
});
|
||||
|
||||
skillPath = Option.String({ required: false, name: 'path' });
|
||||
|
||||
name = Option.String('--name,-n', {
|
||||
description: 'Custom skill name (default: parsed from SKILL.md)',
|
||||
});
|
||||
|
||||
dryRun = Option.Boolean('--dry-run', false, {
|
||||
description: 'Show what would be published without actually publishing',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const skillPath = this.skillPath || process.cwd();
|
||||
const skillMdPath = this.findSkillMd(skillPath);
|
||||
|
||||
if (!skillMdPath) {
|
||||
console.error(chalk.red('No SKILL.md found'));
|
||||
console.error(chalk.dim('Run this command from a directory containing SKILL.md'));
|
||||
console.error(chalk.dim('Or specify the path: skillkit publish ./path/to/skill'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan('Publishing skill to SkillKit marketplace...\n'));
|
||||
|
||||
// Parse SKILL.md
|
||||
const content = readFileSync(skillMdPath, 'utf-8');
|
||||
const frontmatter = this.parseFrontmatter(content);
|
||||
const skillName = this.name || frontmatter.name || basename(dirname(skillMdPath));
|
||||
|
||||
// Get git repo info
|
||||
const repoInfo = this.getRepoInfo(dirname(skillMdPath));
|
||||
if (!repoInfo) {
|
||||
console.error(chalk.red('Not a git repository or no remote configured'));
|
||||
console.error(chalk.dim('Your skill must be in a git repository with a GitHub remote'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Build skill entry
|
||||
const skillSlug = this.slugify(skillName);
|
||||
if (!skillSlug) {
|
||||
console.error(chalk.red('Skill name produces an empty slug.'));
|
||||
console.error(chalk.dim('Please pass --name with letters or numbers.'));
|
||||
return 1;
|
||||
}
|
||||
const skillEntry = {
|
||||
id: `${repoInfo.owner}/${repoInfo.repo}/${skillSlug}`,
|
||||
name: this.formatName(skillName),
|
||||
description: frontmatter.description || `Best practices and patterns for ${this.formatName(skillName)}`,
|
||||
source: `${repoInfo.owner}/${repoInfo.repo}`,
|
||||
tags: frontmatter.tags || this.inferTags(skillName, frontmatter.description || ''),
|
||||
};
|
||||
|
||||
console.log(chalk.white('Skill details:'));
|
||||
console.log(chalk.dim(` ID: ${skillEntry.id}`));
|
||||
console.log(chalk.dim(` Name: ${skillEntry.name}`));
|
||||
console.log(chalk.dim(` Description: ${skillEntry.description}`));
|
||||
console.log(chalk.dim(` Source: ${skillEntry.source}`));
|
||||
console.log(chalk.dim(` Tags: ${skillEntry.tags.join(', ')}`));
|
||||
console.log();
|
||||
|
||||
if (this.dryRun) {
|
||||
console.log(chalk.yellow('Dry run - not publishing'));
|
||||
console.log(chalk.dim('JSON entry that would be added:'));
|
||||
console.log(JSON.stringify(skillEntry, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Create GitHub issue to add skill
|
||||
const issueBody = this.createIssueBody(skillEntry);
|
||||
const issueTitle = encodeURIComponent(`[Publish] ${skillEntry.name}`);
|
||||
const issueBodyEncoded = encodeURIComponent(issueBody);
|
||||
const issueUrl = `https://github.com/rohitg00/skillkit/issues/new?title=${issueTitle}&body=${issueBodyEncoded}&labels=skill-submission,publish`;
|
||||
|
||||
console.log(chalk.green('Opening GitHub to submit your skill...\n'));
|
||||
|
||||
try {
|
||||
// Try to open the URL
|
||||
const openCmd =
|
||||
process.platform === 'darwin'
|
||||
? `open "${issueUrl}"`
|
||||
: process.platform === 'win32'
|
||||
? `cmd /c start "" "${issueUrl}"`
|
||||
: `xdg-open "${issueUrl}"`;
|
||||
execSync(openCmd, { stdio: 'ignore' });
|
||||
|
||||
console.log(chalk.green('GitHub issue page opened!'));
|
||||
console.log(chalk.dim('Review and submit the issue to publish your skill.'));
|
||||
} catch {
|
||||
console.log(chalk.yellow('Could not open browser automatically.'));
|
||||
console.log(chalk.dim('Please open this URL manually:\n'));
|
||||
console.log(chalk.cyan(issueUrl));
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log(chalk.cyan('Next steps:'));
|
||||
console.log(chalk.dim(' 1. Review the skill details in the GitHub issue'));
|
||||
console.log(chalk.dim(' 2. Submit the issue'));
|
||||
console.log(chalk.dim(' 3. A maintainer will review and add your skill'));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private findSkillMd(basePath: string): string | null {
|
||||
// Check if path is directly to SKILL.md
|
||||
if (basePath.endsWith('SKILL.md') && existsSync(basePath)) {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
// Check if SKILL.md exists in the directory
|
||||
const direct = join(basePath, 'SKILL.md');
|
||||
if (existsSync(direct)) {
|
||||
return direct;
|
||||
}
|
||||
|
||||
// Check common skill locations
|
||||
const locations = [
|
||||
join(basePath, 'skills', 'SKILL.md'),
|
||||
join(basePath, '.claude', 'skills', 'SKILL.md'),
|
||||
join(basePath, '.cursor', 'skills', 'SKILL.md'),
|
||||
];
|
||||
|
||||
for (const loc of locations) {
|
||||
if (existsSync(loc)) {
|
||||
return loc;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private parseFrontmatter(content: string): SkillFrontmatter {
|
||||
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
||||
if (!match) return {};
|
||||
|
||||
const frontmatter: SkillFrontmatter = {};
|
||||
const lines = match[1].split(/\r?\n/);
|
||||
let inTagsList = false;
|
||||
|
||||
for (const line of lines) {
|
||||
// Handle multiline tags list
|
||||
if (inTagsList) {
|
||||
const tagMatch = line.match(/^\s*-\s*(.+)$/);
|
||||
if (tagMatch) {
|
||||
frontmatter.tags ??= [];
|
||||
frontmatter.tags.push(tagMatch[1].trim().replace(/^["']|["']$/g, ''));
|
||||
continue;
|
||||
}
|
||||
if (line.trim() === '') continue;
|
||||
inTagsList = false;
|
||||
}
|
||||
|
||||
const colonIdx = line.indexOf(':');
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
const key = line.slice(0, colonIdx).trim();
|
||||
const value = line.slice(colonIdx + 1).trim();
|
||||
|
||||
switch (key) {
|
||||
case 'name':
|
||||
frontmatter.name = value.replace(/^["']|["']$/g, '');
|
||||
break;
|
||||
case 'description':
|
||||
frontmatter.description = value.replace(/^["']|["']$/g, '');
|
||||
break;
|
||||
case 'version':
|
||||
frontmatter.version = value.replace(/^["']|["']$/g, '');
|
||||
break;
|
||||
case 'tags':
|
||||
// Parse YAML array: [tag1, tag2] or multiline list
|
||||
if (value.startsWith('[')) {
|
||||
frontmatter.tags = value
|
||||
.slice(1, -1)
|
||||
.split(',')
|
||||
.map(t => t.trim().replace(/^["']|["']$/g, ''))
|
||||
.filter(t => t.length > 0);
|
||||
} else if (value === '') {
|
||||
inTagsList = true;
|
||||
frontmatter.tags = [];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return frontmatter;
|
||||
}
|
||||
|
||||
private slugify(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
}
|
||||
|
||||
private getRepoInfo(dir: string): { owner: string; repo: string } | null {
|
||||
try {
|
||||
const remote = execSync('git remote get-url origin', {
|
||||
cwd: dir,
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'ignore'],
|
||||
}).trim();
|
||||
|
||||
// Parse GitHub URL: git@github.com:owner/repo.git or https://github.com/owner/repo.git
|
||||
const match = remote.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?$/);
|
||||
if (match) {
|
||||
return { owner: match[1], repo: match[2] };
|
||||
}
|
||||
} catch {
|
||||
// Not a git repo or no remote
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private formatName(name: string): string {
|
||||
return name
|
||||
.split(/[-_]/)
|
||||
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
private inferTags(name: string, description: string): string[] {
|
||||
const tags: string[] = [];
|
||||
const text = `${name} ${description}`.toLowerCase();
|
||||
|
||||
const tagMap: Record<string, string[]> = {
|
||||
react: ['react', 'jsx', 'tsx'],
|
||||
typescript: ['typescript', 'ts'],
|
||||
nextjs: ['next', 'nextjs'],
|
||||
testing: ['test', 'jest', 'vitest'],
|
||||
mobile: ['mobile', 'react-native', 'expo'],
|
||||
backend: ['backend', 'api', 'server'],
|
||||
database: ['database', 'postgres', 'mysql', 'supabase'],
|
||||
frontend: ['frontend', 'ui', 'design'],
|
||||
devops: ['devops', 'ci', 'cd', 'docker'],
|
||||
};
|
||||
|
||||
for (const [tag, keywords] of Object.entries(tagMap)) {
|
||||
if (keywords.some(k => text.includes(k))) {
|
||||
tags.push(tag);
|
||||
}
|
||||
}
|
||||
|
||||
return tags.length > 0 ? tags : ['general'];
|
||||
}
|
||||
|
||||
private createIssueBody(
|
||||
skill: { id: string; name: string; description: string; source: string; tags: string[] }
|
||||
): string {
|
||||
return `## Publish Skill Request
|
||||
|
||||
### Skill Details
|
||||
- **ID:** \`${skill.id}\`
|
||||
- **Name:** ${skill.name}
|
||||
- **Description:** ${skill.description}
|
||||
- **Source:** [${skill.source}](https://github.com/${skill.source})
|
||||
- **Tags:** ${skill.tags.map(t => `\`${t}\``).join(', ')}
|
||||
|
||||
### JSON Entry
|
||||
\`\`\`json
|
||||
${JSON.stringify(skill, null, 2)}
|
||||
\`\`\`
|
||||
|
||||
### Checklist
|
||||
- [ ] SKILL.md follows the standard format
|
||||
- [ ] Skill is publicly accessible on GitHub
|
||||
- [ ] Description accurately describes the skill
|
||||
- [ ] Tags are appropriate
|
||||
|
||||
---
|
||||
Submitted via \`skillkit publish\``;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
type ProjectProfile,
|
||||
type ScoredSkill,
|
||||
@@ -14,10 +12,16 @@ import {
|
||||
INDEX_PATH,
|
||||
KNOWN_SKILL_REPOS,
|
||||
} from '@skillkit/core';
|
||||
import {
|
||||
header,
|
||||
colors,
|
||||
symbols,
|
||||
spinner,
|
||||
warn,
|
||||
showProjectSummary,
|
||||
progressBar,
|
||||
} from '../onboarding/index.js';
|
||||
|
||||
/**
|
||||
* Recommend command - get smart skill recommendations based on project analysis
|
||||
*/
|
||||
export class RecommendCommand extends Command {
|
||||
static override paths = [['recommend'], ['rec']];
|
||||
|
||||
@@ -97,6 +101,11 @@ export class RecommendCommand extends Command {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
// Quiet mode
|
||||
quiet = Option.Boolean('--quiet,-q', false, {
|
||||
description: 'Minimal output',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
|
||||
@@ -105,19 +114,23 @@ export class RecommendCommand extends Command {
|
||||
return await this.updateIndex();
|
||||
}
|
||||
|
||||
if (!this.quiet && !this.json) {
|
||||
header('Skill Recommendations');
|
||||
}
|
||||
|
||||
// Load or create project profile
|
||||
const profile = await this.getProjectProfile(targetPath);
|
||||
if (!profile) {
|
||||
console.error(chalk.red('Failed to analyze project'));
|
||||
console.log(colors.error('Failed to analyze project'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Load skill index
|
||||
const index = this.loadIndex();
|
||||
if (!index || index.skills.length === 0) {
|
||||
console.log(chalk.yellow('No skill index found.'));
|
||||
console.log(chalk.dim('Run "skillkit recommend --update" to fetch skills from known sources.'));
|
||||
console.log(chalk.dim('Or install skills manually with "skillkit install <source>"\n'));
|
||||
warn('No skill index found.');
|
||||
console.log(colors.muted('Run "skillkit recommend --update" to fetch skills from known sources.'));
|
||||
console.log(colors.muted('Or install skills manually with "skillkit install <source>"\n'));
|
||||
|
||||
// Still show project profile
|
||||
this.showProjectProfile(profile);
|
||||
@@ -153,19 +166,20 @@ export class RecommendCommand extends Command {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get project profile from context or by analyzing project
|
||||
*/
|
||||
private async getProjectProfile(projectPath: string): Promise<ProjectProfile | null> {
|
||||
const manager = new ContextManager(projectPath);
|
||||
let context = manager.get();
|
||||
|
||||
if (!context) {
|
||||
// Auto-analyze project
|
||||
if (!this.json) {
|
||||
console.log(chalk.dim('Analyzing project...\n'));
|
||||
if (!this.json && !this.quiet) {
|
||||
const s = spinner();
|
||||
s.start('Analyzing project...');
|
||||
context = manager.init();
|
||||
s.stop('Project analyzed');
|
||||
} else {
|
||||
context = manager.init();
|
||||
}
|
||||
context = manager.init();
|
||||
}
|
||||
|
||||
if (!context) {
|
||||
@@ -183,33 +197,18 @@ export class RecommendCommand extends Command {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Show project profile summary
|
||||
*/
|
||||
private showProjectProfile(profile: ProjectProfile): void {
|
||||
console.log(chalk.cyan('Project Profile:'));
|
||||
console.log(` Name: ${chalk.bold(profile.name)}`);
|
||||
if (profile.type) {
|
||||
console.log(` Type: ${profile.type}`);
|
||||
}
|
||||
const languages = profile.stack.languages.map(l => `${l.name}${l.version ? ` ${l.version}` : ''}`);
|
||||
const frameworks = profile.stack.frameworks.map(f => `${f.name}${f.version ? ` ${f.version}` : ''}`);
|
||||
|
||||
const stackItems: string[] = [];
|
||||
for (const lang of profile.stack.languages) {
|
||||
stackItems.push(`${lang.name}${lang.version ? ` ${lang.version}` : ''}`);
|
||||
}
|
||||
for (const fw of profile.stack.frameworks) {
|
||||
stackItems.push(`${fw.name}${fw.version ? ` ${fw.version}` : ''}`);
|
||||
}
|
||||
|
||||
if (stackItems.length > 0) {
|
||||
console.log(` Stack: ${chalk.dim(stackItems.join(', '))}`);
|
||||
}
|
||||
console.log();
|
||||
showProjectSummary({
|
||||
name: profile.name,
|
||||
type: profile.type,
|
||||
languages,
|
||||
frameworks,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Display recommendations
|
||||
*/
|
||||
private displayRecommendations(
|
||||
recommendations: ScoredSkill[],
|
||||
profile: ProjectProfile,
|
||||
@@ -219,59 +218,59 @@ export class RecommendCommand extends Command {
|
||||
this.showProjectProfile(profile);
|
||||
|
||||
if (recommendations.length === 0) {
|
||||
console.log(chalk.yellow('No matching skills found.'));
|
||||
console.log(chalk.dim('Try lowering the minimum score with --min-score'));
|
||||
warn('No matching skills found.');
|
||||
console.log(colors.muted('Try lowering the minimum score with --min-score'));
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`Recommended Skills (${recommendations.length} of ${totalScanned} scanned):\n`));
|
||||
console.log(colors.bold(`Recommended Skills (${recommendations.length} of ${totalScanned} scanned):`));
|
||||
console.log('');
|
||||
|
||||
for (const rec of recommendations) {
|
||||
const scoreColor = rec.score >= 70 ? chalk.green : rec.score >= 50 ? chalk.yellow : chalk.dim;
|
||||
const scoreBar = this.getScoreBar(rec.score);
|
||||
let scoreColor: (text: string) => string;
|
||||
if (rec.score >= 70) {
|
||||
scoreColor = colors.success;
|
||||
} else if (rec.score >= 50) {
|
||||
scoreColor = colors.warning;
|
||||
} else {
|
||||
scoreColor = colors.muted;
|
||||
}
|
||||
const scoreBar = progressBar(rec.score, 100, 10);
|
||||
|
||||
console.log(` ${scoreColor(`${rec.score}%`)} ${scoreBar} ${chalk.bold(rec.skill.name)}`);
|
||||
console.log(` ${scoreColor(`${rec.score}%`)} ${colors.dim(scoreBar)} ${colors.bold(rec.skill.name)}`);
|
||||
|
||||
if (rec.skill.description) {
|
||||
console.log(` ${chalk.dim(truncate(rec.skill.description, 70))}`);
|
||||
console.log(` ${colors.muted(truncate(rec.skill.description, 70))}`);
|
||||
}
|
||||
|
||||
if (rec.skill.source) {
|
||||
console.log(` ${chalk.dim('Source:')} ${rec.skill.source}`);
|
||||
console.log(` ${colors.dim('Source:')} ${rec.skill.source}`);
|
||||
}
|
||||
|
||||
if (this.verbose && rec.reasons.length > 0) {
|
||||
console.log(chalk.dim(' Reasons:'));
|
||||
console.log(colors.dim(' Reasons:'));
|
||||
for (const reason of rec.reasons.filter(r => r.weight > 0)) {
|
||||
console.log(` ${chalk.dim('•')} ${reason.description} (+${reason.weight})`);
|
||||
console.log(` ${colors.muted(symbols.stepActive)} ${reason.description} (+${reason.weight})`);
|
||||
}
|
||||
}
|
||||
|
||||
if (rec.warnings.length > 0) {
|
||||
for (const warning of rec.warnings) {
|
||||
console.log(` ${chalk.yellow('⚠')} ${warning}`);
|
||||
console.log(` ${colors.warning(symbols.warning)} ${warning}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log('');
|
||||
}
|
||||
|
||||
console.log(chalk.dim('Install with: skillkit install <source>'));
|
||||
console.log(colors.muted('Install with: skillkit install <source>'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a visual score bar
|
||||
*/
|
||||
private getScoreBar(score: number): string {
|
||||
const filled = Math.round(score / 10);
|
||||
const empty = 10 - filled;
|
||||
return chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle search mode
|
||||
*/
|
||||
private handleSearch(engine: RecommendationEngine, query: string): number {
|
||||
if (!this.quiet && !this.json) {
|
||||
header(`Search: "${query}"`);
|
||||
}
|
||||
|
||||
const results = engine.search({
|
||||
query,
|
||||
limit: this.limit ? parseInt(this.limit, 10) : 10,
|
||||
@@ -287,35 +286,41 @@ export class RecommendCommand extends Command {
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
console.log(chalk.yellow(`No skills found matching "${query}"`));
|
||||
warn(`No skills found matching "${query}"`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`Search results for "${query}" (${results.length} found):\n`));
|
||||
console.log('');
|
||||
console.log(colors.bold(`Search results for "${query}" (${results.length} found):`));
|
||||
console.log('');
|
||||
|
||||
for (const result of results) {
|
||||
const relevanceColor =
|
||||
result.relevance >= 70 ? chalk.green : result.relevance >= 50 ? chalk.yellow : chalk.dim;
|
||||
let relevanceColor: (text: string) => string;
|
||||
if (result.relevance >= 70) {
|
||||
relevanceColor = colors.success;
|
||||
} else if (result.relevance >= 50) {
|
||||
relevanceColor = colors.warning;
|
||||
} else {
|
||||
relevanceColor = colors.muted;
|
||||
}
|
||||
const relevanceBar = progressBar(result.relevance, 100, 10);
|
||||
|
||||
console.log(` ${relevanceColor(`${result.relevance}%`)} ${chalk.bold(result.skill.name)}`);
|
||||
console.log(` ${relevanceColor(`${result.relevance}%`)} ${colors.dim(relevanceBar)} ${colors.bold(result.skill.name)}`);
|
||||
|
||||
if (result.snippet) {
|
||||
console.log(` ${chalk.dim(result.snippet)}`);
|
||||
console.log(` ${colors.muted(result.snippet)}`);
|
||||
}
|
||||
|
||||
if (result.matchedTerms.length > 0) {
|
||||
console.log(` ${chalk.dim('Matched:')} ${result.matchedTerms.join(', ')}`);
|
||||
console.log(` ${colors.dim('Matched:')} ${result.matchedTerms.join(', ')}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log('');
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load skill index from cache
|
||||
*/
|
||||
private loadIndex() {
|
||||
const index = loadIndexFromCache();
|
||||
|
||||
@@ -324,63 +329,62 @@ export class RecommendCommand extends Command {
|
||||
}
|
||||
|
||||
// Check if index is stale
|
||||
if (isIndexStale(index) && !this.json) {
|
||||
if (isIndexStale(index) && !this.json && !this.quiet) {
|
||||
const lastUpdated = new Date(index.lastUpdated);
|
||||
const hoursSinceUpdate = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60);
|
||||
console.log(
|
||||
chalk.dim(`Index is ${Math.round(hoursSinceUpdate)} hours old. Run --update to refresh.\n`)
|
||||
colors.muted(`Index is ${Math.round(hoursSinceUpdate)} hours old. Run --update to refresh.\n`)
|
||||
);
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update skill index from sources
|
||||
*/
|
||||
private async updateIndex(): Promise<number> {
|
||||
console.log(chalk.cyan('Updating skill index from GitHub repositories...\n'));
|
||||
console.log(chalk.dim(`Sources: ${KNOWN_SKILL_REPOS.map(r => `${r.owner}/${r.repo}`).join(', ')}\n`));
|
||||
if (!this.quiet) {
|
||||
header('Update Skill Index');
|
||||
}
|
||||
|
||||
const spinner = ora('Fetching skills...').start();
|
||||
console.log(colors.muted(`Sources: ${KNOWN_SKILL_REPOS.map(r => `${r.owner}/${r.repo}`).join(', ')}\n`));
|
||||
|
||||
const s = spinner();
|
||||
s.start('Fetching skills...');
|
||||
|
||||
try {
|
||||
const { index, errors } = await buildSkillIndex(KNOWN_SKILL_REPOS, (message) => {
|
||||
spinner.text = message;
|
||||
s.message(message);
|
||||
});
|
||||
|
||||
spinner.stop();
|
||||
s.stop(`Fetched ${index.skills.length} skills`);
|
||||
|
||||
// Report any errors
|
||||
if (errors.length > 0) {
|
||||
console.log(chalk.yellow('\nWarnings:'));
|
||||
console.log('');
|
||||
console.log(colors.warning('Warnings:'));
|
||||
for (const error of errors) {
|
||||
console.log(chalk.dim(` • ${error}`));
|
||||
console.log(colors.muted(` ${symbols.stepActive} ${error}`));
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
// Save the index
|
||||
saveIndex(index);
|
||||
|
||||
console.log(chalk.green(`✓ Updated index with ${index.skills.length} skills`));
|
||||
console.log('');
|
||||
console.log(colors.success(`${symbols.success} Updated index with ${index.skills.length} skills`));
|
||||
if (index.sources.length > 0) {
|
||||
console.log(chalk.dim(` Sources: ${index.sources.map((s) => s.name).join(', ')}`));
|
||||
console.log(colors.muted(` Sources: ${index.sources.map((s) => s.name).join(', ')}`));
|
||||
}
|
||||
console.log(chalk.dim(` Saved to: ${INDEX_PATH}\n`));
|
||||
console.log(colors.muted(` Saved to: ${INDEX_PATH}\n`));
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Failed to update index');
|
||||
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
|
||||
} catch (err) {
|
||||
s.stop(colors.error('Failed to update index'));
|
||||
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate string to max length
|
||||
*/
|
||||
function truncate(str: string, maxLen: number): string {
|
||||
if (str.length <= maxLen) return str;
|
||||
return str.slice(0, maxLen - 3) + '...';
|
||||
|
||||
@@ -1,11 +1,24 @@
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { loadConfig, findAllSkills } from '@skillkit/core';
|
||||
import type { AgentType } from '@skillkit/core';
|
||||
import { getAdapter, detectAgent } from '@skillkit/agents';
|
||||
import { getAdapter, detectAgent, getAllAdapters } from '@skillkit/agents';
|
||||
import { getSearchDirs, getAgentConfigPath } from '../helpers.js';
|
||||
import {
|
||||
header,
|
||||
colors,
|
||||
symbols,
|
||||
formatAgent,
|
||||
isCancel,
|
||||
spinner,
|
||||
select,
|
||||
confirm,
|
||||
outro,
|
||||
cancel,
|
||||
warn,
|
||||
showSyncSummary,
|
||||
} from '../onboarding/index.js';
|
||||
|
||||
export class SyncCommand extends Command {
|
||||
static override paths = [['sync'], ['s']];
|
||||
@@ -36,19 +49,54 @@ export class SyncCommand extends Command {
|
||||
description: 'Skip confirmation prompts',
|
||||
});
|
||||
|
||||
quiet = Option.Boolean('--quiet,-q', false, {
|
||||
description: 'Minimal output',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const isInteractive = process.stdin.isTTY && !this.yes;
|
||||
|
||||
if (!this.quiet) {
|
||||
header('Sync Skills');
|
||||
}
|
||||
|
||||
try {
|
||||
let agentType: AgentType;
|
||||
const s = spinner();
|
||||
|
||||
if (this.agent) {
|
||||
agentType = this.agent as AgentType;
|
||||
} else if (isInteractive) {
|
||||
// Let user select agent
|
||||
s.start('Detecting agent...');
|
||||
const config = loadConfig();
|
||||
const detected = config.agent || (await detectAgent());
|
||||
s.stop(`Detected: ${formatAgent(detected)}`);
|
||||
|
||||
const allAgents = getAllAdapters().map(a => a.type);
|
||||
|
||||
const agentResult = await select({
|
||||
message: 'Sync to which agent?',
|
||||
options: allAgents.map(a => ({
|
||||
value: a,
|
||||
label: formatAgent(a),
|
||||
hint: a === detected ? '(current)' : undefined,
|
||||
})),
|
||||
initialValue: detected,
|
||||
});
|
||||
|
||||
if (isCancel(agentResult)) {
|
||||
cancel('Sync cancelled');
|
||||
return 0;
|
||||
}
|
||||
|
||||
agentType = agentResult as AgentType;
|
||||
} else {
|
||||
const config = loadConfig();
|
||||
agentType = config.agent || (await detectAgent());
|
||||
}
|
||||
|
||||
const adapter = getAdapter(agentType);
|
||||
|
||||
const outputPath = this.output || getAgentConfigPath(agentType);
|
||||
|
||||
const searchDirs = getSearchDirs(agentType);
|
||||
@@ -59,23 +107,47 @@ export class SyncCommand extends Command {
|
||||
}
|
||||
|
||||
if (skills.length === 0) {
|
||||
console.log(chalk.yellow('No skills found to sync'));
|
||||
console.log(chalk.dim('Install skills with: skillkit install <source>'));
|
||||
warn('No skills found to sync');
|
||||
console.log(colors.muted('Install skills with: skillkit install <source>'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`Syncing ${skills.length} skill(s) for ${adapter.name}:`));
|
||||
skills.forEach(s => {
|
||||
const status = s.enabled ? chalk.green('✓') : chalk.dim('○');
|
||||
const location = s.location === 'project' ? chalk.blue('[project]') : chalk.dim('[global]');
|
||||
console.log(` ${status} ${s.name} ${location}`);
|
||||
});
|
||||
console.log();
|
||||
// Show skills to sync
|
||||
if (!this.quiet) {
|
||||
console.log('');
|
||||
console.log(colors.bold(`Syncing ${skills.length} skill(s) for ${adapter.name}:`));
|
||||
console.log('');
|
||||
|
||||
for (const skill of skills) {
|
||||
const status = skill.enabled ? colors.success(symbols.success) : colors.muted(symbols.stepPending);
|
||||
const location = skill.location === 'project'
|
||||
? colors.cyan('[project]')
|
||||
: colors.muted('[global]');
|
||||
console.log(` ${status} ${skill.name} ${location}`);
|
||||
}
|
||||
console.log('');
|
||||
}
|
||||
|
||||
// Confirm sync
|
||||
if (isInteractive && !this.yes) {
|
||||
const confirmResult = await confirm({
|
||||
message: `Sync ${skills.length} skill(s) to ${outputPath}?`,
|
||||
initialValue: true,
|
||||
});
|
||||
|
||||
if (isCancel(confirmResult) || !confirmResult) {
|
||||
cancel('Sync cancelled');
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Generate and write config
|
||||
s.start('Generating config...');
|
||||
|
||||
const config = adapter.generateConfig(skills);
|
||||
|
||||
if (!config) {
|
||||
console.log(chalk.yellow('No configuration generated'));
|
||||
s.stop('No configuration generated');
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -93,13 +165,23 @@ export class SyncCommand extends Command {
|
||||
|
||||
writeFileSync(outputPath, newContent, 'utf-8');
|
||||
|
||||
console.log(chalk.green(`Synced to ${outputPath}`));
|
||||
console.log(chalk.dim(`Agent: ${adapter.name}`));
|
||||
s.stop('Config generated');
|
||||
|
||||
// Show summary
|
||||
showSyncSummary({
|
||||
skillCount: skills.length,
|
||||
agentType,
|
||||
configPath: outputPath,
|
||||
});
|
||||
|
||||
if (!this.quiet) {
|
||||
outro('Sync complete!');
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
console.error(chalk.red('Sync failed'));
|
||||
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
|
||||
} catch (err) {
|
||||
console.log(colors.error('Sync failed'));
|
||||
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
export {
|
||||
AGENT_ICONS,
|
||||
AGENT_NAMES,
|
||||
symbols,
|
||||
SPINNER_FRAMES,
|
||||
colors,
|
||||
formatAgent,
|
||||
getAgentIcon,
|
||||
formatAgentIconsInline,
|
||||
progressBar,
|
||||
formatScore,
|
||||
} from './theme.js';
|
||||
|
||||
export {
|
||||
getLogo,
|
||||
getFullLogo,
|
||||
getCompactLogo,
|
||||
getMinimalLogo,
|
||||
getHeader,
|
||||
getDivider,
|
||||
} from './logo.js';
|
||||
|
||||
export * as prompts from './prompts.js';
|
||||
export {
|
||||
isCancel,
|
||||
intro,
|
||||
outro,
|
||||
cancel,
|
||||
note,
|
||||
log,
|
||||
step,
|
||||
success,
|
||||
warn,
|
||||
error,
|
||||
spinner,
|
||||
text,
|
||||
password,
|
||||
confirm,
|
||||
select,
|
||||
agentMultiselect,
|
||||
skillMultiselect,
|
||||
groupMultiselect,
|
||||
stepTrail,
|
||||
selectInstallMethod,
|
||||
tasks,
|
||||
summaryBox,
|
||||
type SkillOption,
|
||||
} from './prompts.js';
|
||||
|
||||
export {
|
||||
showInstallSummary,
|
||||
showNextSteps,
|
||||
showAgentSummary,
|
||||
showProjectSummary,
|
||||
showSyncSummary,
|
||||
showSkillList,
|
||||
showMarketplaceInfo,
|
||||
type InstallResult,
|
||||
type InstallSummary,
|
||||
} from './summary.js';
|
||||
|
||||
export {
|
||||
loadPreferences,
|
||||
savePreferences,
|
||||
isOnboardingComplete,
|
||||
completeOnboarding,
|
||||
saveLastAgents,
|
||||
getLastAgents,
|
||||
saveInstallMethod,
|
||||
getInstallMethod,
|
||||
getPreferencesDir,
|
||||
getPreferencesPath,
|
||||
type UserPreferences,
|
||||
} from './preferences.js';
|
||||
|
||||
import { getLogo, getHeader } from './logo.js';
|
||||
import * as prompts from './prompts.js';
|
||||
import { colors, formatAgent } from './theme.js';
|
||||
import { showNextSteps } from './summary.js';
|
||||
import {
|
||||
completeOnboarding,
|
||||
saveLastAgents,
|
||||
getLastAgents,
|
||||
} from './preferences.js';
|
||||
|
||||
let VERSION = '1.7.4';
|
||||
let AGENT_COUNT = 17;
|
||||
|
||||
export function setVersion(version: string): void {
|
||||
VERSION = version;
|
||||
}
|
||||
|
||||
export function setAgentCount(count: number): void {
|
||||
AGENT_COUNT = count;
|
||||
}
|
||||
|
||||
export function welcome(): void {
|
||||
console.log(getLogo(VERSION, AGENT_COUNT));
|
||||
}
|
||||
|
||||
export function header(title: string): void {
|
||||
console.log(getHeader(title));
|
||||
}
|
||||
|
||||
export async function runOnboarding(detectedAgents: string[]): Promise<{
|
||||
selectedAgents: string[];
|
||||
cancelled: boolean;
|
||||
}> {
|
||||
welcome();
|
||||
|
||||
if (detectedAgents.length === 0) {
|
||||
prompts.warn('No agents detected');
|
||||
completeOnboarding();
|
||||
return { selectedAgents: [], cancelled: false };
|
||||
}
|
||||
|
||||
prompts.log(`Detected ${detectedAgents.length} agent${detectedAgents.length !== 1 ? 's' : ''}: ${detectedAgents.map(formatAgent).join(', ')}`);
|
||||
|
||||
const agentResult = await prompts.agentMultiselect({
|
||||
message: 'Select agents to configure',
|
||||
agents: detectedAgents,
|
||||
initialValues: detectedAgents,
|
||||
});
|
||||
|
||||
if (prompts.isCancel(agentResult)) {
|
||||
prompts.cancel('Setup cancelled');
|
||||
return { selectedAgents: [], cancelled: true };
|
||||
}
|
||||
|
||||
saveLastAgents(agentResult as string[]);
|
||||
completeOnboarding();
|
||||
|
||||
prompts.success(`Configured ${agentResult.length} agent${agentResult.length !== 1 ? 's' : ''}`);
|
||||
|
||||
return { selectedAgents: agentResult as string[], cancelled: false };
|
||||
}
|
||||
|
||||
export interface InstallFlowOptions {
|
||||
source: string;
|
||||
discoveredSkills: Array<{ name: string; path: string }>;
|
||||
detectedAgents: string[];
|
||||
showLogo?: boolean;
|
||||
}
|
||||
|
||||
export interface InstallFlowResult {
|
||||
selectedSkills: string[];
|
||||
selectedAgents: string[];
|
||||
installMethod: 'symlink' | 'copy';
|
||||
cancelled: boolean;
|
||||
}
|
||||
|
||||
export async function runInstallFlow(options: InstallFlowOptions): Promise<InstallFlowResult> {
|
||||
const { source, discoveredSkills, detectedAgents, showLogo = true } = options;
|
||||
|
||||
if (showLogo) {
|
||||
welcome();
|
||||
}
|
||||
|
||||
prompts.step(`Source: ${colors.cyan(source)}`);
|
||||
prompts.step(`Found ${discoveredSkills.length} skill${discoveredSkills.length !== 1 ? 's' : ''}`);
|
||||
|
||||
const skillNames = discoveredSkills.map(s => s.name);
|
||||
const skillResult = await prompts.skillMultiselect({
|
||||
message: 'Select skills to install',
|
||||
skills: discoveredSkills.map(s => ({ name: s.name })),
|
||||
initialValues: skillNames,
|
||||
});
|
||||
|
||||
if (prompts.isCancel(skillResult)) {
|
||||
prompts.cancel('Installation cancelled');
|
||||
return { selectedSkills: [], selectedAgents: [], installMethod: 'symlink', cancelled: true };
|
||||
}
|
||||
|
||||
if (detectedAgents.length > 1) {
|
||||
prompts.step(`Detected ${detectedAgents.length} agents`);
|
||||
}
|
||||
|
||||
const lastAgents = getLastAgents();
|
||||
const initialAgents = lastAgents.length > 0 ? lastAgents : detectedAgents;
|
||||
|
||||
const agentResult = await prompts.agentMultiselect({
|
||||
message: 'Install to which agents?',
|
||||
agents: detectedAgents,
|
||||
initialValues: initialAgents.filter(a => detectedAgents.includes(a)),
|
||||
});
|
||||
|
||||
if (prompts.isCancel(agentResult)) {
|
||||
prompts.cancel('Installation cancelled');
|
||||
return { selectedSkills: skillResult as string[], selectedAgents: [], installMethod: 'symlink', cancelled: true };
|
||||
}
|
||||
|
||||
saveLastAgents(agentResult as string[]);
|
||||
|
||||
const methodResult = await prompts.selectInstallMethod({
|
||||
message: 'Installation method',
|
||||
});
|
||||
|
||||
if (prompts.isCancel(methodResult)) {
|
||||
prompts.cancel('Installation cancelled');
|
||||
return {
|
||||
selectedSkills: skillResult as string[],
|
||||
selectedAgents: agentResult as string[],
|
||||
installMethod: 'symlink',
|
||||
cancelled: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
selectedSkills: skillResult as string[],
|
||||
selectedAgents: agentResult as string[],
|
||||
installMethod: methodResult as 'symlink' | 'copy',
|
||||
cancelled: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function showCompletion(options: {
|
||||
skillNames: string[];
|
||||
agentTypes: string[];
|
||||
action?: 'install' | 'sync' | 'init';
|
||||
}): void {
|
||||
const action = options.action || 'install';
|
||||
const messages: Record<string, string> = {
|
||||
install: 'Installation complete!',
|
||||
sync: 'Sync complete!',
|
||||
init: 'Initialization complete!',
|
||||
};
|
||||
|
||||
prompts.outro(messages[action] || 'Done!');
|
||||
showNextSteps(options);
|
||||
}
|
||||
|
||||
export function handleCancel(message?: string): void {
|
||||
prompts.cancel(message || 'Operation cancelled');
|
||||
process.exit(0);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import pc from 'picocolors';
|
||||
import { symbols } from './theme.js';
|
||||
|
||||
function getTerminalWidth(): number {
|
||||
return process.stdout.columns || 80;
|
||||
}
|
||||
|
||||
export function getFullLogo(version?: string, agentCount?: number): string {
|
||||
const lines = [
|
||||
'',
|
||||
pc.dim(' ') + pc.white('███████╗') + pc.gray('██╗ ██╗') + pc.dim('██╗') + pc.gray('██╗ ') + pc.dim('██╗ ') + pc.white('██╗ ██╗') + pc.gray('██╗') + pc.dim('████████╗'),
|
||||
pc.dim(' ') + pc.white('██╔════╝') + pc.gray('██║ ██╔╝') + pc.dim('██║') + pc.gray('██║ ') + pc.dim('██║ ') + pc.white('██║ ██╔╝') + pc.gray('██║') + pc.dim('╚══██╔══╝'),
|
||||
pc.dim(' ') + pc.white('███████╗') + pc.gray('█████╔╝ ') + pc.dim('██║') + pc.gray('██║ ') + pc.dim('██║ ') + pc.white('█████╔╝ ') + pc.gray('██║') + pc.dim(' ██║ '),
|
||||
pc.dim(' ') + pc.white('╚════██║') + pc.gray('██╔═██╗ ') + pc.dim('██║') + pc.gray('██║ ') + pc.dim('██║ ') + pc.white('██╔═██╗ ') + pc.gray('██║') + pc.dim(' ██║ '),
|
||||
pc.dim(' ') + pc.white('███████║') + pc.gray('██║ ██╗') + pc.dim('██║') + pc.gray('███████╗') + pc.dim('███████╗') + pc.white('██║ ██╗') + pc.gray('██║') + pc.dim(' ██║ '),
|
||||
pc.dim(' ') + pc.white('╚══════╝') + pc.gray('╚═╝ ╚═╝') + pc.dim('╚═╝') + pc.gray('╚══════╝') + pc.dim('╚══════╝') + pc.white('╚═╝ ╚═╝') + pc.gray('╚═╝') + pc.dim(' ╚═╝ '),
|
||||
'',
|
||||
];
|
||||
|
||||
if (version || agentCount) {
|
||||
const info: string[] = [];
|
||||
if (version) info.push(`v${version}`);
|
||||
if (agentCount) info.push(`${agentCount} agents`);
|
||||
lines.push(pc.dim(' ') + pc.dim(info.join(' │ ')));
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export function getCompactLogo(version?: string, agentCount?: number): string {
|
||||
const frame = `${symbols.frameCorner}${symbols.frameLine.repeat(18)}${symbols.frameCorner}`;
|
||||
|
||||
const lines = [
|
||||
'',
|
||||
pc.dim(` ${frame}`),
|
||||
pc.dim(' ') + pc.white(' S K I L L K I T '),
|
||||
pc.dim(` ${frame}`),
|
||||
];
|
||||
|
||||
if (version || agentCount) {
|
||||
const info: string[] = [];
|
||||
if (version) info.push(`v${version}`);
|
||||
if (agentCount) info.push(`${agentCount} agents`);
|
||||
lines.push(pc.dim(' ') + pc.dim(info.join(' │ ')));
|
||||
}
|
||||
|
||||
lines.push('');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export function getMinimalLogo(version?: string): string {
|
||||
const lines = [
|
||||
'',
|
||||
pc.dim(`${symbols.diamondOpen}───`) + pc.white('SKILLKIT') + pc.dim(`───${symbols.diamondOpen}`),
|
||||
];
|
||||
|
||||
if (version) {
|
||||
lines.push(pc.dim(` v${version}`));
|
||||
}
|
||||
|
||||
lines.push('');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export function getLogo(version?: string, agentCount?: number): string {
|
||||
const width = getTerminalWidth();
|
||||
|
||||
if (width >= 70) {
|
||||
return getFullLogo(version, agentCount);
|
||||
}
|
||||
if (width >= 50) {
|
||||
return getCompactLogo(version, agentCount);
|
||||
}
|
||||
return getMinimalLogo(version);
|
||||
}
|
||||
|
||||
export function getHeader(title: string): string {
|
||||
return `\n${pc.dim(symbols.diamondOpen)} ${pc.white(pc.bold('SkillKit'))} ${pc.dim('│')} ${pc.cyan(title)}\n`;
|
||||
}
|
||||
|
||||
export function getDivider(width?: number): string {
|
||||
const fallback = Math.min(getTerminalWidth() - 4, 60);
|
||||
const w = Math.max(1, width ?? fallback);
|
||||
return pc.dim(symbols.horizontalLine.repeat(w));
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
|
||||
const SKILLKIT_DIR = join(homedir(), '.skillkit');
|
||||
const PREFERENCES_FILE = join(SKILLKIT_DIR, 'preferences.json');
|
||||
|
||||
export interface UserPreferences {
|
||||
onboardingComplete: boolean;
|
||||
lastSelectedAgents: string[];
|
||||
defaultInstallMethod: 'symlink' | 'copy';
|
||||
outputFormat: 'pretty' | 'json';
|
||||
lastAccessed: string;
|
||||
version?: string;
|
||||
}
|
||||
|
||||
const DEFAULT_PREFERENCES: UserPreferences = {
|
||||
onboardingComplete: false,
|
||||
lastSelectedAgents: [],
|
||||
defaultInstallMethod: 'symlink',
|
||||
outputFormat: 'pretty',
|
||||
lastAccessed: new Date().toISOString(),
|
||||
};
|
||||
|
||||
function ensureDir(): void {
|
||||
if (!existsSync(SKILLKIT_DIR)) {
|
||||
mkdirSync(SKILLKIT_DIR, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
export function loadPreferences(): UserPreferences {
|
||||
try {
|
||||
if (!existsSync(PREFERENCES_FILE)) {
|
||||
return { ...DEFAULT_PREFERENCES };
|
||||
}
|
||||
|
||||
const content = readFileSync(PREFERENCES_FILE, 'utf-8');
|
||||
const data = JSON.parse(content);
|
||||
|
||||
return {
|
||||
...DEFAULT_PREFERENCES,
|
||||
...data,
|
||||
lastAccessed: new Date().toISOString(),
|
||||
};
|
||||
} catch {
|
||||
return { ...DEFAULT_PREFERENCES };
|
||||
}
|
||||
}
|
||||
|
||||
export function savePreferences(prefs: Partial<UserPreferences>): void {
|
||||
try {
|
||||
ensureDir();
|
||||
|
||||
const current = loadPreferences();
|
||||
const updated: UserPreferences = {
|
||||
...current,
|
||||
...prefs,
|
||||
lastAccessed: new Date().toISOString(),
|
||||
};
|
||||
|
||||
writeFileSync(PREFERENCES_FILE, JSON.stringify(updated, null, 2), 'utf-8');
|
||||
} catch {
|
||||
// Silently fail - preferences are not critical
|
||||
}
|
||||
}
|
||||
|
||||
export function isOnboardingComplete(): boolean {
|
||||
return loadPreferences().onboardingComplete;
|
||||
}
|
||||
|
||||
export function completeOnboarding(): void {
|
||||
savePreferences({ onboardingComplete: true });
|
||||
}
|
||||
|
||||
export function saveLastAgents(agents: string[]): void {
|
||||
savePreferences({ lastSelectedAgents: agents });
|
||||
}
|
||||
|
||||
export function getLastAgents(): string[] {
|
||||
return loadPreferences().lastSelectedAgents;
|
||||
}
|
||||
|
||||
export function saveInstallMethod(method: 'symlink' | 'copy'): void {
|
||||
savePreferences({ defaultInstallMethod: method });
|
||||
}
|
||||
|
||||
export function getInstallMethod(): 'symlink' | 'copy' {
|
||||
return loadPreferences().defaultInstallMethod;
|
||||
}
|
||||
|
||||
export function getPreferencesDir(): string {
|
||||
return SKILLKIT_DIR;
|
||||
}
|
||||
|
||||
export function getPreferencesPath(): string {
|
||||
return PREFERENCES_FILE;
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import * as clack from '@clack/prompts';
|
||||
import pc from 'picocolors';
|
||||
import { symbols, colors, formatAgent, formatScore } from './theme.js';
|
||||
|
||||
export function isCancel(value: unknown): value is symbol {
|
||||
return clack.isCancel(value);
|
||||
}
|
||||
|
||||
export function intro(message?: string): void {
|
||||
clack.intro(message ? pc.bold(message) : undefined);
|
||||
}
|
||||
|
||||
export function outro(message: string): void {
|
||||
clack.outro(pc.green(message));
|
||||
}
|
||||
|
||||
export function cancel(message: string = 'Operation cancelled'): void {
|
||||
clack.cancel(pc.yellow(message));
|
||||
}
|
||||
|
||||
export function note(message: string, title?: string): void {
|
||||
clack.note(message, title);
|
||||
}
|
||||
|
||||
export function log(message: string): void {
|
||||
clack.log.info(message);
|
||||
}
|
||||
|
||||
export function step(message: string): void {
|
||||
clack.log.step(message);
|
||||
}
|
||||
|
||||
export function success(message: string): void {
|
||||
clack.log.success(pc.green(message));
|
||||
}
|
||||
|
||||
export function warn(message: string): void {
|
||||
clack.log.warn(pc.yellow(message));
|
||||
}
|
||||
|
||||
export function error(message: string): void {
|
||||
clack.log.error(pc.red(message));
|
||||
}
|
||||
|
||||
export function spinner(): ReturnType<typeof clack.spinner> {
|
||||
return clack.spinner();
|
||||
}
|
||||
|
||||
export async function text(options: {
|
||||
message: string;
|
||||
placeholder?: string;
|
||||
defaultValue?: string;
|
||||
validate?: (value: string) => string | Error | undefined;
|
||||
}): Promise<string | symbol> {
|
||||
return clack.text({
|
||||
message: options.message,
|
||||
placeholder: options.placeholder,
|
||||
defaultValue: options.defaultValue,
|
||||
validate: options.validate,
|
||||
});
|
||||
}
|
||||
|
||||
export async function password(options: {
|
||||
message: string;
|
||||
validate?: (value: string) => string | Error | undefined;
|
||||
}): Promise<string | symbol> {
|
||||
return clack.password({
|
||||
message: options.message,
|
||||
validate: options.validate,
|
||||
});
|
||||
}
|
||||
|
||||
export async function confirm(options: {
|
||||
message: string;
|
||||
initialValue?: boolean;
|
||||
}): Promise<boolean | symbol> {
|
||||
return clack.confirm({
|
||||
message: options.message,
|
||||
initialValue: options.initialValue,
|
||||
});
|
||||
}
|
||||
|
||||
export async function select<T extends string>(options: {
|
||||
message: string;
|
||||
options: Array<{ value: T; label: string; hint?: string }>;
|
||||
initialValue?: T;
|
||||
}): Promise<T | symbol> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return clack.select({
|
||||
message: options.message,
|
||||
options: options.options as any,
|
||||
initialValue: options.initialValue,
|
||||
});
|
||||
}
|
||||
|
||||
export async function agentMultiselect(options: {
|
||||
message: string;
|
||||
agents: string[];
|
||||
initialValues?: string[];
|
||||
required?: boolean;
|
||||
}): Promise<string[] | symbol> {
|
||||
const agentOptions = options.agents.map((agent) => ({
|
||||
value: agent,
|
||||
label: formatAgent(agent),
|
||||
hint: undefined as string | undefined,
|
||||
}));
|
||||
|
||||
return clack.multiselect({
|
||||
message: options.message,
|
||||
options: agentOptions,
|
||||
initialValues: options.initialValues,
|
||||
required: options.required ?? true,
|
||||
});
|
||||
}
|
||||
|
||||
export interface SkillOption {
|
||||
name: string;
|
||||
description?: string;
|
||||
score?: number;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export async function skillMultiselect(options: {
|
||||
message: string;
|
||||
skills: SkillOption[];
|
||||
initialValues?: string[];
|
||||
required?: boolean;
|
||||
}): Promise<string[] | symbol> {
|
||||
const skillOptions = options.skills.map((skill) => {
|
||||
const label = skill.name;
|
||||
let hint: string | undefined;
|
||||
|
||||
if (skill.score !== undefined) {
|
||||
hint = formatScore(skill.score);
|
||||
} else if (skill.source) {
|
||||
hint = pc.dim(skill.source);
|
||||
}
|
||||
|
||||
return { value: skill.name, label, hint };
|
||||
});
|
||||
|
||||
return clack.multiselect({
|
||||
message: options.message,
|
||||
options: skillOptions,
|
||||
initialValues: options.initialValues,
|
||||
required: options.required ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
export async function groupMultiselect<T extends string>(options: {
|
||||
message: string;
|
||||
options: Record<string, Array<{ value: T; label: string; hint?: string }>>;
|
||||
required?: boolean;
|
||||
}): Promise<T[] | symbol> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return clack.groupMultiselect({
|
||||
message: options.message,
|
||||
options: options.options as any,
|
||||
required: options.required,
|
||||
});
|
||||
}
|
||||
|
||||
export function stepTrail(steps: Array<{ label: string; status: 'pending' | 'active' | 'complete' }>): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (let i = 0; i < steps.length; i++) {
|
||||
const currentStep = steps[i];
|
||||
const isLast = i === steps.length - 1;
|
||||
|
||||
let icon: string;
|
||||
let labelColor: (text: string) => string;
|
||||
|
||||
switch (currentStep.status) {
|
||||
case 'complete':
|
||||
icon = colors.success(symbols.stepComplete);
|
||||
labelColor = colors.muted;
|
||||
break;
|
||||
case 'active':
|
||||
icon = colors.accent(symbols.stepActive);
|
||||
labelColor = colors.primary;
|
||||
break;
|
||||
case 'pending':
|
||||
default:
|
||||
icon = colors.muted(symbols.stepPending);
|
||||
labelColor = colors.muted;
|
||||
break;
|
||||
}
|
||||
|
||||
lines.push(`${icon} ${labelColor(currentStep.label)}`);
|
||||
|
||||
if (!isLast) {
|
||||
lines.push(`${colors.muted(symbols.stepLine)}`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export async function selectInstallMethod(options: {
|
||||
message?: string;
|
||||
}): Promise<'symlink' | 'copy' | symbol> {
|
||||
return clack.select({
|
||||
message: options.message || 'Installation method',
|
||||
options: [
|
||||
{
|
||||
value: 'symlink' as const,
|
||||
label: 'Symlink (Recommended)',
|
||||
hint: 'Single source, auto-updates',
|
||||
},
|
||||
{
|
||||
value: 'copy' as const,
|
||||
label: 'Copy to all agents',
|
||||
hint: 'Independent copies',
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export async function tasks(
|
||||
taskList: Array<{
|
||||
title: string;
|
||||
task: (message: (msg: string) => void) => Promise<string | void>;
|
||||
enabled?: boolean;
|
||||
}>
|
||||
): Promise<void> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return clack.tasks(taskList.filter((t) => t.enabled !== false) as any);
|
||||
}
|
||||
|
||||
export function summaryBox(options: {
|
||||
title: string;
|
||||
items: Array<{ label: string; value: string; icon?: string }>;
|
||||
}): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const item of options.items) {
|
||||
const icon = item.icon ? `${item.icon} ` : '';
|
||||
lines.push(` ${icon}${colors.primary(item.label)}`);
|
||||
lines.push(` ${colors.muted(item.value)}`);
|
||||
}
|
||||
|
||||
clack.note(lines.join('\n'), options.title);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import * as prompts from './prompts.js';
|
||||
import { symbols, colors, formatAgent, getAgentIcon, formatAgentIconsInline } from './theme.js';
|
||||
|
||||
export interface InstallResult {
|
||||
skillName: string;
|
||||
method: 'symlink' | 'copy';
|
||||
agents: string[];
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface InstallSummary {
|
||||
totalSkills: number;
|
||||
totalAgents: number;
|
||||
results: InstallResult[];
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export function showInstallSummary(summary: InstallSummary): void {
|
||||
const title = `Installed ${summary.totalSkills} skill${summary.totalSkills !== 1 ? 's' : ''} to ${summary.totalAgents} agent${summary.totalAgents !== 1 ? 's' : ''}`;
|
||||
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const result of summary.results) {
|
||||
lines.push(`${colors.success(symbols.success)} ${colors.primary(result.skillName)}`);
|
||||
|
||||
const agentDisplay = result.agents.length <= 3
|
||||
? result.agents.map(formatAgent).join(', ')
|
||||
: `${formatAgentIconsInline(result.agents.slice(0, 3))} +${result.agents.length - 3} more`;
|
||||
|
||||
lines.push(` ${result.method} ${symbols.arrowRight} ${agentDisplay}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
prompts.note(lines.join('\n').trim(), title);
|
||||
}
|
||||
|
||||
export function showNextSteps(options: {
|
||||
skillNames: string[];
|
||||
agentTypes: string[];
|
||||
syncNeeded?: boolean;
|
||||
}): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`${colors.muted('1.')} Run ${colors.cyan('skillkit sync')} to update agent configs`);
|
||||
lines.push(`${colors.muted('2.')} Use ${colors.cyan(`skillkit read ${options.skillNames[0] || '<skill>'}`)} to view skill docs`);
|
||||
|
||||
if (options.agentTypes.includes('claude-code')) {
|
||||
lines.push(`${colors.muted('3.')} Skills are available via ${colors.cyan('/@')} in Claude Code`);
|
||||
} else if (options.agentTypes.includes('cursor')) {
|
||||
lines.push(`${colors.muted('3.')} Skills are available in Cursor rules`);
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log(colors.dim('Next steps:'));
|
||||
console.log(lines.map(l => ` ${l}`).join('\n'));
|
||||
console.log('');
|
||||
}
|
||||
|
||||
export function showAgentSummary(agents: string[]): void {
|
||||
console.log('');
|
||||
console.log(colors.dim('Detected agents:'));
|
||||
|
||||
const iconLine = agents.map(a => `${getAgentIcon(a)} ${colors.muted(a)}`).join(' ');
|
||||
console.log(` ${iconLine}`);
|
||||
console.log('');
|
||||
}
|
||||
|
||||
export function showProjectSummary(profile: {
|
||||
name: string;
|
||||
type?: string;
|
||||
languages: string[];
|
||||
frameworks: string[];
|
||||
}): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`${colors.primary('Project:')} ${profile.name}`);
|
||||
|
||||
if (profile.type) {
|
||||
lines.push(`${colors.primary('Type:')} ${profile.type}`);
|
||||
}
|
||||
|
||||
if (profile.languages.length > 0) {
|
||||
lines.push(`${colors.primary('Languages:')} ${profile.languages.join(', ')}`);
|
||||
}
|
||||
|
||||
if (profile.frameworks.length > 0) {
|
||||
lines.push(`${colors.primary('Frameworks:')} ${profile.frameworks.join(', ')}`);
|
||||
}
|
||||
|
||||
prompts.note(lines.join('\n'), 'Project Analysis');
|
||||
}
|
||||
|
||||
export function showSyncSummary(options: {
|
||||
skillCount: number;
|
||||
agentType: string;
|
||||
configPath: string;
|
||||
}): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`${colors.success(symbols.success)} Synced ${options.skillCount} skill${options.skillCount !== 1 ? 's' : ''}`);
|
||||
lines.push(` Agent: ${formatAgent(options.agentType)}`);
|
||||
lines.push(` Config: ${colors.muted(options.configPath)}`);
|
||||
|
||||
console.log('');
|
||||
console.log(lines.join('\n'));
|
||||
console.log('');
|
||||
}
|
||||
|
||||
export function showSkillList(skills: Array<{
|
||||
name: string;
|
||||
description?: string;
|
||||
score?: number;
|
||||
source?: string;
|
||||
installed?: boolean;
|
||||
}>): void {
|
||||
console.log('');
|
||||
|
||||
for (const skill of skills) {
|
||||
let line = '';
|
||||
|
||||
if (skill.installed) {
|
||||
line += colors.success(symbols.success) + ' ';
|
||||
} else {
|
||||
line += colors.muted(symbols.stepPending) + ' ';
|
||||
}
|
||||
|
||||
line += colors.primary(skill.name);
|
||||
|
||||
if (skill.score !== undefined) {
|
||||
let scoreColor: (text: string) => string;
|
||||
if (skill.score >= 70) {
|
||||
scoreColor = colors.success;
|
||||
} else if (skill.score >= 50) {
|
||||
scoreColor = colors.warning;
|
||||
} else {
|
||||
scoreColor = colors.muted;
|
||||
}
|
||||
line += ` ${scoreColor(`${skill.score}%`)}`;
|
||||
}
|
||||
|
||||
console.log(line);
|
||||
|
||||
if (skill.description) {
|
||||
console.log(` ${colors.muted(truncate(skill.description, 60))}`);
|
||||
}
|
||||
|
||||
if (skill.source) {
|
||||
console.log(` ${colors.dim(`Source: ${skill.source}`)}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('');
|
||||
}
|
||||
|
||||
export function showMarketplaceInfo(options: {
|
||||
totalSkills: number;
|
||||
sourceCount: number;
|
||||
lastUpdated?: string;
|
||||
}): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`Total skills: ${colors.cyan(String(options.totalSkills))}`);
|
||||
lines.push(`Sources: ${colors.cyan(String(options.sourceCount))}`);
|
||||
|
||||
if (options.lastUpdated) {
|
||||
const date = new Date(options.lastUpdated).toLocaleDateString();
|
||||
lines.push(`Updated: ${colors.muted(date)}`);
|
||||
}
|
||||
|
||||
prompts.note(lines.join('\n'), 'Skill Marketplace');
|
||||
}
|
||||
|
||||
function truncate(str: string, maxLen: number): string {
|
||||
if (str.length <= maxLen) return str;
|
||||
return str.slice(0, maxLen - 3) + '...';
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import pc from 'picocolors';
|
||||
|
||||
export const AGENT_ICONS: Record<string, string> = {
|
||||
'claude-code': '\u27c1',
|
||||
'cursor': '\u25eb',
|
||||
'codex': '\u25ce',
|
||||
'gemini-cli': '\u2726',
|
||||
'opencode': '\u2b21',
|
||||
'github-copilot': '\u25c8',
|
||||
'windsurf': '\u224b',
|
||||
'droid': '\u25a3',
|
||||
'goose': '\u25c7',
|
||||
'amp': '\u25b3',
|
||||
'kilo': '\u25c9',
|
||||
'kiro-cli': '\u2b22',
|
||||
'roo': '\u2299',
|
||||
'trae': '\u25c6',
|
||||
'antigravity': '\u229b',
|
||||
'clawdbot': '\u27d0',
|
||||
'universal': '\u25cf',
|
||||
};
|
||||
|
||||
export const AGENT_NAMES: Record<string, string> = {
|
||||
'claude-code': 'Claude Code',
|
||||
'cursor': 'Cursor',
|
||||
'codex': 'Codex CLI',
|
||||
'gemini-cli': 'Gemini CLI',
|
||||
'opencode': 'OpenCode',
|
||||
'github-copilot': 'Copilot',
|
||||
'windsurf': 'Windsurf',
|
||||
'droid': 'Droid',
|
||||
'goose': 'Goose',
|
||||
'amp': 'Amp',
|
||||
'kilo': 'Kilo Code',
|
||||
'kiro-cli': 'Kiro',
|
||||
'roo': 'Roo Code',
|
||||
'trae': 'Trae',
|
||||
'antigravity': 'Antigravity',
|
||||
'clawdbot': 'Clawdbot',
|
||||
'universal': 'Universal',
|
||||
};
|
||||
|
||||
export const symbols = {
|
||||
stepPending: '\u25cb',
|
||||
stepActive: '\u25cf',
|
||||
stepComplete: '\u25cf',
|
||||
stepLine: '\u2502',
|
||||
selected: '\u25cf',
|
||||
unselected: '\u25cb',
|
||||
pointer: '\u25b8',
|
||||
progressFull: '\u2588',
|
||||
progressEmpty: '\u2591',
|
||||
success: '\u2713',
|
||||
error: '\u2717',
|
||||
warning: '\u26a0',
|
||||
info: '\u2139',
|
||||
arrowRight: '\u2192',
|
||||
arrowLeft: '\u2190',
|
||||
diamondOpen: '\u25c7',
|
||||
diamondFilled: '\u25c6',
|
||||
horizontalLine: '\u2500',
|
||||
verticalLine: '\u2502',
|
||||
frameCorner: '\u25c7',
|
||||
frameLine: '\u2500',
|
||||
};
|
||||
|
||||
export const SPINNER_FRAMES = [
|
||||
'\u280b',
|
||||
'\u2819',
|
||||
'\u2839',
|
||||
'\u2838',
|
||||
'\u283c',
|
||||
'\u2834',
|
||||
'\u2826',
|
||||
'\u2827',
|
||||
'\u2807',
|
||||
'\u280f',
|
||||
];
|
||||
|
||||
export const colors = {
|
||||
accent: (text: string) => pc.green(text),
|
||||
accentBright: (text: string) => pc.bold(pc.green(text)),
|
||||
primary: (text: string) => pc.white(text),
|
||||
secondary: (text: string) => pc.gray(text),
|
||||
muted: (text: string) => pc.dim(text),
|
||||
success: (text: string) => pc.green(text),
|
||||
error: (text: string) => pc.red(text),
|
||||
warning: (text: string) => pc.yellow(text),
|
||||
info: (text: string) => pc.blue(text),
|
||||
bold: (text: string) => pc.bold(text),
|
||||
dim: (text: string) => pc.dim(text),
|
||||
underline: (text: string) => pc.underline(text),
|
||||
cyan: (text: string) => pc.cyan(text),
|
||||
magenta: (text: string) => pc.magenta(text),
|
||||
};
|
||||
|
||||
export function formatAgent(agentType: string): string {
|
||||
const icon = AGENT_ICONS[agentType] || symbols.stepActive;
|
||||
const name = AGENT_NAMES[agentType] || agentType;
|
||||
return `${icon} ${name}`;
|
||||
}
|
||||
|
||||
export function getAgentIcon(agentType: string): string {
|
||||
return AGENT_ICONS[agentType] || symbols.stepActive;
|
||||
}
|
||||
|
||||
export function formatAgentIconsInline(agents: string[]): string {
|
||||
return agents.map(a => getAgentIcon(a)).join(' ');
|
||||
}
|
||||
|
||||
export function progressBar(value: number, total: number, width: number = 6): string {
|
||||
if (width <= 0 || total <= 0) return '';
|
||||
const clampedValue = Math.min(Math.max(value, 0), total);
|
||||
const filled = Math.round((clampedValue / total) * width);
|
||||
const safeFilled = Math.min(Math.max(filled, 0), width);
|
||||
const empty = width - safeFilled;
|
||||
return symbols.progressFull.repeat(safeFilled) + symbols.progressEmpty.repeat(empty);
|
||||
}
|
||||
|
||||
export function formatScore(score: number): string {
|
||||
const bar = progressBar(score, 100, 6);
|
||||
let scoreColor: (text: string) => string;
|
||||
if (score >= 70) {
|
||||
scoreColor = colors.success;
|
||||
} else if (score >= 50) {
|
||||
scoreColor = colors.warning;
|
||||
} else {
|
||||
scoreColor = colors.muted;
|
||||
}
|
||||
return `${scoreColor(`${score}%`)} ${colors.dim(bar)}`;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@skillkit/core",
|
||||
"version": "1.5.0",
|
||||
"version": "1.7.4",
|
||||
"description": "Core functionality for SkillKit - skill discovery, parsing, and translation",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { mkdirSync, writeFileSync, rmSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import {
|
||||
AGENT_SKILL_FORMATS,
|
||||
parseSkillToCanonical,
|
||||
parseSkillContentToCanonical,
|
||||
translateSkillToAgent,
|
||||
translateSkillToAll,
|
||||
writeTranslatedSkill,
|
||||
generateSkillsConfig,
|
||||
getAgentSkillsDir,
|
||||
getAgentConfigFile,
|
||||
supportsAutoDiscovery,
|
||||
getAllSkillsDirs,
|
||||
getGlobalSkillsDir,
|
||||
type CrossAgentSkill,
|
||||
type SkillTranslationOptions,
|
||||
} from '../skill-translator.js';
|
||||
|
||||
describe('Skill Translator', () => {
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
tempDir = join(tmpdir(), `skillkit-test-${Date.now()}`);
|
||||
mkdirSync(tempDir, { recursive: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (existsSync(tempDir)) {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe('AGENT_SKILL_FORMATS', () => {
|
||||
it('should have configurations for all supported agents', () => {
|
||||
const expectedAgents = [
|
||||
'claude-code', 'cursor', 'codex', 'gemini-cli', 'opencode',
|
||||
'antigravity', 'amp', 'clawdbot', 'droid', 'github-copilot',
|
||||
'goose', 'kilo', 'kiro-cli', 'roo', 'trae', 'windsurf', 'universal',
|
||||
];
|
||||
|
||||
for (const agent of expectedAgents) {
|
||||
expect(AGENT_SKILL_FORMATS[agent as keyof typeof AGENT_SKILL_FORMATS]).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('should have valid skillsDir for each agent', () => {
|
||||
for (const [agent, format] of Object.entries(AGENT_SKILL_FORMATS)) {
|
||||
expect(format.skillsDir).toBeTruthy();
|
||||
expect(typeof format.skillsDir).toBe('string');
|
||||
}
|
||||
});
|
||||
|
||||
it('should have valid configFile for each agent', () => {
|
||||
for (const [agent, format] of Object.entries(AGENT_SKILL_FORMATS)) {
|
||||
expect(format.configFile).toBeTruthy();
|
||||
expect(typeof format.configFile).toBe('string');
|
||||
}
|
||||
});
|
||||
|
||||
it('should have correct Cursor MDC format', () => {
|
||||
const cursor = AGENT_SKILL_FORMATS.cursor;
|
||||
expect(cursor.skillsDir).toBe('.cursor/skills');
|
||||
expect(cursor.configFile).toBe('.cursor/rules/skills.mdc');
|
||||
expect(cursor.configFormat).toBe('mdc');
|
||||
});
|
||||
|
||||
it('should have correct Windsurf format', () => {
|
||||
const windsurf = AGENT_SKILL_FORMATS.windsurf;
|
||||
expect(windsurf.skillsDir).toBe('.windsurf/skills');
|
||||
expect(windsurf.configFile).toBe('.windsurf/rules/skills.md');
|
||||
expect(windsurf.configFormat).toBe('markdown');
|
||||
expect(windsurf.globalSkillsDir).toBe('~/.codeium/windsurf/skills');
|
||||
});
|
||||
|
||||
it('should have correct GitHub Copilot format', () => {
|
||||
const copilot = AGENT_SKILL_FORMATS['github-copilot'];
|
||||
expect(copilot.skillsDir).toBe('.github/skills');
|
||||
expect(copilot.configFile).toBe('.github/copilot-instructions.md');
|
||||
expect(copilot.configFormat).toBe('markdown');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseSkillToCanonical', () => {
|
||||
it('should parse a valid SKILL.md file', () => {
|
||||
const skillDir = join(tempDir, 'test-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: test-skill
|
||||
description: A test skill for unit testing
|
||||
version: "1.0.0"
|
||||
author: Test Author
|
||||
tags:
|
||||
- testing
|
||||
- unit-test
|
||||
---
|
||||
# Test Skill
|
||||
|
||||
This is a test skill for unit testing purposes.
|
||||
|
||||
## Usage
|
||||
|
||||
Use this skill when you need to test something.
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.name).toBe('test-skill');
|
||||
expect(result?.description).toBe('A test skill for unit testing');
|
||||
expect(result?.version).toBe('1.0.0');
|
||||
expect(result?.author).toBe('Test Author');
|
||||
expect(result?.tags).toEqual(['testing', 'unit-test']);
|
||||
expect(result?.content).toContain('# Test Skill');
|
||||
});
|
||||
|
||||
it('should return null for non-existent skill', () => {
|
||||
const result = parseSkillToCanonical(join(tempDir, 'non-existent'));
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('should handle SKILL.md without frontmatter', () => {
|
||||
const skillDir = join(tempDir, 'no-frontmatter-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `# Simple Skill
|
||||
|
||||
Just some content without frontmatter.
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
expect(result).not.toBeNull();
|
||||
// Without frontmatter, name is derived from directory name
|
||||
expect(result?.name).toBe('no-frontmatter-skill');
|
||||
});
|
||||
|
||||
it('should extract allowed-tools from frontmatter', () => {
|
||||
const skillDir = join(tempDir, 'tools-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: tools-skill
|
||||
description: Skill with allowed tools
|
||||
allowed-tools: Read, Write, Bash
|
||||
---
|
||||
Content here.
|
||||
`);
|
||||
|
||||
const result = parseSkillToCanonical(skillDir);
|
||||
expect(result?.allowedTools).toEqual(['Read', 'Write', 'Bash']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseSkillContentToCanonical', () => {
|
||||
it('should parse skill content with full frontmatter', () => {
|
||||
const content = `---
|
||||
name: content-skill
|
||||
description: Parsed from content
|
||||
model: opus
|
||||
context: fork
|
||||
disable-model-invocation: true
|
||||
---
|
||||
# Content Skill
|
||||
|
||||
Instructions here.
|
||||
`;
|
||||
|
||||
const result = parseSkillContentToCanonical(content, '/path/to/skill', 'claude-code');
|
||||
expect(result?.name).toBe('content-skill');
|
||||
expect(result?.description).toBe('Parsed from content');
|
||||
expect(result?.agentFields?.['model']).toBe('opus');
|
||||
expect(result?.agentFields?.['context']).toBe('fork');
|
||||
expect(result?.agentFields?.['disable-model-invocation']).toBe(true);
|
||||
expect(result?.sourceAgent).toBe('claude-code');
|
||||
});
|
||||
|
||||
it('should extract description from content when not in frontmatter', () => {
|
||||
const content = `---
|
||||
name: no-desc
|
||||
---
|
||||
This is a longer paragraph that should be used as the description when none is provided in frontmatter.
|
||||
|
||||
## More Content
|
||||
`;
|
||||
|
||||
const result = parseSkillContentToCanonical(content, '/path/to/skill');
|
||||
expect(result?.description).toContain('This is a longer paragraph');
|
||||
});
|
||||
});
|
||||
|
||||
describe('translateSkillToAgent', () => {
|
||||
const testSkill: CrossAgentSkill = {
|
||||
name: 'translate-test',
|
||||
description: 'A skill to test translation',
|
||||
content: '# Translate Test\n\nTest content for translation.',
|
||||
frontmatter: { name: 'translate-test', description: 'A skill to test translation' },
|
||||
sourcePath: '/test/path',
|
||||
sourceAgent: 'claude-code',
|
||||
version: '1.0.0',
|
||||
author: 'Test',
|
||||
tags: ['test'],
|
||||
};
|
||||
|
||||
it('should translate to Claude Code format', () => {
|
||||
const result = translateSkillToAgent(testSkill, 'claude-code');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.content).toContain('name: translate-test');
|
||||
expect(result.content).toContain('description: A skill to test translation');
|
||||
expect(result.targetAgent).toBe('claude-code');
|
||||
});
|
||||
|
||||
it('should translate to Cursor format', () => {
|
||||
const result = translateSkillToAgent(testSkill, 'cursor');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.content).toContain('name: translate-test');
|
||||
expect(result.targetAgent).toBe('cursor');
|
||||
});
|
||||
|
||||
it('should translate to Windsurf format', () => {
|
||||
const result = translateSkillToAgent(testSkill, 'windsurf');
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.targetAgent).toBe('windsurf');
|
||||
});
|
||||
|
||||
it('should include translation metadata when requested', () => {
|
||||
const options: SkillTranslationOptions = { addMetadata: true };
|
||||
const result = translateSkillToAgent(testSkill, 'cursor', options);
|
||||
expect(result.content).toContain('_translated-from: claude-code');
|
||||
expect(result.content).toContain('_translated-at:');
|
||||
});
|
||||
|
||||
it('should preserve agent-specific fields for Claude Code', () => {
|
||||
const skillWithFields: CrossAgentSkill = {
|
||||
...testSkill,
|
||||
agentFields: {
|
||||
model: 'opus',
|
||||
context: 'fork',
|
||||
'disable-model-invocation': true,
|
||||
},
|
||||
};
|
||||
|
||||
const result = translateSkillToAgent(skillWithFields, 'claude-code');
|
||||
expect(result.content).toContain('model: opus');
|
||||
expect(result.content).toContain('context: fork');
|
||||
expect(result.content).toContain('disable-model-invocation: true');
|
||||
});
|
||||
|
||||
it('should report incompatible features', () => {
|
||||
const skillWithHooks: CrossAgentSkill = {
|
||||
...testSkill,
|
||||
agentFields: {
|
||||
hooks: [{ type: 'PreToolUse', command: 'echo test' }],
|
||||
},
|
||||
};
|
||||
|
||||
const result = translateSkillToAgent(skillWithHooks, 'cursor');
|
||||
expect(result.incompatible).toContain('hooks (only supported in Claude Code)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('translateSkillToAll', () => {
|
||||
it('should translate skill to all supported agents', () => {
|
||||
const skillDir = join(tempDir, 'all-agents-skill');
|
||||
mkdirSync(skillDir, { recursive: true });
|
||||
writeFileSync(join(skillDir, 'SKILL.md'), `---
|
||||
name: all-agents
|
||||
description: Skill for all agents
|
||||
---
|
||||
# All Agents Skill
|
||||
`);
|
||||
|
||||
const results = translateSkillToAll(skillDir, 'claude-code');
|
||||
expect(results.size).toBeGreaterThan(0);
|
||||
|
||||
// Should not include source agent
|
||||
expect(results.has('claude-code')).toBe(false);
|
||||
|
||||
// Should include other agents
|
||||
expect(results.has('cursor')).toBe(true);
|
||||
expect(results.has('windsurf')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return empty map for non-existent skill', () => {
|
||||
const results = translateSkillToAll(join(tempDir, 'non-existent'));
|
||||
expect(results.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeTranslatedSkill', () => {
|
||||
it('should write translated skill to disk', () => {
|
||||
const result = {
|
||||
success: true,
|
||||
content: '---\nname: written-skill\n---\n# Content',
|
||||
filename: 'SKILL.md',
|
||||
targetDir: 'test-skill',
|
||||
warnings: [],
|
||||
incompatible: [],
|
||||
targetAgent: 'claude-code' as const,
|
||||
};
|
||||
|
||||
const writeResult = writeTranslatedSkill(result, tempDir);
|
||||
expect(writeResult.success).toBe(true);
|
||||
expect(existsSync(writeResult.path)).toBe(true);
|
||||
});
|
||||
|
||||
it('should create nested directories', () => {
|
||||
const result = {
|
||||
success: true,
|
||||
content: '---\nname: nested\n---\n# Content',
|
||||
filename: 'SKILL.md',
|
||||
targetDir: '.cursor/skills/nested-skill',
|
||||
warnings: [],
|
||||
incompatible: [],
|
||||
targetAgent: 'cursor' as const,
|
||||
};
|
||||
|
||||
const writeResult = writeTranslatedSkill(result, tempDir);
|
||||
expect(writeResult.success).toBe(true);
|
||||
expect(existsSync(join(tempDir, '.cursor/skills/nested-skill/SKILL.md'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateSkillsConfig', () => {
|
||||
const testSkills = [
|
||||
{ name: 'skill-one', description: 'First skill', path: '/path/one', location: 'project' as const, enabled: true },
|
||||
{ name: 'skill-two', description: 'Second skill', path: '/path/two', location: 'project' as const, enabled: true },
|
||||
{ name: 'disabled-skill', description: 'Disabled', path: '/path/disabled', location: 'project' as const, enabled: false },
|
||||
];
|
||||
|
||||
it('should generate XML config for Claude Code', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'claude-code');
|
||||
expect(config).toContain('<skills_system');
|
||||
expect(config).toContain('<name>skill-one</name>');
|
||||
expect(config).toContain('<name>skill-two</name>');
|
||||
expect(config).not.toContain('disabled-skill');
|
||||
});
|
||||
|
||||
it('should generate MDC config for Cursor', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'cursor');
|
||||
expect(config).toContain('---');
|
||||
expect(config).toContain('description:');
|
||||
expect(config).toContain('globs:');
|
||||
expect(config).toContain('alwaysApply: true');
|
||||
expect(config).toContain('**skill-one**');
|
||||
expect(config).toContain('**skill-two**');
|
||||
});
|
||||
|
||||
it('should generate Markdown table config for Codex', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'codex');
|
||||
expect(config).toContain('| Skill | Description | Command |');
|
||||
expect(config).toContain('| skill-one |');
|
||||
expect(config).toContain('| skill-two |');
|
||||
});
|
||||
|
||||
it('should generate JSON config for Gemini CLI', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'gemini-cli');
|
||||
expect(config).toContain('```json');
|
||||
expect(config).toContain('"name": "skill-one"');
|
||||
expect(config).toContain('"name": "skill-two"');
|
||||
});
|
||||
|
||||
it('should generate Markdown config for Windsurf', () => {
|
||||
const config = generateSkillsConfig(testSkills, 'windsurf');
|
||||
expect(config).toContain('### skill-one');
|
||||
expect(config).toContain('### skill-two');
|
||||
expect(config).toContain('**Invoke:**');
|
||||
});
|
||||
|
||||
it('should return empty string for no enabled skills', () => {
|
||||
const disabledSkills = [
|
||||
{ name: 'disabled', description: 'Disabled', path: '/path', location: 'project' as const, enabled: false },
|
||||
];
|
||||
const config = generateSkillsConfig(disabledSkills, 'claude-code');
|
||||
expect(config).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('utility functions', () => {
|
||||
it('getAgentSkillsDir should return correct path', () => {
|
||||
expect(getAgentSkillsDir('claude-code')).toBe('.claude/skills');
|
||||
expect(getAgentSkillsDir('cursor')).toBe('.cursor/skills');
|
||||
expect(getAgentSkillsDir('windsurf')).toBe('.windsurf/skills');
|
||||
});
|
||||
|
||||
it('getAgentConfigFile should return correct path', () => {
|
||||
expect(getAgentConfigFile('claude-code')).toBe('CLAUDE.md');
|
||||
expect(getAgentConfigFile('cursor')).toBe('.cursor/rules/skills.mdc');
|
||||
expect(getAgentConfigFile('github-copilot')).toBe('.github/copilot-instructions.md');
|
||||
});
|
||||
|
||||
it('supportsAutoDiscovery should return true for all major agents', () => {
|
||||
expect(supportsAutoDiscovery('claude-code')).toBe(true);
|
||||
expect(supportsAutoDiscovery('cursor')).toBe(true);
|
||||
expect(supportsAutoDiscovery('windsurf')).toBe(true);
|
||||
});
|
||||
|
||||
it('getAllSkillsDirs should include alternative directories', () => {
|
||||
const cursorDirs = getAllSkillsDirs('cursor');
|
||||
expect(cursorDirs).toContain('.cursor/skills');
|
||||
expect(cursorDirs).toContain('.cursor/commands');
|
||||
|
||||
const windsurfDirs = getAllSkillsDirs('windsurf');
|
||||
expect(windsurfDirs).toContain('.windsurf/skills');
|
||||
expect(windsurfDirs).toContain('.windsurf/workflows');
|
||||
});
|
||||
|
||||
it('getGlobalSkillsDir should return correct global path', () => {
|
||||
expect(getGlobalSkillsDir('claude-code')).toBe('~/.claude/skills');
|
||||
expect(getGlobalSkillsDir('windsurf')).toBe('~/.codeium/windsurf/skills');
|
||||
expect(getGlobalSkillsDir('opencode')).toBe('~/.config/opencode/skills');
|
||||
expect(getGlobalSkillsDir('roo')).toBe('~/.roo/skills');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Agent Adapter Integration', () => {
|
||||
it('should have matching config formats between AGENT_SKILL_FORMATS and expected values', () => {
|
||||
// Verify that the 2026 updates are consistent
|
||||
expect(AGENT_SKILL_FORMATS.cursor.configFormat).toBe('mdc');
|
||||
expect(AGENT_SKILL_FORMATS.windsurf.configFormat).toBe('markdown');
|
||||
expect(AGENT_SKILL_FORMATS['github-copilot'].configFormat).toBe('markdown');
|
||||
expect(AGENT_SKILL_FORMATS.trae.configFormat).toBe('markdown');
|
||||
expect(AGENT_SKILL_FORMATS['claude-code'].configFormat).toBe('xml');
|
||||
expect(AGENT_SKILL_FORMATS.codex.configFormat).toBe('markdown-table');
|
||||
expect(AGENT_SKILL_FORMATS['gemini-cli'].configFormat).toBe('json');
|
||||
});
|
||||
|
||||
it('should have valid invoke commands', () => {
|
||||
for (const format of Object.values(AGENT_SKILL_FORMATS)) {
|
||||
expect(format.invokeCommand).toBe('skillkit read');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user