commit 088b9bad4e7d1a4ef8c5ce23f46c1e0957fe5611 Author: Rohit Ghumare Date: Tue Jan 20 15:42:51 2026 +0000 Initial release v1.0.0 - Universal skills loader for AI agents Features: - Multi-agent support: Claude Code, Codex, Cursor, Gemini CLI, OpenCode, Antigravity - Multi-platform Git: GitHub, GitLab, Bitbucket, local paths - Agent Skills spec compliance (agentskills.io) - Skill toggle, validation, and CI/CD support - Programmatic API for library usage diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..0c3f43c1 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [18, 20, 22] + + steps: + - uses: actions/checkout@v4 + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: 'npm' + + - name: Install dependencies + run: npm ci + + - name: Type check + run: npm run typecheck + + - name: Build + run: npm run build + + - name: Test + run: npm test diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 00000000..2c86f382 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,37 @@ +name: Publish to npm + +on: + release: + types: [published] + +jobs: + publish: + runs-on: ubuntu-latest + + permissions: + contents: read + id-token: write + + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + registry-url: 'https://registry.npmjs.org' + + - name: Install dependencies + run: npm ci + + - name: Build + run: npm run build + + - name: Test + run: npm test + + - name: Publish to npm + run: npm publish --provenance --access public + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..c01232df --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +# Dependencies +node_modules/ + +# Build output +dist/ + +# Test coverage +coverage/ + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Logs +*.log +npm-debug.log* + +# Environment +.env +.env.local +.env.*.local + +# Package manager +package-lock.json +yarn.lock +pnpm-lock.yaml + +# Temporary files +tmp/ +temp/ +*.tmp diff --git a/.npmignore b/.npmignore new file mode 100644 index 00000000..80c05f2c --- /dev/null +++ b/.npmignore @@ -0,0 +1,21 @@ +# Source files (dist is published) +src/ +tests/ + +# Config files +tsconfig.json +tsup.config.ts +vitest.config.ts +.eslintrc* + +# Dev files +.gitignore +.github/ +coverage/ + +# IDE +.idea/ +.vscode/ + +# OS +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..61442168 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Rohit Ghumare + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 00000000..b432ad71 --- /dev/null +++ b/README.md @@ -0,0 +1,308 @@ +# SkillKit + +Universal skills loader for AI coding agents. Install, manage, and sync skills across your favorite AI tools. + +Skills follow the [Agent Skills](https://agentskills.io) open format—a simple, portable standard for giving agents new capabilities and expertise. + +### Compatible With + +| Agent | Status | +|-------|--------| +| Claude Code | ✅ Native | +| OpenAI Codex | ✅ Native | +| Cursor | ✅ Native | +| Gemini CLI | ✅ Native | +| OpenCode | ✅ Native | +| Amp | ✅ Supported | +| Goose | ✅ Supported | +| VS Code (Copilot) | ✅ Supported | +| Letta | ✅ Supported | +| Factory | ✅ Supported | +| Antigravity | ✅ Native | +| *Any markdown-config agent* | ✅ Universal | + +## Features + +- **Multi-Agent Support**: Works with 10+ AI coding agents out of the box +- **Multi-Platform Git**: GitHub, GitLab, Bitbucket, and local paths +- **CI/CD Friendly**: Non-interactive flags for automation (`--skills`, `--all`, `--yes`) +- **Skill Toggle**: Enable/disable skills without removing them +- **Type-Safe**: Built with TypeScript and Zod validation +- **Zero Config**: Auto-detects your agent and configures appropriately + +## Installation + +```bash +npm install -g skillkit +# or +npx skillkit +``` + +## Quick Start + +```bash +# Initialize in your project (auto-detects agent) +skillkit init + +# Install skills from GitHub +skillkit install owner/repo + +# Install from GitLab +skillkit install gitlab:owner/repo + +# Install specific skills (CI/CD friendly) +skillkit install owner/repo --skills=pdf,xlsx,docx + +# Sync skills to your agent config +skillkit sync + +# Read a skill (for AI consumption) +skillkit read pdf +``` + +## Popular Skill Repositories + +Install skills from these community repositories: + +```bash +# Anthropic's official skill marketplace +skillkit install anthropics/skills + +# Vercel's React & Next.js best practices +skillkit install vercel-labs/agent-skills/skills +``` + +| Repository | Skills | Description | +|------------|--------|-------------| +| [anthropics/skills](https://github.com/anthropics/skills) | `pdf`, `xlsx`, `docx`, etc. | Official Claude Code skill marketplace | +| [vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills) | `vercel-react-best-practices`, `web-design-guidelines` | React/Next.js optimization & UI review | + + +## Commands + +### `skillkit install ` + +Install skills from various sources. + +```bash +# GitHub (default) +skillkit install owner/repo +skillkit install https://github.com/owner/repo + +# Install from a subdirectory +skillkit install owner/repo/skills + +# GitLab +skillkit install gitlab:owner/repo +skillkit install https://gitlab.com/owner/repo + +# Bitbucket +skillkit install bitbucket:owner/repo + +# Local path +skillkit install ./my-skills +skillkit install ~/dev/skills + +# Options +--skills=pdf,xlsx # Install specific skills only (CI/CD) +--all # Install all discovered skills +--yes # Skip confirmation prompts +--global # Install to global directory +--force # Overwrite existing skills +--provider=gitlab # Force specific provider +``` + +### `skillkit sync` + +Sync installed skills to your agent's config file. + +```bash +skillkit sync +skillkit sync --agent cursor +skillkit sync --output AGENTS.md +skillkit sync --enabled-only +``` + +### `skillkit read ` + +Read skill content for AI agent consumption. + +```bash +skillkit read pdf +skillkit read pdf,xlsx,docx # Multiple skills +``` + +### `skillkit list` + +List all installed skills. + +```bash +skillkit list +skillkit list --enabled +skillkit list --json +``` + +### `skillkit enable/disable ` + +Toggle skills on/off without removing them. + +```bash +skillkit enable pdf xlsx +skillkit disable docx +``` + +### `skillkit update [skills]` + +Update skills from their original sources. + +```bash +skillkit update # Update all +skillkit update pdf xlsx # Update specific +``` + +### `skillkit remove ` + +Remove installed skills. + +```bash +skillkit remove pdf xlsx +``` + +### `skillkit init` + +Initialize skillkit in a project. + +```bash +skillkit init +skillkit init --agent cursor +skillkit init --list # List supported agents +``` + +### `skillkit validate ` + +Validate skills against the [Agent Skills specification](https://agentskills.io/specification). + +```bash +skillkit validate ./my-skill # Validate single skill +skillkit validate ./skills --all # Validate all skills in directory +``` + +## Supported Agents + +| Agent | Config File | Skills Directory | +|-------|-------------|------------------| +| Claude Code | `AGENTS.md` | `.claude/skills/` | +| Cursor | `.cursorrules` | `.cursor/skills/` | +| Codex | `AGENTS.md` | `.codex/skills/` | +| Gemini CLI | `GEMINI.md` | `.gemini/skills/` | +| OpenCode | `AGENTS.md` | `.opencode/skills/` | +| Antigravity | `AGENTS.md` | `.antigravity/skills/` | +| Universal | `AGENTS.md` | `.agent/skills/` | + +## Creating Skills + +A skill is a directory with a `SKILL.md` file: + +``` +my-skill/ +├── SKILL.md # Required: Instructions for the AI +├── references/ # Optional: Documentation +├── scripts/ # Optional: Helper scripts +└── assets/ # Optional: Templates, configs +``` + +### SKILL.md Format + +Follows the [Agent Skills specification](https://agentskills.io/specification): + +```markdown +--- +name: my-skill +description: What this skill does and when to use it. Include trigger keywords. +license: MIT +compatibility: Requires Node.js 18+ +metadata: + author: your-org + version: "1.0" +--- + +# My Skill + +Instructions for the AI agent on how to use this skill. + +## When to Use + +- Scenario 1 +- Scenario 2 + +## Steps + +1. First step +2. Second step +``` + +| Field | Required | Description | +|-------|----------|-------------| +| `name` | Yes | Lowercase alphanumeric with hyphens (max 64 chars) | +| `description` | Yes | What it does and when to use it (max 1024 chars) | +| `license` | No | License name or reference | +| `compatibility` | No | Environment requirements | +| `metadata` | No | Arbitrary key-value pairs | + +## CI/CD Usage + +```yaml +# GitHub Actions example +- name: Setup skills + run: | + npx skillkit install owner/skills --skills=lint,test,deploy --yes + npx skillkit sync --yes +``` + +## Programmatic API + +```typescript +import { + findAllSkills, + discoverSkills, + detectAgent, + getAdapter, +} from 'skillkit'; + +// Find all installed skills +const skills = findAllSkills(searchDirs); + +// Detect current agent +const agent = await detectAgent(); + +// Generate config +const adapter = getAdapter(agent); +const config = adapter.generateConfig(skills); +``` + +## Configuration + +Create `skillkit.yaml` in your project: + +```yaml +version: 1 +agent: cursor # Override auto-detection +autoSync: true # Auto-sync on changes +enabledSkills: + - pdf + - xlsx +disabledSkills: + - deprecated-skill +``` + +## License + +MIT License - see [LICENSE](LICENSE) for details. + +## Contributing + +Contributions welcome! Please read our contributing guidelines. + +## Acknowledgments + +Implements the [Agent Skills](https://agentskills.io) open format, originally developed by Anthropic and adopted by leading AI development tools. diff --git a/package.json b/package.json new file mode 100644 index 00000000..31cac279 --- /dev/null +++ b/package.json @@ -0,0 +1,74 @@ +{ + "name": "skillkit", + "version": "1.0.0", + "description": "Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "bin": { + "skillkit": "./dist/cli.js", + "sk": "./dist/cli.js" + }, + "exports": { + ".": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + } + }, + "files": [ + "dist", + "schemas" + ], + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "test": "vitest run", + "test:watch": "vitest", + "test:coverage": "vitest run --coverage", + "typecheck": "tsc --noEmit", + "lint": "eslint src --ext .ts", + "prepublishOnly": "npm run typecheck && npm run build && npm run test" + }, + "keywords": [ + "ai", + "skills", + "claude", + "codex", + "cursor", + "gemini", + "opencode", + "antigravity", + "agent", + "coding-assistant", + "skill-loader", + "cli" + ], + "author": "Rohit Ghumare", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/rohitghumare/skillkit.git" + }, + "bugs": { + "url": "https://github.com/rohitghumare/skillkit/issues" + }, + "homepage": "https://github.com/rohitghumare/skillkit#readme", + "engines": { + "node": ">=18.0.0" + }, + "dependencies": { + "chalk": "^5.3.0", + "clipanion": "^4.0.0-rc.4", + "got": "^14.4.1", + "isomorphic-git": "^1.27.1", + "ora": "^8.1.0", + "yaml": "^2.6.1", + "zod": "^3.24.1" + }, + "devDependencies": { + "@types/node": "^22.10.5", + "tsup": "^8.3.5", + "typescript": "^5.7.2", + "vitest": "^2.1.8" + } +} diff --git a/schemas/skill.schema.json b/schemas/skill.schema.json new file mode 100644 index 00000000..032e7a62 --- /dev/null +++ b/schemas/skill.schema.json @@ -0,0 +1,62 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://skillkit.dev/schemas/skill.schema.json", + "title": "Skill Frontmatter", + "description": "Schema for SKILL.md frontmatter validation (follows Agent Skills spec: https://agentskills.io/specification)", + "type": "object", + "required": ["name", "description"], + "properties": { + "name": { + "type": "string", + "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$", + "minLength": 1, + "maxLength": 64, + "description": "Unique skill identifier. Lowercase alphanumeric with hyphens, no leading/trailing/consecutive hyphens." + }, + "description": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "description": "What the skill does and when to use it." + }, + "license": { + "type": "string", + "description": "License name or reference to bundled license file." + }, + "compatibility": { + "type": "string", + "maxLength": 500, + "description": "Environment requirements (intended product, system packages, network access, etc.)." + }, + "metadata": { + "type": "object", + "additionalProperties": { "type": "string" }, + "description": "Arbitrary key-value mapping for additional metadata." + }, + "allowed-tools": { + "type": "string", + "description": "Space-delimited list of pre-approved tools the skill may use (experimental)." + }, + "version": { + "type": "string", + "description": "Semantic version (e.g., 1.0.0)" + }, + "author": { + "type": "string", + "description": "Skill author name or organization" + }, + "tags": { + "type": "array", + "items": { "type": "string" }, + "description": "Categorization tags" + }, + "agents": { + "type": "array", + "items": { + "type": "string", + "enum": ["claude-code", "codex", "cursor", "antigravity", "opencode", "gemini-cli", "universal"] + }, + "description": "Compatible AI agents (empty = all agents)" + } + } +} diff --git a/src/agents/antigravity.ts b/src/agents/antigravity.ts new file mode 100644 index 00000000..2cad9205 --- /dev/null +++ b/src/agents/antigravity.ts @@ -0,0 +1,80 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import type { Skill, AgentType } from '../core/types.js'; + +export class AntigravityAdapter implements AgentAdapter { + readonly type: AgentType = 'antigravity'; + readonly name = 'Antigravity'; + readonly skillsDir = '.antigravity/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsYaml = enabledSkills + .map(s => ` - name: ${s.name}\n description: "${s.description}"\n invoke: skillkit read ${s.name}`) + .join('\n'); + + return `# Antigravity Skills Configuration + + + +## Available Skills + +${enabledSkills.map(s => `### ${s.name} + +${s.description} + +**Usage:** \`skillkit read ${s.name}\` +`).join('\n')} + +## How Skills Work + +1. Skills provide specialized knowledge for specific tasks +2. Load a skill when the current task matches its description +3. Skills are loaded on-demand to preserve context window +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + + const yamlMatch = content.match(//); + if (yamlMatch) { + const nameRegex = /name:\s*([a-z0-9-]+)/g; + let match; + while ((match = nameRegex.exec(yamlMatch[1])) !== null) { + skillNames.push(match[1].trim()); + } + } + + if (skillNames.length === 0) { + const headerRegex = /^### ([a-z0-9-]+)$/gm; + let match; + while ((match = headerRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const agDir = join(process.cwd(), '.antigravity'); + const globalAg = join(homedir(), '.antigravity'); + + return existsSync(agDir) || existsSync(globalAg); + } +} diff --git a/src/agents/base.ts b/src/agents/base.ts new file mode 100644 index 00000000..e3053c9f --- /dev/null +++ b/src/agents/base.ts @@ -0,0 +1,37 @@ +import type { Skill, AgentType } from '../core/types.js'; + +export interface AgentAdapter { + + readonly type: AgentType; + + readonly name: string; + + readonly skillsDir: string; + + readonly configFile: string; + + generateConfig(skills: Skill[]): string; + + parseConfig(content: string): string[]; + + getInvokeCommand(skillName: string): string; + + isDetected(): Promise; +} + +export function createSkillXml(skill: Skill): string { + return ` +${skill.name} +${escapeXml(skill.description)} +${skill.location} +`; +} + +export function escapeXml(text: string): string { + return text + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} diff --git a/src/agents/claude-code.ts b/src/agents/claude-code.ts new file mode 100644 index 00000000..f26e44c4 --- /dev/null +++ b/src/agents/claude-code.ts @@ -0,0 +1,76 @@ +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 '../core/types.js'; + +export class ClaudeCodeAdapter implements AgentAdapter { + readonly type: AgentType = 'claude-code'; + readonly name = 'Claude Code'; + readonly skillsDir = '.claude/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + + const projectClaude = join(process.cwd(), '.claude'); + const globalClaude = join(homedir(), '.claude'); + const claudeMd = join(process.cwd(), 'CLAUDE.md'); + + return existsSync(projectClaude) || existsSync(globalClaude) || existsSync(claudeMd); + } +} diff --git a/src/agents/codex.ts b/src/agents/codex.ts new file mode 100644 index 00000000..d8cefe32 --- /dev/null +++ b/src/agents/codex.ts @@ -0,0 +1,70 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import type { Skill, AgentType } from '../core/types.js'; + +export class CodexAdapter implements AgentAdapter { + readonly type: AgentType = 'codex'; + readonly name = 'OpenAI Codex CLI'; + readonly skillsDir = '.codex/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsList = enabledSkills + .map(s => `| ${s.name} | ${s.description} | \`skillkit read ${s.name}\` |`) + .join('\n'); + + return `# Skills + +You have access to specialized skills for completing complex tasks. + +| Skill | Description | Command | +|-------|-------------|---------| +${skillsList} + +## Usage + +When a task matches a skill's capability, run the command to load detailed instructions: + +\`\`\`bash +skillkit read +\`\`\` + +Skills are loaded on-demand to keep context clean. Only load skills when relevant to the current task. +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + + const tableRegex = /^\|\s*([a-z0-9-]+)\s*\|/gm; + let match; + + while ((match = tableRegex.exec(content)) !== null) { + const name = match[1].trim(); + if (name && name !== 'Skill' && name !== '-------') { + skillNames.push(name); + } + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const codexDir = join(process.cwd(), '.codex'); + const globalCodex = join(homedir(), '.codex'); + + return existsSync(codexDir) || existsSync(globalCodex); + } +} diff --git a/src/agents/cursor.ts b/src/agents/cursor.ts new file mode 100644 index 00000000..4a4147ed --- /dev/null +++ b/src/agents/cursor.ts @@ -0,0 +1,71 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '../core/types.js'; + +export class CursorAdapter implements AgentAdapter { + readonly type: AgentType = 'cursor'; + readonly name = 'Cursor'; + readonly skillsDir = '.cursor/skills'; + readonly configFile = '.cursorrules'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsList = enabledSkills + .map(s => `- **${s.name}**: ${s.description}`) + .join('\n'); + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return `# Skills System + +You have access to specialized skills that can help complete tasks. Use the skillkit CLI to load skill instructions when needed. + +## Available Skills + +${skillsList} + +## How to Use Skills + +When a task matches a skill's description, load it with: +\`\`\`bash +skillkit read +\`\`\` + +The skill will provide detailed instructions for completing the task. + + +${skillsXml} + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const cursorRules = join(process.cwd(), '.cursorrules'); + const cursorDir = join(process.cwd(), '.cursor'); + + return existsSync(cursorRules) || existsSync(cursorDir); + } +} diff --git a/src/agents/gemini-cli.ts b/src/agents/gemini-cli.ts new file mode 100644 index 00000000..f3526be3 --- /dev/null +++ b/src/agents/gemini-cli.ts @@ -0,0 +1,88 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import type { Skill, AgentType } from '../core/types.js'; + +export class GeminiCliAdapter implements AgentAdapter { + readonly type: AgentType = 'gemini-cli'; + readonly name = 'Gemini CLI'; + readonly skillsDir = '.gemini/skills'; + readonly configFile = 'GEMINI.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsJson = enabledSkills.map(s => ({ + name: s.name, + description: s.description, + invoke: `skillkit read ${s.name}`, + location: s.location, + })); + + return `# Skills Configuration + +You have access to specialized skills that extend your capabilities. + +## Available Skills + +${enabledSkills.map(s => `### ${s.name}\n${s.description}\n\nInvoke: \`skillkit read ${s.name}\``).join('\n\n')} + +## Skills Data + +\`\`\`json +${JSON.stringify(skillsJson, null, 2)} +\`\`\` + +## Usage Instructions + +1. When a task matches a skill's description, load it using the invoke command +2. Skills provide step-by-step instructions for complex tasks +3. Each skill is self-contained with its own resources +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + + const jsonMatch = content.match(/```json\s*([\s\S]*?)```/); + if (jsonMatch) { + try { + const skills = JSON.parse(jsonMatch[1]); + if (Array.isArray(skills)) { + skills.forEach(s => { + if (s.name) skillNames.push(s.name); + }); + } + } catch { + + } + } + + if (skillNames.length === 0) { + const headerRegex = /^### ([a-z0-9-]+)$/gm; + let match; + while ((match = headerRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const geminiMd = join(process.cwd(), 'GEMINI.md'); + const geminiDir = join(process.cwd(), '.gemini'); + const globalGemini = join(homedir(), '.gemini'); + + return existsSync(geminiMd) || existsSync(geminiDir) || existsSync(globalGemini); + } +} diff --git a/src/agents/index.ts b/src/agents/index.ts new file mode 100644 index 00000000..42422a94 --- /dev/null +++ b/src/agents/index.ts @@ -0,0 +1,66 @@ +import type { AgentAdapter } from './base.js'; +import type { AgentType } from '../core/types.js'; +import { ClaudeCodeAdapter } from './claude-code.js'; +import { CursorAdapter } from './cursor.js'; +import { CodexAdapter } from './codex.js'; +import { GeminiCliAdapter } from './gemini-cli.js'; +import { OpenCodeAdapter } from './opencode.js'; +import { AntigravityAdapter } from './antigravity.js'; +import { UniversalAdapter } from './universal.js'; + +export * from './base.js'; +export * from './claude-code.js'; +export * from './cursor.js'; +export * from './codex.js'; +export * from './gemini-cli.js'; +export * from './opencode.js'; +export * from './antigravity.js'; +export * from './universal.js'; + +const adapters: Record = { + 'claude-code': new ClaudeCodeAdapter(), + cursor: new CursorAdapter(), + codex: new CodexAdapter(), + 'gemini-cli': new GeminiCliAdapter(), + opencode: new OpenCodeAdapter(), + antigravity: new AntigravityAdapter(), + universal: new UniversalAdapter(), +}; + +export function getAdapter(type: AgentType): AgentAdapter { + return adapters[type]; +} + +export function getAllAdapters(): AgentAdapter[] { + return Object.values(adapters); +} + +export async function detectAgent(): Promise { + + const checkOrder: AgentType[] = [ + 'claude-code', + 'cursor', + 'codex', + 'gemini-cli', + 'opencode', + 'antigravity', + 'universal', + ]; + + for (const type of checkOrder) { + const adapter = adapters[type]; + if (await adapter.isDetected()) { + return type; + } + } + + return 'universal'; +} + +export function getSkillsDir(type: AgentType): string { + return adapters[type].skillsDir; +} + +export function getConfigFile(type: AgentType): string { + return adapters[type].configFile; +} diff --git a/src/agents/opencode.ts b/src/agents/opencode.ts new file mode 100644 index 00000000..84a039a6 --- /dev/null +++ b/src/agents/opencode.ts @@ -0,0 +1,67 @@ +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 '../core/types.js'; + +export class OpenCodeAdapter implements AgentAdapter { + readonly type: AgentType = 'opencode'; + readonly name = 'OpenCode'; + readonly skillsDir = '.opencode/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` +# Skills + +The following skills are available to help complete tasks: + + +${skillsXml} + + +## How to Use + +When a task matches a skill's description: + +\`\`\`bash +skillkit read +\`\`\` + +This loads the skill's instructions into context. + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const opencodeDir = join(process.cwd(), '.opencode'); + const globalOpencode = join(homedir(), '.opencode'); + + return existsSync(opencodeDir) || existsSync(globalOpencode); + } +} diff --git a/src/agents/universal.ts b/src/agents/universal.ts new file mode 100644 index 00000000..096b2f44 --- /dev/null +++ b/src/agents/universal.ts @@ -0,0 +1,99 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '../core/types.js'; + +export class UniversalAdapter implements AgentAdapter { + readonly type: AgentType = 'universal'; + readonly name = 'Universal (Any Agent)'; + readonly skillsDir = '.agent/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + const skillsList = enabledSkills + .map(s => `- **${s.name}**: ${s.description}`) + .join('\n'); + + return `# Skills System + + + +## Available Skills + +${skillsList} + +## How to Use Skills + +When a task matches one of the available skills, load it to get detailed instructions: + +\`\`\`bash +skillkit read +\`\`\` + +Or with npx: + +\`\`\`bash +npx skillkit read +\`\`\` + +## Skills Data + + + +Skills provide specialized capabilities and domain knowledge. +- Invoke: \`skillkit read \` +- Base directory provided in output for resolving resources +- Only use skills listed below +- Each invocation is stateless + + + + +${skillsXml} + + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + + const skillRegex = /([^<]+)<\/name>/g; + let match; + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + if (skillNames.length === 0) { + const listRegex = /^- \*\*([a-z0-9-]+)\*\*:/gm; + while ((match = listRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + + const agentDir = join(process.cwd(), '.agent'); + const agentsMd = join(process.cwd(), 'AGENTS.md'); + + return existsSync(agentDir) || existsSync(agentsMd); + } +} diff --git a/src/cli.ts b/src/cli.ts new file mode 100644 index 00000000..cf10c6b7 --- /dev/null +++ b/src/cli.ts @@ -0,0 +1,36 @@ +#!/usr/bin/env node +import { Cli, Builtins } from 'clipanion'; +import { + InstallCommand, + SyncCommand, + ReadCommand, + ListCommand, + EnableCommand, + DisableCommand, + UpdateCommand, + RemoveCommand, + InitCommand, + ValidateCommand, +} from './commands/index.js'; + +const cli = new Cli({ + binaryLabel: 'skillkit', + binaryName: 'skillkit', + binaryVersion: '1.0.0', +}); + +cli.register(Builtins.HelpCommand); +cli.register(Builtins.VersionCommand); + +cli.register(InstallCommand); +cli.register(SyncCommand); +cli.register(ReadCommand); +cli.register(ListCommand); +cli.register(EnableCommand); +cli.register(DisableCommand); +cli.register(UpdateCommand); +cli.register(RemoveCommand); +cli.register(InitCommand); +cli.register(ValidateCommand); + +cli.runExit(process.argv.slice(2)); diff --git a/src/commands/enable.ts b/src/commands/enable.ts new file mode 100644 index 00000000..b4683893 --- /dev/null +++ b/src/commands/enable.ts @@ -0,0 +1,106 @@ +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { getSearchDirs, setSkillEnabled } from '../core/config.js'; +import { findSkill } from '../core/skills.js'; + +export class EnableCommand extends Command { + static override paths = [['enable']]; + + static override usage = Command.Usage({ + description: 'Enable one or more skills', + examples: [ + ['Enable a skill', '$0 enable pdf'], + ['Enable multiple skills', '$0 enable pdf xlsx docx'], + ], + }); + + skills = Option.Rest({ required: 1 }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + let success = 0; + let failed = 0; + + for (const skillName of this.skills) { + const skill = findSkill(skillName, searchDirs); + + if (!skill) { + console.log(chalk.red(`Skill not found: ${skillName}`)); + failed++; + continue; + } + + if (skill.enabled) { + console.log(chalk.dim(`Already enabled: ${skillName}`)); + continue; + } + + const result = setSkillEnabled(skill.path, true); + + if (result) { + console.log(chalk.green(`Enabled: ${skillName}`)); + success++; + } else { + console.log(chalk.red(`Failed to enable: ${skillName}`)); + failed++; + } + } + + if (success > 0) { + console.log(chalk.dim('\nRun `skillkit sync` to update your agent config')); + } + + return failed > 0 ? 1 : 0; + } +} + +export class DisableCommand extends Command { + static override paths = [['disable']]; + + static override usage = Command.Usage({ + description: 'Disable one or more skills', + examples: [ + ['Disable a skill', '$0 disable pdf'], + ['Disable multiple skills', '$0 disable pdf xlsx docx'], + ], + }); + + skills = Option.Rest({ required: 1 }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + let success = 0; + let failed = 0; + + for (const skillName of this.skills) { + const skill = findSkill(skillName, searchDirs); + + if (!skill) { + console.log(chalk.red(`Skill not found: ${skillName}`)); + failed++; + continue; + } + + if (!skill.enabled) { + console.log(chalk.dim(`Already disabled: ${skillName}`)); + continue; + } + + const result = setSkillEnabled(skill.path, false); + + if (result) { + console.log(chalk.yellow(`Disabled: ${skillName}`)); + success++; + } else { + console.log(chalk.red(`Failed to disable: ${skillName}`)); + failed++; + } + } + + if (success > 0) { + console.log(chalk.dim('\nRun `skillkit sync` to update your agent config')); + } + + return failed > 0 ? 1 : 0; + } +} diff --git a/src/commands/index.ts b/src/commands/index.ts new file mode 100644 index 00000000..b34d2dba --- /dev/null +++ b/src/commands/index.ts @@ -0,0 +1,9 @@ +export { InstallCommand } from './install.js'; +export { SyncCommand } from './sync.js'; +export { ReadCommand } from './read.js'; +export { ListCommand } from './list.js'; +export { EnableCommand, DisableCommand } from './enable.js'; +export { UpdateCommand } from './update.js'; +export { RemoveCommand } from './remove.js'; +export { InitCommand } from './init.js'; +export { ValidateCommand } from './validate.js'; diff --git a/src/commands/init.ts b/src/commands/init.ts new file mode 100644 index 00000000..fba11937 --- /dev/null +++ b/src/commands/init.ts @@ -0,0 +1,80 @@ +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { initProject } from '../core/config.js'; +import { detectAgent, getAdapter, getAllAdapters } from '../agents/index.js'; +import type { AgentType } from '../core/types.js'; + +export class InitCommand extends Command { + static override paths = [['init']]; + + static override usage = Command.Usage({ + description: 'Initialize skillkit in a project', + examples: [ + ['Auto-detect agent and initialize', '$0 init'], + ['Initialize for specific agent', '$0 init --agent cursor'], + ['List supported agents', '$0 init --list'], + ], + }); + + agent = Option.String('--agent,-a', { + description: 'Target agent type', + }); + + list = Option.Boolean('--list,-l', false, { + description: 'List supported agents', + }); + + async execute(): Promise { + if (this.list) { + console.log(chalk.cyan('Supported agents:\n')); + const adapters = getAllAdapters(); + + 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(); + } + + return 0; + } + + try { + + let agentType: AgentType; + + if (this.agent) { + agentType = this.agent as AgentType; + } else { + console.log(chalk.dim('Auto-detecting agent...')); + agentType = await detectAgent(); + } + + const adapter = getAdapter(agentType); + + console.log(chalk.cyan(`Initializing for ${adapter.name}...`)); + + await initProject(agentType); + + 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 ')); + + return 0; + } catch (error) { + console.error(chalk.red('Initialization failed')); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + return 1; + } + } +} diff --git a/src/commands/install.ts b/src/commands/install.ts new file mode 100644 index 00000000..42329424 --- /dev/null +++ b/src/commands/install.ts @@ -0,0 +1,188 @@ +import { existsSync, mkdirSync, cpSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import chalk from 'chalk'; +import ora from 'ora'; +import { Command, Option } from 'clipanion'; +import { detectProvider, isLocalPath } from '../providers/index.js'; +import { getInstallDir, saveSkillMetadata } from '../core/config.js'; +import { isPathInside } from '../core/skills.js'; +import type { SkillMetadata, GitProvider } from '../core/types.js'; + +export class InstallCommand extends Command { + static override paths = [['install'], ['i']]; + + static override usage = Command.Usage({ + description: 'Install skills from GitHub, GitLab, Bitbucket, or local path', + examples: [ + ['Install from GitHub', '$0 install owner/repo'], + ['Install from GitLab', '$0 install gitlab:owner/repo'], + ['Install from Bitbucket', '$0 install bitbucket:owner/repo'], + ['Install specific skills (CI/CD)', '$0 install owner/repo --skills=pdf,xlsx'], + ['Install all skills non-interactively', '$0 install owner/repo --all'], + ['Install from local path', '$0 install ./my-skills'], + ['Install globally', '$0 install owner/repo --global'], + ], + }); + + source = Option.String({ required: true }); + + skills = Option.String('--skills,-s', { + description: 'Comma-separated list of skills to install (non-interactive)', + }); + + all = Option.Boolean('--all,-a', false, { + description: 'Install all discovered skills (non-interactive)', + }); + + yes = Option.Boolean('--yes,-y', false, { + description: 'Skip confirmation prompts', + }); + + global = Option.Boolean('--global,-g', false, { + description: 'Install to global skills directory', + }); + + force = Option.Boolean('--force,-f', false, { + description: 'Overwrite existing skills', + }); + + provider = Option.String('--provider,-p', { + description: 'Force specific provider (github, gitlab, bitbucket)', + }); + + async execute(): Promise { + const spinner = ora(); + + try { + let providerAdapter = detectProvider(this.source); + + if (this.provider) { + const { getProvider } = await import('../providers/index.js'); + providerAdapter = getProvider(this.provider as GitProvider); + } + + 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')); + return 1; + } + + spinner.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')); + return 1; + } + + spinner.succeed(`Found ${result.skills?.length || 0} skill(s)`); + + const discoveredSkills = result.discoveredSkills || []; + + let skillsToInstall = discoveredSkills; + + 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(', ')}`)); + return 1; + } + + skillsToInstall = discoveredSkills.filter(s => requestedSkills.includes(s.name)); + } else if (this.all || this.yes) { + skillsToInstall = discoveredSkills; + } else { + skillsToInstall = discoveredSkills; + + if (skillsToInstall.length > 0) { + console.log(chalk.cyan('\nSkills to install:')); + skillsToInstall.forEach(s => console.log(chalk.dim(` - ${s.name}`))); + console.log(); + } + } + + if (skillsToInstall.length === 0) { + console.log(chalk.yellow('No skills to install')); + return 0; + } + + const installDir = getInstallDir(this.global); + + 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)`)); + continue; + } + + const securityRoot = result.tempRoot || result.path; + if (!isPathInside(sourcePath, securityRoot)) { + console.log(chalk.red(` Skipping ${skillName} (path traversal detected)`)); + continue; + } + + spinner.start(`Installing ${skillName}...`); + + try { + if (existsSync(targetPath)) { + rmSync(targetPath, { recursive: true, force: true }); + } + + cpSync(sourcePath, targetPath, { recursive: true, dereference: true }); + + const metadata: SkillMetadata = { + name: skillName, + description: '', + source: this.source, + sourceType: providerAdapter.type, + subpath: skillName, + installedAt: new Date().toISOString(), + enabled: true, + }; + 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))); + } + } + + const cleanupPath = result.tempRoot || result.path; + if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) { + rmSync(cleanupPath, { recursive: true, force: true }); + } + + console.log(); + console.log(chalk.green(`Installed ${installed} skill(s) to ${installDir}`)); + + if (!this.yes) { + console.log(chalk.dim('\nRun `skillkit sync` to update your agent config')); + } + + return 0; + } catch (error) { + spinner.fail(chalk.red('Installation failed')); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + return 1; + } + } +} diff --git a/src/commands/list.ts b/src/commands/list.ts new file mode 100644 index 00000000..a960e3b5 --- /dev/null +++ b/src/commands/list.ts @@ -0,0 +1,107 @@ +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { getSearchDirs } from '../core/config.js'; +import { findAllSkills } from '../core/skills.js'; + +export class ListCommand extends Command { + static override paths = [['list'], ['ls'], ['l']]; + + static override usage = Command.Usage({ + description: 'List all installed skills', + examples: [ + ['List all skills', '$0 list'], + ['Show only enabled skills', '$0 list --enabled'], + ['Show JSON output', '$0 list --json'], + ], + }); + + enabled = Option.Boolean('--enabled,-e', false, { + description: 'Show only enabled skills', + }); + + disabled = Option.Boolean('--disabled,-d', false, { + description: 'Show only disabled skills', + }); + + json = Option.Boolean('--json,-j', false, { + description: 'Output as JSON', + }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + let skills = findAllSkills(searchDirs); + + if (this.enabled) { + skills = skills.filter(s => s.enabled); + } else if (this.disabled) { + skills = skills.filter(s => !s.enabled); + } + + skills.sort((a, b) => { + if (a.location !== b.location) { + return a.location === 'project' ? -1 : 1; + } + return a.name.localeCompare(b.name); + }); + + if (this.json) { + console.log(JSON.stringify(skills, null, 2)); + return 0; + } + + if (skills.length === 0) { + console.log(chalk.yellow('No skills installed')); + console.log(chalk.dim('Install skills with: skillkit install ')); + return 0; + } + + console.log(chalk.cyan(`Installed skills (${skills.length}):\n`)); + + const projectSkills = skills.filter(s => s.location === 'project'); + const globalSkills = skills.filter(s => s.location === 'global'); + + if (projectSkills.length > 0) { + console.log(chalk.blue('Project skills:')); + for (const skill of projectSkills) { + printSkill(skill); + } + console.log(); + } + + if (globalSkills.length > 0) { + console.log(chalk.dim('Global skills:')); + for (const skill of globalSkills) { + printSkill(skill); + } + console.log(); + } + + const enabledCount = skills.filter(s => s.enabled).length; + const disabledCount = skills.length - enabledCount; + + console.log( + chalk.dim( + `${projectSkills.length} project, ${globalSkills.length} global` + + (disabledCount > 0 ? `, ${disabledCount} disabled` : '') + ) + ); + + return 0; + } +} + +function printSkill(skill: { name: string; description: string; enabled: boolean; location: string }) { + const status = skill.enabled ? chalk.green('✓') : chalk.red('○'); + const name = skill.enabled ? skill.name : chalk.dim(skill.name); + const desc = chalk.dim(truncate(skill.description, 50)); + + console.log(` ${status} ${name}`); + if (skill.description) { + console.log(` ${desc}`); + } +} + +function truncate(str: string, maxLen: number): string { + if (str.length <= maxLen) return str; + return str.slice(0, maxLen - 3) + '...'; +} diff --git a/src/commands/read.ts b/src/commands/read.ts new file mode 100644 index 00000000..4ba93437 --- /dev/null +++ b/src/commands/read.ts @@ -0,0 +1,79 @@ +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { getSearchDirs } from '../core/config.js'; +import { findSkill, readSkillContent } from '../core/skills.js'; + +export class ReadCommand extends Command { + static override paths = [['read'], ['r']]; + + static override usage = Command.Usage({ + description: 'Read skill content for AI agent consumption', + examples: [ + ['Read a single skill', '$0 read pdf'], + ['Read multiple skills', '$0 read pdf,xlsx,docx'], + ['Read with verbose output', '$0 read pdf --verbose'], + ], + }); + + skills = Option.String({ required: true }); + + verbose = Option.Boolean('--verbose,-v', false, { + description: 'Show additional information', + }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + + const skillNames = this.skills + .split(',') + .map(s => s.trim()) + .filter(s => s.length > 0); + + if (skillNames.length === 0) { + console.error(chalk.red('No skill names provided')); + return 1; + } + + let exitCode = 0; + + for (const skillName of skillNames) { + const skill = findSkill(skillName, searchDirs); + + if (!skill) { + console.error(chalk.red(`Skill not found: ${skillName}`)); + console.error(chalk.dim('Available directories:')); + searchDirs.forEach(d => console.error(chalk.dim(` - ${d}`))); + exitCode = 1; + continue; + } + + if (!skill.enabled) { + console.error(chalk.yellow(`Skill disabled: ${skillName}`)); + console.error(chalk.dim('Enable with: skillkit enable ' + skillName)); + exitCode = 1; + continue; + } + + const content = readSkillContent(skill.path); + + if (!content) { + console.error(chalk.red(`Could not read SKILL.md for: ${skillName}`)); + exitCode = 1; + continue; + } + + console.log(`Reading: ${skillName}`); + console.log(`Base directory: ${skill.path}`); + console.log(); + console.log(content); + console.log(); + console.log(`Skill read: ${skillName}`); + + if (skillNames.length > 1 && skillName !== skillNames[skillNames.length - 1]) { + console.log('\n---\n'); + } + } + + return exitCode; + } +} diff --git a/src/commands/remove.ts b/src/commands/remove.ts new file mode 100644 index 00000000..c62cbdc8 --- /dev/null +++ b/src/commands/remove.ts @@ -0,0 +1,60 @@ +import { existsSync, rmSync } from 'node:fs'; +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { getSearchDirs } from '../core/config.js'; +import { findSkill } from '../core/skills.js'; + +export class RemoveCommand extends Command { + static override paths = [['remove'], ['rm'], ['uninstall']]; + + static override usage = Command.Usage({ + description: 'Remove installed skills', + examples: [ + ['Remove a skill', '$0 remove pdf'], + ['Remove multiple skills', '$0 remove pdf xlsx docx'], + ['Force removal without confirmation', '$0 remove pdf --force'], + ], + }); + + skills = Option.Rest({ required: 1 }); + + force = Option.Boolean('--force,-f', false, { + description: 'Skip confirmation', + }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + let removed = 0; + let failed = 0; + + for (const skillName of this.skills) { + const skill = findSkill(skillName, searchDirs); + + if (!skill) { + console.log(chalk.yellow(`Skill not found: ${skillName}`)); + continue; + } + + if (!existsSync(skill.path)) { + console.log(chalk.yellow(`Path not found: ${skill.path}`)); + continue; + } + + try { + rmSync(skill.path, { recursive: true, force: true }); + console.log(chalk.green(`Removed: ${skillName}`)); + removed++; + } catch (error) { + console.log(chalk.red(`Failed to remove: ${skillName}`)); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + failed++; + } + } + + if (removed > 0) { + console.log(chalk.dim('\nRun `skillkit sync` to update your agent config')); + } + + return failed > 0 ? 1 : 0; + } +} diff --git a/src/commands/sync.ts b/src/commands/sync.ts new file mode 100644 index 00000000..ba5a36f0 --- /dev/null +++ b/src/commands/sync.ts @@ -0,0 +1,156 @@ +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { dirname } from 'node:path'; +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { getSearchDirs, getAgentConfigPath, loadConfig } from '../core/config.js'; +import { findAllSkills } from '../core/skills.js'; +import { getAdapter, detectAgent } from '../agents/index.js'; +import type { AgentType } from '../core/types.js'; + +export class SyncCommand extends Command { + static override paths = [['sync'], ['s']]; + + static override usage = Command.Usage({ + description: 'Sync skills to agent configuration file', + examples: [ + ['Sync all enabled skills', '$0 sync'], + ['Sync to specific file', '$0 sync --output AGENTS.md'], + ['Sync for specific agent', '$0 sync --agent cursor'], + ['Only sync enabled skills', '$0 sync --enabled-only'], + ], + }); + + output = Option.String('--output,-o', { + description: 'Output file path (default: agent-specific config file)', + }); + + agent = Option.String('--agent,-a', { + description: 'Target agent type (claude-code, cursor, codex, etc.)', + }); + + enabledOnly = Option.Boolean('--enabled-only,-e', true, { + description: 'Only include enabled skills (default: true)', + }); + + yes = Option.Boolean('--yes,-y', false, { + description: 'Skip confirmation prompts', + }); + + async execute(): Promise { + try { + + let agentType: AgentType; + + if (this.agent) { + agentType = this.agent 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); + let skills = findAllSkills(searchDirs); + + if (this.enabledOnly) { + skills = skills.filter(s => s.enabled); + } + + if (skills.length === 0) { + console.log(chalk.yellow('No skills found to sync')); + console.log(chalk.dim('Install skills with: skillkit install ')); + 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(); + + const config = adapter.generateConfig(skills); + + if (!config) { + console.log(chalk.yellow('No configuration generated')); + return 0; + } + + let existingContent = ''; + if (existsSync(outputPath)) { + existingContent = readFileSync(outputPath, 'utf-8'); + } + + const newContent = updateConfigContent(existingContent, config, agentType); + + const dir = dirname(outputPath); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + + writeFileSync(outputPath, newContent, 'utf-8'); + + console.log(chalk.green(`Synced to ${outputPath}`)); + console.log(chalk.dim(`Agent: ${adapter.name}`)); + + return 0; + } catch (error) { + console.error(chalk.red('Sync failed')); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + return 1; + } + } +} + +function updateConfigContent(existing: string, newConfig: string, agentType: AgentType): string { + + const markers: Record = { + 'claude-code': { + start: '', + end: '', + }, + cursor: { + start: '', + end: '', + }, + universal: { + start: '', + end: '', + }, + }; + + const agentMarkers = markers[agentType] || markers.universal; + + const startIdx = existing.indexOf(agentMarkers.start); + const endIdx = existing.indexOf(agentMarkers.end); + + if (startIdx !== -1 && endIdx !== -1) { + + return ( + existing.slice(0, startIdx) + + newConfig.slice(newConfig.indexOf(agentMarkers.start)) + + existing.slice(endIdx + agentMarkers.end.length) + ); + } + + const genericStart = ''; + const genericEnd = ''; + const gStartIdx = existing.indexOf(genericStart); + const gEndIdx = existing.indexOf(genericEnd); + + if (gStartIdx !== -1 && gEndIdx !== -1) { + return ( + existing.slice(0, gStartIdx) + newConfig + existing.slice(gEndIdx + genericEnd.length) + ); + } + + if (existing.trim()) { + return existing + '\n\n' + newConfig; + } + + return newConfig; +} diff --git a/src/commands/update.ts b/src/commands/update.ts new file mode 100644 index 00000000..b23f1c70 --- /dev/null +++ b/src/commands/update.ts @@ -0,0 +1,156 @@ +import { existsSync, rmSync, cpSync } from 'node:fs'; +import { join } from 'node:path'; +import chalk from 'chalk'; +import ora from 'ora'; +import { Command, Option } from 'clipanion'; +import { getSearchDirs, loadSkillMetadata, saveSkillMetadata } from '../core/config.js'; +import { findAllSkills, findSkill } from '../core/skills.js'; +import { detectProvider, isLocalPath } from '../providers/index.js'; + +export class UpdateCommand extends Command { + static override paths = [['update'], ['u']]; + + static override usage = Command.Usage({ + description: 'Update skills from their original sources', + examples: [ + ['Update all skills', '$0 update'], + ['Update specific skills', '$0 update pdf xlsx'], + ['Force update (overwrite local changes)', '$0 update --force'], + ], + }); + + skills = Option.Rest(); + + force = Option.Boolean('--force,-f', false, { + description: 'Force update even if local changes exist', + }); + + async execute(): Promise { + const spinner = ora(); + const searchDirs = getSearchDirs(); + + let skillsToUpdate; + + if (this.skills.length > 0) { + + skillsToUpdate = this.skills + .map(name => findSkill(name, searchDirs)) + .filter((s): s is NonNullable => s !== null); + + const notFound = this.skills.filter(name => !findSkill(name, searchDirs)); + if (notFound.length > 0) { + console.log(chalk.yellow(`Skills not found: ${notFound.join(', ')}`)); + } + } else { + + skillsToUpdate = findAllSkills(searchDirs); + } + + if (skillsToUpdate.length === 0) { + console.log(chalk.yellow('No skills to update')); + return 0; + } + + console.log(chalk.cyan(`Updating ${skillsToUpdate.length} skill(s)...\n`)); + + let updated = 0; + let skipped = 0; + let failed = 0; + + for (const skill of skillsToUpdate) { + const metadata = loadSkillMetadata(skill.path); + + if (!metadata) { + console.log(chalk.dim(`Skipping ${skill.name} (no metadata, reinstall needed)`)); + skipped++; + continue; + } + + spinner.start(`Updating ${skill.name}...`); + + try { + if (isLocalPath(metadata.source)) { + + const localPath = metadata.subpath + ? join(metadata.source, metadata.subpath) + : metadata.source; + + if (!existsSync(localPath)) { + spinner.warn(chalk.yellow(`${skill.name}: local source missing`)); + skipped++; + continue; + } + + const skillMdPath = join(localPath, 'SKILL.md'); + if (!existsSync(skillMdPath)) { + spinner.warn(chalk.yellow(`${skill.name}: no SKILL.md at source`)); + skipped++; + continue; + } + + rmSync(skill.path, { recursive: true, force: true }); + cpSync(localPath, skill.path, { recursive: true, dereference: true }); + + metadata.updatedAt = new Date().toISOString(); + saveSkillMetadata(skill.path, metadata); + + spinner.succeed(chalk.green(`Updated ${skill.name}`)); + updated++; + } else { + + const provider = detectProvider(metadata.source); + + if (!provider) { + spinner.warn(chalk.yellow(`${skill.name}: unknown provider`)); + skipped++; + continue; + } + + const result = await provider.clone(metadata.source, '', { depth: 1 }); + + if (!result.success || !result.path) { + spinner.fail(chalk.red(`${skill.name}: ${result.error || 'clone failed'}`)); + failed++; + continue; + } + + const sourcePath = metadata.subpath + ? join(result.path, metadata.subpath) + : result.path; + + const skillMdPath = join(sourcePath, 'SKILL.md'); + if (!existsSync(skillMdPath)) { + spinner.warn(chalk.yellow(`${skill.name}: no SKILL.md in source`)); + rmSync(result.path, { recursive: true, force: true }); + skipped++; + continue; + } + + rmSync(skill.path, { recursive: true, force: true }); + cpSync(sourcePath, skill.path, { recursive: true, dereference: true }); + + rmSync(result.path, { recursive: true, force: true }); + + metadata.updatedAt = new Date().toISOString(); + saveSkillMetadata(skill.path, metadata); + + spinner.succeed(chalk.green(`Updated ${skill.name}`)); + updated++; + } + } catch (error) { + spinner.fail(chalk.red(`Failed to update ${skill.name}`)); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + failed++; + } + } + + console.log(); + console.log( + chalk.cyan( + `Updated: ${updated}, Skipped: ${skipped}, Failed: ${failed}` + ) + ); + + return failed > 0 ? 1 : 0; + } +} diff --git a/src/commands/validate.ts b/src/commands/validate.ts new file mode 100644 index 00000000..a5e4b962 --- /dev/null +++ b/src/commands/validate.ts @@ -0,0 +1,87 @@ +import { existsSync, readdirSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { validateSkill } from '../core/skills.js'; + +export class ValidateCommand extends Command { + static override paths = [['validate'], ['v']]; + + static override usage = Command.Usage({ + description: 'Validate skill(s) against the Agent Skills specification (agentskills.io)', + examples: [ + ['Validate a skill directory', '$0 validate ./my-skill'], + ['Validate all skills in a directory', '$0 validate ./skills --all'], + ], + }); + + skillPath = Option.String({ required: true }); + + all = Option.Boolean('--all,-a', false, { + description: 'Validate all skills in the directory', + }); + + async execute(): Promise { + const targetPath = this.skillPath; + + if (!existsSync(targetPath)) { + console.error(chalk.red(`Path does not exist: ${targetPath}`)); + return 1; + } + + const skillPaths: string[] = []; + + if (this.all) { + const entries = readdirSync(targetPath, { withFileTypes: true }); + for (const entry of entries) { + if (entry.isDirectory()) { + const skillPath = join(targetPath, entry.name); + if (existsSync(join(skillPath, 'SKILL.md'))) { + skillPaths.push(skillPath); + } + } + } + + if (skillPaths.length === 0) { + console.error(chalk.yellow('No skills found in directory')); + return 1; + } + } else { + skillPaths.push(targetPath); + } + + let hasErrors = false; + + for (const skillPath of skillPaths) { + const skillName = basename(skillPath); + const result = validateSkill(skillPath); + + if (result.valid) { + console.log(chalk.green(`✓ ${skillName}`)); + + if (result.warnings && result.warnings.length > 0) { + result.warnings.forEach(w => { + console.log(chalk.yellow(` ⚠ ${w}`)); + }); + } + } else { + console.log(chalk.red(`✗ ${skillName}`)); + result.errors.forEach(e => { + console.log(chalk.red(` • ${e}`)); + }); + hasErrors = true; + } + } + + console.log(); + + if (hasErrors) { + console.log(chalk.red('Validation failed')); + console.log(chalk.dim('See https://agentskills.io/specification for the complete format')); + return 1; + } + + console.log(chalk.green(`Validated ${skillPaths.length} skill(s) successfully`)); + return 0; + } +} diff --git a/src/core/config.ts b/src/core/config.ts new file mode 100644 index 00000000..bc10e830 --- /dev/null +++ b/src/core/config.ts @@ -0,0 +1,157 @@ +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { homedir } from 'node:os'; +import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'; +import { SkillkitConfig, type AgentType, type SkillMetadata } from './types.js'; +import { getAdapter, detectAgent } from '../agents/index.js'; + +const CONFIG_FILE = 'skillkit.yaml'; +const METADATA_FILE = '.skillkit.json'; + +export function getProjectConfigPath(): string { + return join(process.cwd(), CONFIG_FILE); +} + +export function getGlobalConfigPath(): string { + return join(homedir(), '.config', 'skillkit', CONFIG_FILE); +} + +export function loadConfig(): SkillkitConfig { + const projectPath = getProjectConfigPath(); + const globalPath = getGlobalConfigPath(); + + if (existsSync(projectPath)) { + try { + const content = readFileSync(projectPath, 'utf-8'); + const data = parseYaml(content); + const parsed = SkillkitConfig.safeParse(data); + if (parsed.success) { + return parsed.data; + } + } catch { + + } + } + + if (existsSync(globalPath)) { + try { + const content = readFileSync(globalPath, 'utf-8'); + const data = parseYaml(content); + const parsed = SkillkitConfig.safeParse(data); + if (parsed.success) { + return parsed.data; + } + } catch { + + } + } + + return { + version: 1, + agent: 'universal', + autoSync: true, + }; +} + +export function saveConfig(config: SkillkitConfig, global = false): void { + const configPath = global ? getGlobalConfigPath() : getProjectConfigPath(); + const dir = dirname(configPath); + + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + + const content = stringifyYaml(config); + writeFileSync(configPath, content, 'utf-8'); +} + +export function getSearchDirs(agentType?: AgentType): string[] { + const type = agentType || loadConfig().agent; + const adapter = getAdapter(type); + const dirs: string[] = []; + + dirs.push(join(process.cwd(), adapter.skillsDir)); + + dirs.push(join(process.cwd(), '.agent', 'skills')); + + dirs.push(join(homedir(), adapter.skillsDir)); + + dirs.push(join(homedir(), '.agent', 'skills')); + + return dirs; +} + +export function getInstallDir(global = false, agentType?: AgentType): string { + const type = agentType || loadConfig().agent; + const adapter = getAdapter(type); + + if (global) { + return join(homedir(), adapter.skillsDir); + } + + return join(process.cwd(), adapter.skillsDir); +} + +export function getAgentConfigPath(agentType?: AgentType): string { + const type = agentType || loadConfig().agent; + const adapter = getAdapter(type); + + return join(process.cwd(), adapter.configFile); +} + +export function saveSkillMetadata(skillPath: string, metadata: SkillMetadata): void { + const metadataPath = join(skillPath, METADATA_FILE); + writeFileSync(metadataPath, JSON.stringify(metadata, null, 2), 'utf-8'); +} + +export function loadSkillMetadata(skillPath: string): SkillMetadata | null { + const metadataPath = join(skillPath, METADATA_FILE); + + if (!existsSync(metadataPath)) { + return null; + } + + try { + const content = readFileSync(metadataPath, 'utf-8'); + return JSON.parse(content) as SkillMetadata; + } catch { + return null; + } +} + +export function setSkillEnabled(skillPath: string, enabled: boolean): boolean { + const metadata = loadSkillMetadata(skillPath); + + if (!metadata) { + return false; + } + + metadata.enabled = enabled; + metadata.updatedAt = new Date().toISOString(); + saveSkillMetadata(skillPath, metadata); + + return true; +} + +export async function initProject(agentType?: AgentType): Promise { + + const type = agentType || (await detectAgent()); + const adapter = getAdapter(type); + + const skillsDir = join(process.cwd(), adapter.skillsDir); + if (!existsSync(skillsDir)) { + mkdirSync(skillsDir, { recursive: true }); + } + + const config: SkillkitConfig = { + version: 1, + agent: type, + autoSync: true, + }; + saveConfig(config); + + const agentConfigPath = join(process.cwd(), adapter.configFile); + if (!existsSync(agentConfigPath)) { + writeFileSync(agentConfigPath, `# ${adapter.name} Configuration\n\n`, 'utf-8'); + } +} diff --git a/src/core/index.ts b/src/core/index.ts new file mode 100644 index 00000000..a19e9482 --- /dev/null +++ b/src/core/index.ts @@ -0,0 +1,3 @@ +export * from './types.js'; +export * from './skills.js'; +export * from './config.js'; diff --git a/src/core/skills.ts b/src/core/skills.ts new file mode 100644 index 00000000..025f3206 --- /dev/null +++ b/src/core/skills.ts @@ -0,0 +1,222 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import { parse as parseYaml } from 'yaml'; +import { SkillFrontmatter, SkillMetadata, type Skill, type SkillLocation } from './types.js'; + +export function discoverSkills(dir: string): Skill[] { + const skills: Skill[] = []; + + if (!existsSync(dir)) { + return skills; + } + + const entries = readdirSync(dir, { withFileTypes: true }); + + for (const entry of entries) { + if (!entry.isDirectory()) continue; + + const skillPath = join(dir, entry.name); + const skillMdPath = join(skillPath, 'SKILL.md'); + + if (existsSync(skillMdPath)) { + const skill = parseSkill(skillPath); + if (skill) { + skills.push(skill); + } + } + } + + return skills; +} + +export function parseSkill(skillPath: string, location: SkillLocation = 'project'): Skill | null { + const skillMdPath = join(skillPath, 'SKILL.md'); + + if (!existsSync(skillMdPath)) { + return null; + } + + try { + const content = readFileSync(skillMdPath, 'utf-8'); + const frontmatter = extractFrontmatter(content); + + if (!frontmatter) { + const name = basename(skillPath); + return { + name, + description: 'No description available', + path: skillPath, + location, + enabled: true, + }; + } + + const parsed = SkillFrontmatter.safeParse(frontmatter); + + if (!parsed.success) { + return { + name: (frontmatter.name as string) || basename(skillPath), + description: (frontmatter.description as string) || 'No description available', + path: skillPath, + location, + enabled: true, + }; + } + + const metadata = loadMetadata(skillPath); + + return { + name: parsed.data.name, + description: parsed.data.description, + path: skillPath, + location, + metadata: metadata ?? undefined, + enabled: metadata?.enabled ?? true, + }; + } catch { + return null; + } +} + +export function extractFrontmatter(content: string): Record | null { + const match = content.match(/^---\s*\n([\s\S]*?)\n---/); + + if (!match) { + return null; + } + + try { + return parseYaml(match[1]) as Record; + } catch { + return null; + } +} + +export function extractField(content: string, field: string): string | null { + const frontmatter = extractFrontmatter(content); + if (!frontmatter || !(field in frontmatter)) { + return null; + } + + const value = frontmatter[field]; + return typeof value === 'string' ? value : null; +} + +export function loadMetadata(skillPath: string): SkillMetadata | null { + const metadataPath = join(skillPath, '.skillkit.json'); + + if (!existsSync(metadataPath)) { + return null; + } + + try { + const content = readFileSync(metadataPath, 'utf-8'); + const data = JSON.parse(content); + const parsed = SkillMetadata.safeParse(data); + + return parsed.success ? parsed.data : null; + } catch { + return null; + } +} + +export function readSkillContent(skillPath: string): string | null { + const skillMdPath = join(skillPath, 'SKILL.md'); + + if (!existsSync(skillMdPath)) { + return null; + } + + try { + return readFileSync(skillMdPath, 'utf-8'); + } catch { + return null; + } +} + +export function findSkill(name: string, searchDirs: string[]): Skill | null { + for (const dir of searchDirs) { + if (!existsSync(dir)) continue; + + const skillPath = join(dir, name); + if (existsSync(skillPath)) { + const location: SkillLocation = dir.includes(process.cwd()) ? 'project' : 'global'; + return parseSkill(skillPath, location); + } + } + + return null; +} + +export function findAllSkills(searchDirs: string[]): Skill[] { + const skills: Skill[] = []; + const seen = new Set(); + + for (const dir of searchDirs) { + if (!existsSync(dir)) continue; + + const location: SkillLocation = dir.includes(process.cwd()) ? 'project' : 'global'; + const discovered = discoverSkills(dir); + + for (const skill of discovered) { + if (!seen.has(skill.name)) { + seen.add(skill.name); + skills.push({ ...skill, location }); + } + } + } + + return skills; +} + +export function validateSkill(skillPath: string): { valid: boolean; errors: string[]; warnings?: string[] } { + const errors: string[] = []; + const warnings: string[] = []; + const dirName = basename(skillPath); + + const skillMdPath = join(skillPath, 'SKILL.md'); + if (!existsSync(skillMdPath)) { + errors.push('Missing SKILL.md file'); + return { valid: false, errors }; + } + + const content = readFileSync(skillMdPath, 'utf-8'); + const frontmatter = extractFrontmatter(content); + + if (!frontmatter) { + errors.push('Missing YAML frontmatter in SKILL.md'); + return { valid: false, errors }; + } + + const parsed = SkillFrontmatter.safeParse(frontmatter); + if (!parsed.success) { + for (const issue of parsed.error.issues) { + errors.push(`${issue.path.join('.') || 'frontmatter'}: ${issue.message}`); + } + } + + if (parsed.success) { + const data = parsed.data; + + if (data.name !== dirName) { + warnings.push(`name "${data.name}" does not match directory name "${dirName}"`); + } + + if (data.description && data.description.length < 50) { + warnings.push('description is short; consider describing what the skill does AND when to use it'); + } + } + + const bodyContent = content.replace(/^---[\s\S]*?---\s*/, ''); + const lineCount = bodyContent.split('\n').length; + if (lineCount > 500) { + warnings.push(`SKILL.md has ${lineCount} lines; consider moving detailed content to references/`); + } + + return { valid: errors.length === 0, errors, warnings }; +} + +export function isPathInside(child: string, parent: string): boolean { + const relative = child.replace(parent, ''); + return !relative.startsWith('..') && !relative.includes('/..'); +} diff --git a/src/core/types.ts b/src/core/types.ts new file mode 100644 index 00000000..b0bc7eb0 --- /dev/null +++ b/src/core/types.ts @@ -0,0 +1,121 @@ +import { z } from 'zod'; + +export const AgentType = z.enum([ + 'claude-code', + 'codex', + 'cursor', + 'antigravity', + 'opencode', + 'gemini-cli', + 'universal', +]); +export type AgentType = z.infer; + +export const GitProvider = z.enum(['github', 'gitlab', 'bitbucket', 'local']); +export type GitProvider = z.infer; + +export const SkillFrontmatter = z.object({ + name: z.string() + .min(1) + .max(64) + .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Skill name must be lowercase alphanumeric with hyphens, no leading/trailing/consecutive hyphens'), + description: z.string().min(1).max(1024), + license: z.string().optional(), + compatibility: z.string().max(500).optional(), + metadata: z.record(z.string()).optional(), + 'allowed-tools': z.string().optional(), + version: z.string().optional(), + author: z.string().optional(), + tags: z.array(z.string()).optional(), + agents: z.array(AgentType).optional(), +}); +export type SkillFrontmatter = z.infer; + +export const SkillMetadata = z.object({ + name: z.string(), + description: z.string(), + source: z.string(), + sourceType: GitProvider, + subpath: z.string().optional(), + installedAt: z.string().datetime(), + updatedAt: z.string().datetime().optional(), + enabled: z.boolean().default(true), + version: z.string().optional(), + checksum: z.string().optional(), +}); +export type SkillMetadata = z.infer; + +export const SkillLocation = z.enum(['project', 'global']); +export type SkillLocation = z.infer; + +export const Skill = z.object({ + name: z.string(), + description: z.string(), + path: z.string(), + location: SkillLocation, + metadata: SkillMetadata.optional(), + enabled: z.boolean().default(true), +}); +export type Skill = z.infer; + +export const SkillkitConfig = z.object({ + version: z.literal(1), + agent: AgentType.default('universal'), + skillsDir: z.string().optional(), + enabledSkills: z.array(z.string()).optional(), + disabledSkills: z.array(z.string()).optional(), + autoSync: z.boolean().default(true), +}); +export type SkillkitConfig = z.infer; + +export interface InstallOptions { + global?: boolean; + skills?: string[]; + provider?: GitProvider; + yes?: boolean; + force?: boolean; +} + +export interface SyncOptions { + output?: string; + agent?: AgentType; + yes?: boolean; + enabledOnly?: boolean; +} + +export interface UpdateOptions { + skills?: string[]; + all?: boolean; + force?: boolean; +} + +export interface RegistrySkill { + name: string; + description: string; + source: string; + provider: GitProvider; + downloads?: number; + stars?: number; + tags?: string[]; +} + +export interface DiscoveredSkill { + name: string; + dirName: string; + path: string; +} + +export interface CloneResult { + success: boolean; + path?: string; + tempRoot?: string; + error?: string; + skills?: string[]; + discoveredSkills?: DiscoveredSkill[]; +} + +export interface CommandResult { + success: boolean; + message: string; + data?: unknown; +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 00000000..40d03545 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,27 @@ +export * from './core/types.js'; +export * from './core/skills.js'; +export * from './core/config.js'; + +export * from './agents/index.js'; + +export * from './providers/index.js'; + +export { + findSkill, + findAllSkills, + discoverSkills, + readSkillContent, + validateSkill, +} from './core/skills.js'; + +export { + loadConfig, + saveConfig, + getSearchDirs, + getInstallDir, + initProject, +} from './core/config.js'; + +export { detectAgent, getAdapter, getAllAdapters } from './agents/index.js'; + +export { detectProvider, parseSource, getAllProviders } from './providers/index.js'; diff --git a/src/providers/base.ts b/src/providers/base.ts new file mode 100644 index 00000000..6ca8508a --- /dev/null +++ b/src/providers/base.ts @@ -0,0 +1,61 @@ +import type { GitProvider, CloneResult } from '../core/types.js'; + +export interface GitProviderAdapter { + + readonly type: GitProvider; + + readonly name: string; + + readonly baseUrl: string; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null; + + matches(source: string): boolean; + + getCloneUrl(owner: string, repo: string): string; + + getSshUrl(owner: string, repo: string): string; + + clone(source: string, targetDir: string, options?: CloneOptions): Promise; +} + +export interface CloneOptions { + depth?: number; + branch?: string; + ssh?: boolean; +} + +export function parseShorthand(source: string): { owner: string; repo: string; subpath?: string } | null { + + const cleaned = source.replace(/^\/+|\/+$/g, ''); + const parts = cleaned.split('/'); + + if (parts.length < 2) { + return null; + } + + const owner = parts[0]; + const repo = parts[1]; + const subpath = parts.length > 2 ? parts.slice(2).join('/') : undefined; + + return { owner, repo, subpath }; +} + +export function isLocalPath(source: string): boolean { + return ( + source.startsWith('/') || + source.startsWith('./') || + source.startsWith('../') || + source.startsWith('~/') || + source.startsWith('.') + ); +} + +export function isGitUrl(source: string): boolean { + return ( + source.startsWith('git@') || + source.startsWith('https://') || + source.startsWith('http://') || + source.startsWith('ssh://') + ); +} diff --git a/src/providers/bitbucket.ts b/src/providers/bitbucket.ts new file mode 100644 index 00000000..436760c1 --- /dev/null +++ b/src/providers/bitbucket.ts @@ -0,0 +1,107 @@ +import { execSync } from 'node:child_process'; +import { existsSync, rmSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import { tmpdir } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import type { GitProviderAdapter, CloneOptions } from './base.js'; +import { parseShorthand } from './base.js'; +import type { GitProvider, CloneResult } from '../core/types.js'; +import { discoverSkills } from '../core/skills.js'; + +export class BitbucketProvider implements GitProviderAdapter { + readonly type: GitProvider = 'bitbucket'; + readonly name = 'Bitbucket'; + readonly baseUrl = 'https://bitbucket.org'; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null { + + if (source.startsWith('https://bitbucket.org/')) { + const path = source.replace('https://bitbucket.org/', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('git@bitbucket.org:')) { + const path = source.replace('git@bitbucket.org:', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('bitbucket:')) { + return parseShorthand(source.replace('bitbucket:', '')); + } + + if (source.startsWith('bitbucket.org/')) { + return parseShorthand(source.replace('bitbucket.org/', '')); + } + + return null; + } + + matches(source: string): boolean { + return ( + source.startsWith('https://bitbucket.org/') || + source.startsWith('git@bitbucket.org:') || + source.startsWith('bitbucket:') || + source.startsWith('bitbucket.org/') + ); + } + + getCloneUrl(owner: string, repo: string): string { + return `https://bitbucket.org/${owner}/${repo}.git`; + } + + getSshUrl(owner: string, repo: string): string { + return `git@bitbucket.org:${owner}/${repo}.git`; + } + + async clone(source: string, _targetDir: string, options: CloneOptions = {}): Promise { + const parsed = this.parseSource(source); + if (!parsed) { + return { success: false, error: `Invalid Bitbucket source: ${source}` }; + } + + const { owner, repo, subpath } = parsed; + const cloneUrl = options.ssh ? this.getSshUrl(owner, repo) : this.getCloneUrl(owner, repo); + + const tempDir = join(tmpdir(), `skillkit-${randomUUID()}`); + + try { + + const args = ['clone']; + if (options.depth) { + args.push('--depth', String(options.depth)); + } + if (options.branch) { + args.push('--branch', options.branch); + } + args.push(cloneUrl, tempDir); + + execSync(`git ${args.join(' ')}`, { + stdio: ['pipe', 'pipe', 'pipe'], + encoding: 'utf-8', + }); + + const searchDir = subpath ? join(tempDir, subpath) : tempDir; + const skills = discoverSkills(searchDir); + + return { + success: true, + path: searchDir, + tempRoot: tempDir, + skills: skills.map(s => s.name), + discoveredSkills: skills.map(s => ({ + name: s.name, + dirName: basename(s.path), + path: s.path, + })), + }; + } catch (error) { + + if (existsSync(tempDir)) { + rmSync(tempDir, { recursive: true, force: true }); + } + + const message = error instanceof Error ? error.message : String(error); + return { success: false, error: `Failed to clone: ${message}` }; + } + } +} diff --git a/src/providers/github.ts b/src/providers/github.ts new file mode 100644 index 00000000..0b7651c8 --- /dev/null +++ b/src/providers/github.ts @@ -0,0 +1,103 @@ +import { execSync } from 'node:child_process'; +import { existsSync, rmSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import { tmpdir } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import type { GitProviderAdapter, CloneOptions } from './base.js'; +import { parseShorthand, isGitUrl } from './base.js'; +import type { GitProvider, CloneResult } from '../core/types.js'; +import { discoverSkills } from '../core/skills.js'; + +export class GitHubProvider implements GitProviderAdapter { + readonly type: GitProvider = 'github'; + readonly name = 'GitHub'; + readonly baseUrl = 'https://github.com'; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null { + + if (source.startsWith('https://github.com/')) { + const path = source.replace('https://github.com/', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('git@github.com:')) { + const path = source.replace('git@github.com:', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (!isGitUrl(source) && !source.includes(':')) { + return parseShorthand(source); + } + + return null; + } + + matches(source: string): boolean { + return ( + source.startsWith('https://github.com/') || + source.startsWith('git@github.com:') || + + (!isGitUrl(source) && !source.includes(':') && source.includes('/')) + ); + } + + getCloneUrl(owner: string, repo: string): string { + return `https://github.com/${owner}/${repo}.git`; + } + + getSshUrl(owner: string, repo: string): string { + return `git@github.com:${owner}/${repo}.git`; + } + + async clone(source: string, _targetDir: string, options: CloneOptions = {}): Promise { + const parsed = this.parseSource(source); + if (!parsed) { + return { success: false, error: `Invalid GitHub source: ${source}` }; + } + + const { owner, repo, subpath } = parsed; + const cloneUrl = options.ssh ? this.getSshUrl(owner, repo) : this.getCloneUrl(owner, repo); + + const tempDir = join(tmpdir(), `skillkit-${randomUUID()}`); + + try { + + const args = ['clone']; + if (options.depth) { + args.push('--depth', String(options.depth)); + } + if (options.branch) { + args.push('--branch', options.branch); + } + args.push(cloneUrl, tempDir); + + execSync(`git ${args.join(' ')}`, { + stdio: ['pipe', 'pipe', 'pipe'], + encoding: 'utf-8', + }); + + const searchDir = subpath ? join(tempDir, subpath) : tempDir; + const skills = discoverSkills(searchDir); + + return { + success: true, + path: searchDir, + tempRoot: tempDir, + skills: skills.map(s => s.name), + discoveredSkills: skills.map(s => ({ + name: s.name, + dirName: basename(s.path), + path: s.path, + })), + }; + } catch (error) { + + if (existsSync(tempDir)) { + rmSync(tempDir, { recursive: true, force: true }); + } + + const message = error instanceof Error ? error.message : String(error); + return { success: false, error: `Failed to clone: ${message}` }; + } + } +} diff --git a/src/providers/gitlab.ts b/src/providers/gitlab.ts new file mode 100644 index 00000000..735ac496 --- /dev/null +++ b/src/providers/gitlab.ts @@ -0,0 +1,107 @@ +import { execSync } from 'node:child_process'; +import { existsSync, rmSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import { tmpdir } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import type { GitProviderAdapter, CloneOptions } from './base.js'; +import { parseShorthand } from './base.js'; +import type { GitProvider, CloneResult } from '../core/types.js'; +import { discoverSkills } from '../core/skills.js'; + +export class GitLabProvider implements GitProviderAdapter { + readonly type: GitProvider = 'gitlab'; + readonly name = 'GitLab'; + readonly baseUrl = 'https://gitlab.com'; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null { + + if (source.startsWith('https://gitlab.com/')) { + const path = source.replace('https://gitlab.com/', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('git@gitlab.com:')) { + const path = source.replace('git@gitlab.com:', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('gitlab:')) { + return parseShorthand(source.replace('gitlab:', '')); + } + + if (source.startsWith('gitlab.com/')) { + return parseShorthand(source.replace('gitlab.com/', '')); + } + + return null; + } + + matches(source: string): boolean { + return ( + source.startsWith('https://gitlab.com/') || + source.startsWith('git@gitlab.com:') || + source.startsWith('gitlab:') || + source.startsWith('gitlab.com/') + ); + } + + getCloneUrl(owner: string, repo: string): string { + return `https://gitlab.com/${owner}/${repo}.git`; + } + + getSshUrl(owner: string, repo: string): string { + return `git@gitlab.com:${owner}/${repo}.git`; + } + + async clone(source: string, _targetDir: string, options: CloneOptions = {}): Promise { + const parsed = this.parseSource(source); + if (!parsed) { + return { success: false, error: `Invalid GitLab source: ${source}` }; + } + + const { owner, repo, subpath } = parsed; + const cloneUrl = options.ssh ? this.getSshUrl(owner, repo) : this.getCloneUrl(owner, repo); + + const tempDir = join(tmpdir(), `skillkit-${randomUUID()}`); + + try { + + const args = ['clone']; + if (options.depth) { + args.push('--depth', String(options.depth)); + } + if (options.branch) { + args.push('--branch', options.branch); + } + args.push(cloneUrl, tempDir); + + execSync(`git ${args.join(' ')}`, { + stdio: ['pipe', 'pipe', 'pipe'], + encoding: 'utf-8', + }); + + const searchDir = subpath ? join(tempDir, subpath) : tempDir; + const skills = discoverSkills(searchDir); + + return { + success: true, + path: searchDir, + tempRoot: tempDir, + skills: skills.map(s => s.name), + discoveredSkills: skills.map(s => ({ + name: s.name, + dirName: basename(s.path), + path: s.path, + })), + }; + } catch (error) { + + if (existsSync(tempDir)) { + rmSync(tempDir, { recursive: true, force: true }); + } + + const message = error instanceof Error ? error.message : String(error); + return { success: false, error: `Failed to clone: ${message}` }; + } + } +} diff --git a/src/providers/index.ts b/src/providers/index.ts new file mode 100644 index 00000000..9f08ad8a --- /dev/null +++ b/src/providers/index.ts @@ -0,0 +1,48 @@ +import type { GitProviderAdapter } from './base.js'; +import type { GitProvider } from '../core/types.js'; +import { GitHubProvider } from './github.js'; +import { GitLabProvider } from './gitlab.js'; +import { BitbucketProvider } from './bitbucket.js'; +import { LocalProvider } from './local.js'; + +export * from './base.js'; +export * from './github.js'; +export * from './gitlab.js'; +export * from './bitbucket.js'; +export * from './local.js'; + +const providers: GitProviderAdapter[] = [ + new LocalProvider(), + new GitLabProvider(), + new BitbucketProvider(), + new GitHubProvider(), +]; + +export function getProvider(type: GitProvider): GitProviderAdapter | undefined { + return providers.find(p => p.type === type); +} + +export function getAllProviders(): GitProviderAdapter[] { + return providers; +} + +export function detectProvider(source: string): GitProviderAdapter | undefined { + return providers.find(p => p.matches(source)); +} + +export function parseSource(source: string): { + provider: GitProviderAdapter; + owner: string; + repo: string; + subpath?: string; +} | null { + for (const provider of providers) { + if (provider.matches(source)) { + const parsed = provider.parseSource(source); + if (parsed) { + return { provider, ...parsed }; + } + } + } + return null; +} diff --git a/src/providers/local.ts b/src/providers/local.ts new file mode 100644 index 00000000..fa4b6a56 --- /dev/null +++ b/src/providers/local.ts @@ -0,0 +1,85 @@ +import { existsSync, statSync, realpathSync } from 'node:fs'; +import { join, resolve, basename } from 'node:path'; +import { homedir } from 'node:os'; +import type { GitProviderAdapter, CloneOptions } from './base.js'; +import { isLocalPath } from './base.js'; +import type { GitProvider, CloneResult } from '../core/types.js'; +import { discoverSkills } from '../core/skills.js'; + +export class LocalProvider implements GitProviderAdapter { + readonly type: GitProvider = 'local'; + readonly name = 'Local Filesystem'; + readonly baseUrl = ''; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null { + if (!isLocalPath(source)) { + return null; + } + + let expandedPath = source; + if (source.startsWith('~/')) { + expandedPath = join(homedir(), source.slice(2)); + } + + const absolutePath = resolve(expandedPath); + + const dirName = basename(absolutePath); + + return { + owner: 'local', + repo: dirName, + subpath: absolutePath, + }; + } + + matches(source: string): boolean { + return isLocalPath(source); + } + + getCloneUrl(_owner: string, _repo: string): string { + return ''; + } + + getSshUrl(_owner: string, _repo: string): string { + return ''; + } + + async clone(source: string, _targetDir: string, _options: CloneOptions = {}): Promise { + const parsed = this.parseSource(source); + if (!parsed || !parsed.subpath) { + return { success: false, error: `Invalid local path: ${source}` }; + } + + const sourcePath = parsed.subpath; + + if (!existsSync(sourcePath)) { + return { success: false, error: `Path does not exist: ${sourcePath}` }; + } + + const stats = statSync(sourcePath); + if (!stats.isDirectory()) { + return { success: false, error: `Path is not a directory: ${sourcePath}` }; + } + + try { + + let actualPath = sourcePath; + try { + actualPath = realpathSync(sourcePath); + } catch { + + } + + const skills = discoverSkills(actualPath); + + return { + success: true, + path: actualPath, + skills: skills.map(s => s.name), + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { success: false, error: `Failed to process local path: ${message}` }; + } + } +} diff --git a/tests/agents.test.ts b/tests/agents.test.ts new file mode 100644 index 00000000..3c6293ff --- /dev/null +++ b/tests/agents.test.ts @@ -0,0 +1,166 @@ +import { describe, it, expect } from 'vitest'; +import { + getAdapter, + getAllAdapters, + getSkillsDir, + getConfigFile, +} from '../src/agents/index.js'; +import type { Skill } from '../src/core/types.js'; + +describe('agents', () => { + const mockSkills: Skill[] = [ + { + name: 'pdf', + description: 'PDF manipulation toolkit', + path: '/path/to/pdf', + location: 'project', + enabled: true, + }, + { + name: 'xlsx', + description: 'Excel file processing', + path: '/path/to/xlsx', + location: 'global', + enabled: true, + }, + ]; + + describe('getAdapter', () => { + it('should return adapter for claude-code', () => { + const adapter = getAdapter('claude-code'); + expect(adapter.type).toBe('claude-code'); + expect(adapter.name).toBe('Claude Code'); + expect(adapter.skillsDir).toBe('.claude/skills'); + expect(adapter.configFile).toBe('AGENTS.md'); + }); + + it('should return adapter for cursor', () => { + const adapter = getAdapter('cursor'); + expect(adapter.type).toBe('cursor'); + expect(adapter.name).toBe('Cursor'); + expect(adapter.skillsDir).toBe('.cursor/skills'); + expect(adapter.configFile).toBe('.cursorrules'); + }); + + it('should return adapter for codex', () => { + const adapter = getAdapter('codex'); + expect(adapter.type).toBe('codex'); + expect(adapter.name).toBe('OpenAI Codex CLI'); + }); + + it('should return adapter for gemini-cli', () => { + const adapter = getAdapter('gemini-cli'); + expect(adapter.type).toBe('gemini-cli'); + expect(adapter.name).toBe('Gemini CLI'); + }); + + it('should return adapter for opencode', () => { + const adapter = getAdapter('opencode'); + expect(adapter.type).toBe('opencode'); + expect(adapter.name).toBe('OpenCode'); + }); + + it('should return adapter for antigravity', () => { + const adapter = getAdapter('antigravity'); + expect(adapter.type).toBe('antigravity'); + expect(adapter.name).toBe('Antigravity'); + }); + + it('should return adapter for universal', () => { + const adapter = getAdapter('universal'); + expect(adapter.type).toBe('universal'); + expect(adapter.name).toBe('Universal (Any Agent)'); + }); + }); + + describe('getAllAdapters', () => { + it('should return all adapters', () => { + const adapters = getAllAdapters(); + expect(adapters.length).toBeGreaterThanOrEqual(7); + expect(adapters.map(a => a.type)).toContain('claude-code'); + expect(adapters.map(a => a.type)).toContain('cursor'); + expect(adapters.map(a => a.type)).toContain('universal'); + }); + }); + + describe('generateConfig', () => { + it('should generate claude-code config with XML', () => { + const adapter = getAdapter('claude-code'); + const config = adapter.generateConfig(mockSkills); + + expect(config).toContain('pdf'); + expect(config).toContain('xlsx'); + expect(config).toContain('SKILLS_TABLE_START'); + }); + + it('should generate cursor config with markdown', () => { + const adapter = getAdapter('cursor'); + const config = adapter.generateConfig(mockSkills); + + expect(config).toContain('# Skills System'); + expect(config).toContain('**pdf**'); + expect(config).toContain('**xlsx**'); + }); + + it('should generate universal config', () => { + const adapter = getAdapter('universal'); + const config = adapter.generateConfig(mockSkills); + + expect(config).toContain('SKILLKIT_SKILLS_START'); + expect(config).toContain(''); + }); + + it('should return empty string for no skills', () => { + const adapter = getAdapter('claude-code'); + const config = adapter.generateConfig([]); + + expect(config).toBe(''); + }); + + it('should filter disabled skills', () => { + const skillsWithDisabled: Skill[] = [ + { ...mockSkills[0], enabled: false }, + mockSkills[1], + ]; + + const adapter = getAdapter('claude-code'); + const config = adapter.generateConfig(skillsWithDisabled); + + expect(config).not.toContain('pdf'); + expect(config).toContain('xlsx'); + }); + }); + + describe('parseConfig', () => { + it('should parse skill names from XML config', () => { + const adapter = getAdapter('claude-code'); + const config = adapter.generateConfig(mockSkills); + const names = adapter.parseConfig(config); + + expect(names).toContain('pdf'); + expect(names).toContain('xlsx'); + }); + }); + + describe('getInvokeCommand', () => { + it('should return correct invoke command', () => { + const adapter = getAdapter('claude-code'); + expect(adapter.getInvokeCommand('pdf')).toBe('skillkit read pdf'); + }); + }); + + describe('utility functions', () => { + it('getSkillsDir should return correct directory', () => { + expect(getSkillsDir('claude-code')).toBe('.claude/skills'); + expect(getSkillsDir('cursor')).toBe('.cursor/skills'); + expect(getSkillsDir('universal')).toBe('.agent/skills'); + }); + + it('getConfigFile should return correct file', () => { + expect(getConfigFile('claude-code')).toBe('AGENTS.md'); + expect(getConfigFile('cursor')).toBe('.cursorrules'); + expect(getConfigFile('universal')).toBe('AGENTS.md'); + }); + }); +}); diff --git a/tests/providers.test.ts b/tests/providers.test.ts new file mode 100644 index 00000000..e4fa9085 --- /dev/null +++ b/tests/providers.test.ts @@ -0,0 +1,151 @@ +import { describe, it, expect } from 'vitest'; +import { GitHubProvider } from '../src/providers/github.js'; +import { GitLabProvider } from '../src/providers/gitlab.js'; +import { BitbucketProvider } from '../src/providers/bitbucket.js'; +import { LocalProvider } from '../src/providers/local.js'; +import { detectProvider, parseSource, isLocalPath, isGitUrl } from '../src/providers/index.js'; + +describe('providers', () => { + describe('GitHubProvider', () => { + const provider = new GitHubProvider(); + + it('should match GitHub URLs', () => { + expect(provider.matches('https://github.com/owner/repo')).toBe(true); + expect(provider.matches('git@github.com:owner/repo')).toBe(true); + expect(provider.matches('owner/repo')).toBe(true); + }); + + it('should not match other URLs', () => { + expect(provider.matches('https://gitlab.com/owner/repo')).toBe(false); + expect(provider.matches('gitlab:owner/repo')).toBe(false); + }); + + it('should parse GitHub URLs', () => { + expect(provider.parseSource('owner/repo')).toEqual({ + owner: 'owner', + repo: 'repo', + subpath: undefined, + }); + + expect(provider.parseSource('owner/repo/subdir')).toEqual({ + owner: 'owner', + repo: 'repo', + subpath: 'subdir', + }); + + expect(provider.parseSource('https://github.com/owner/repo')).toEqual({ + owner: 'owner', + repo: 'repo', + subpath: undefined, + }); + }); + + it('should generate correct clone URLs', () => { + expect(provider.getCloneUrl('owner', 'repo')).toBe('https://github.com/owner/repo.git'); + expect(provider.getSshUrl('owner', 'repo')).toBe('git@github.com:owner/repo.git'); + }); + }); + + describe('GitLabProvider', () => { + const provider = new GitLabProvider(); + + it('should match GitLab URLs', () => { + expect(provider.matches('https://gitlab.com/owner/repo')).toBe(true); + expect(provider.matches('git@gitlab.com:owner/repo')).toBe(true); + expect(provider.matches('gitlab:owner/repo')).toBe(true); + expect(provider.matches('gitlab.com/owner/repo')).toBe(true); + }); + + it('should not match other URLs', () => { + expect(provider.matches('https://github.com/owner/repo')).toBe(false); + expect(provider.matches('owner/repo')).toBe(false); + }); + + it('should parse GitLab URLs', () => { + expect(provider.parseSource('gitlab:owner/repo')).toEqual({ + owner: 'owner', + repo: 'repo', + subpath: undefined, + }); + + expect(provider.parseSource('https://gitlab.com/owner/repo')).toEqual({ + owner: 'owner', + repo: 'repo', + subpath: undefined, + }); + }); + }); + + describe('BitbucketProvider', () => { + const provider = new BitbucketProvider(); + + it('should match Bitbucket URLs', () => { + expect(provider.matches('https://bitbucket.org/owner/repo')).toBe(true); + expect(provider.matches('git@bitbucket.org:owner/repo')).toBe(true); + expect(provider.matches('bitbucket:owner/repo')).toBe(true); + }); + + it('should parse Bitbucket URLs', () => { + expect(provider.parseSource('bitbucket:owner/repo')).toEqual({ + owner: 'owner', + repo: 'repo', + subpath: undefined, + }); + }); + }); + + describe('LocalProvider', () => { + const provider = new LocalProvider(); + + it('should match local paths', () => { + expect(provider.matches('./local')).toBe(true); + expect(provider.matches('../parent')).toBe(true); + expect(provider.matches('/absolute/path')).toBe(true); + expect(provider.matches('~/home/path')).toBe(true); + }); + + it('should not match URLs', () => { + expect(provider.matches('https://github.com/owner/repo')).toBe(false); + expect(provider.matches('owner/repo')).toBe(false); + }); + }); + + describe('detectProvider', () => { + it('should detect GitHub', () => { + const provider = detectProvider('owner/repo'); + expect(provider?.type).toBe('github'); + }); + + it('should detect GitLab', () => { + const provider = detectProvider('gitlab:owner/repo'); + expect(provider?.type).toBe('gitlab'); + }); + + it('should detect Bitbucket', () => { + const provider = detectProvider('bitbucket:owner/repo'); + expect(provider?.type).toBe('bitbucket'); + }); + + it('should detect local paths', () => { + const provider = detectProvider('./local-path'); + expect(provider?.type).toBe('local'); + }); + }); + + describe('utility functions', () => { + it('isLocalPath should identify local paths', () => { + expect(isLocalPath('./path')).toBe(true); + expect(isLocalPath('../path')).toBe(true); + expect(isLocalPath('/absolute')).toBe(true); + expect(isLocalPath('~/home')).toBe(true); + expect(isLocalPath('owner/repo')).toBe(false); + }); + + it('isGitUrl should identify git URLs', () => { + expect(isGitUrl('https://github.com/owner/repo')).toBe(true); + expect(isGitUrl('git@github.com:owner/repo')).toBe(true); + expect(isGitUrl('ssh://git@github.com/owner/repo')).toBe(true); + expect(isGitUrl('owner/repo')).toBe(false); + }); + }); +}); diff --git a/tests/skills.test.ts b/tests/skills.test.ts new file mode 100644 index 00000000..07b79577 --- /dev/null +++ b/tests/skills.test.ts @@ -0,0 +1,326 @@ +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 { randomUUID } from 'node:crypto'; +import { + discoverSkills, + parseSkill, + extractFrontmatter, + extractField, + validateSkill, + isPathInside, +} from '../src/core/skills.js'; + +describe('skills', () => { + let testDir: string; + + beforeEach(() => { + testDir = join(tmpdir(), `skillkit-test-${randomUUID()}`); + mkdirSync(testDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(testDir)) { + rmSync(testDir, { recursive: true, force: true }); + } + }); + + describe('extractFrontmatter', () => { + it('should extract valid YAML frontmatter', () => { + const content = `--- +name: test-skill +description: A test skill +--- +# Content`; + + const frontmatter = extractFrontmatter(content); + expect(frontmatter).toEqual({ + name: 'test-skill', + description: 'A test skill', + }); + }); + + it('should return null for missing frontmatter', () => { + const content = '# No frontmatter'; + expect(extractFrontmatter(content)).toBeNull(); + }); + + it('should handle multiline descriptions', () => { + const content = `--- +name: test-skill +description: | + A multiline + description +--- +# Content`; + + const frontmatter = extractFrontmatter(content); + expect(frontmatter?.description).toContain('multiline'); + }); + }); + + describe('extractField', () => { + it('should extract specific field', () => { + const content = `--- +name: test-skill +description: A test +---`; + + expect(extractField(content, 'name')).toBe('test-skill'); + expect(extractField(content, 'description')).toBe('A test'); + }); + + it('should return null for missing field', () => { + const content = `--- +name: test-skill +---`; + + expect(extractField(content, 'description')).toBeNull(); + }); + }); + + describe('discoverSkills', () => { + it('should discover skills with SKILL.md', () => { + // Create test skill + const skillDir = join(testDir, 'test-skill'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: test-skill +description: A test skill for testing purposes +--- +# Test Skill` + ); + + const skills = discoverSkills(testDir); + expect(skills).toHaveLength(1); + expect(skills[0].name).toBe('test-skill'); + }); + + it('should skip directories without SKILL.md', () => { + const noSkillDir = join(testDir, 'not-a-skill'); + mkdirSync(noSkillDir); + writeFileSync(join(noSkillDir, 'README.md'), '# Not a skill'); + + const skills = discoverSkills(testDir); + expect(skills).toHaveLength(0); + }); + + it('should return empty array for non-existent directory', () => { + const skills = discoverSkills('/nonexistent/path'); + expect(skills).toHaveLength(0); + }); + }); + + describe('parseSkill', () => { + it('should parse a valid skill', () => { + const skillDir = join(testDir, 'valid-skill'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: valid-skill +description: A valid skill with proper frontmatter +--- +# Valid Skill` + ); + + const skill = parseSkill(skillDir); + expect(skill).not.toBeNull(); + expect(skill?.name).toBe('valid-skill'); + expect(skill?.description).toBe('A valid skill with proper frontmatter'); + }); + + it('should return null for missing SKILL.md', () => { + const emptyDir = join(testDir, 'empty'); + mkdirSync(emptyDir); + + expect(parseSkill(emptyDir)).toBeNull(); + }); + }); + + describe('validateSkill', () => { + it('should validate a proper skill', () => { + const skillDir = join(testDir, 'valid'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: valid +description: A valid skill with proper frontmatter that is long enough +--- +# Content` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + expect(result.errors).toHaveLength(0); + }); + + it('should fail for missing SKILL.md', () => { + const emptyDir = join(testDir, 'empty'); + mkdirSync(emptyDir); + + const result = validateSkill(emptyDir); + expect(result.valid).toBe(false); + expect(result.errors).toContain('Missing SKILL.md file'); + }); + + it('should fail for missing frontmatter', () => { + const skillDir = join(testDir, 'no-fm'); + mkdirSync(skillDir); + writeFileSync(join(skillDir, 'SKILL.md'), '# No frontmatter'); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(false); + expect(result.errors).toContain('Missing YAML frontmatter in SKILL.md'); + }); + + it('should warn when name does not match directory', () => { + const skillDir = join(testDir, 'my-dir'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: different-name +description: A skill with mismatched name that is long enough for validation +--- +# Content` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + expect(result.warnings).toBeDefined(); + expect(result.warnings?.some(w => w.includes('does not match directory'))).toBe(true); + }); + + it('should warn for short descriptions', () => { + const skillDir = join(testDir, 'short-desc'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: short-desc +description: Too short +--- +# Content` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + expect(result.warnings?.some(w => w.includes('description is short'))).toBe(true); + }); + }); + + describe('Agent Skills spec frontmatter', () => { + it('should accept license field', () => { + const skillDir = join(testDir, 'with-license'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: with-license +description: A skill with license field that meets minimum length requirement +license: MIT +--- +# Content` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + }); + + it('should accept compatibility field', () => { + const skillDir = join(testDir, 'with-compat'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: with-compat +description: A skill with compatibility field that meets minimum length requirement +compatibility: Requires Node.js 18+ +--- +# Content` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + }); + + it('should accept metadata field', () => { + const skillDir = join(testDir, 'with-meta'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: with-meta +description: A skill with metadata field that meets minimum length requirement +metadata: + author: test-org + version: "1.0" +--- +# Content` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + + const frontmatter = extractFrontmatter(`--- +name: with-meta +description: A skill +metadata: + author: test-org + version: "1.0" +---`); + expect(frontmatter?.metadata).toEqual({ author: 'test-org', version: '1.0' }); + }); + + it('should accept allowed-tools field', () => { + const skillDir = join(testDir, 'with-tools'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: with-tools +description: A skill with allowed-tools field that meets minimum length requirement +allowed-tools: Bash(git:*) Read Write +--- +# Content` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + }); + + it('should reject invalid skill names', () => { + const skillDir = join(testDir, 'InvalidName'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: InvalidName +description: A skill with invalid name format +--- +# Content` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(false); + expect(result.errors.some(e => e.includes('lowercase'))).toBe(true); + }); + }); + + describe('isPathInside', () => { + it('should return true for child paths', () => { + expect(isPathInside('/parent/child', '/parent')).toBe(true); + expect(isPathInside('/parent/child/grandchild', '/parent')).toBe(true); + }); + + it('should return false for path traversal', () => { + expect(isPathInside('/parent/../outside', '/parent')).toBe(false); + expect(isPathInside('/parent/child/../../outside', '/parent')).toBe(false); + }); + }); +}); diff --git a/tests/validate.test.ts b/tests/validate.test.ts new file mode 100644 index 00000000..7619fe27 --- /dev/null +++ b/tests/validate.test.ts @@ -0,0 +1,236 @@ +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 { randomUUID } from 'node:crypto'; +import { validateSkill } from '../src/core/skills.js'; + +describe('validate command', () => { + let testDir: string; + + beforeEach(() => { + testDir = join(tmpdir(), `skillkit-validate-test-${randomUUID()}`); + mkdirSync(testDir, { recursive: true }); + }); + + afterEach(() => { + if (existsSync(testDir)) { + rmSync(testDir, { recursive: true, force: true }); + } + }); + + describe('Agent Skills spec validation', () => { + it('should validate complete Agent Skills spec skill', () => { + const skillDir = join(testDir, 'complete-skill'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: complete-skill +description: A complete skill following the Agent Skills specification format +license: MIT +compatibility: Requires Node.js 18+ and npm +metadata: + author: test-org + version: "1.0.0" + repository: https://github.com/test/skill +allowed-tools: Bash(git:*) Read Write +--- +# Complete Skill + +This skill demonstrates the full Agent Skills spec format. + +## When to Use + +- When you need to test validation +- When you want to see all fields + +## Instructions + +1. Step one +2. Step two +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + expect(result.errors).toHaveLength(0); + }); + + it('should validate minimal required fields only', () => { + const skillDir = join(testDir, 'minimal'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: minimal +description: Just the required fields - name and description for Agent Skills +--- +# Minimal Skill +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + }); + + it('should fail when name is missing', () => { + const skillDir = join(testDir, 'no-name'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +description: A skill without a name +--- +# No Name +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(false); + expect(result.errors.some(e => e.includes('name'))).toBe(true); + }); + + it('should fail when description is missing', () => { + const skillDir = join(testDir, 'no-desc'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: no-desc +--- +# No Description +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(false); + expect(result.errors.some(e => e.includes('description'))).toBe(true); + }); + + it('should fail for name with uppercase letters', () => { + const skillDir = join(testDir, 'upper'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: MySkill +description: A skill with uppercase name +--- +# Content +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(false); + }); + + it('should fail for name with spaces', () => { + const skillDir = join(testDir, 'spaces'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: my skill +description: A skill with spaces in name +--- +# Content +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(false); + }); + + it('should fail for name with underscores', () => { + const skillDir = join(testDir, 'underscores'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: my_skill +description: A skill with underscores in name +--- +# Content +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(false); + }); + + it('should pass for name with hyphens', () => { + const skillDir = join(testDir, 'my-skill'); + mkdirSync(skillDir); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: my-skill +description: A skill with hyphens in name that is long enough for validation +--- +# Content +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + }); + + it('should reject description over 1024 chars', () => { + const skillDir = join(testDir, 'long-desc'); + mkdirSync(skillDir); + const longDesc = 'x'.repeat(1025); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: long-desc +description: ${longDesc} +--- +# Content +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(false); + }); + + it('should reject name over 64 chars', () => { + const skillDir = join(testDir, 'long-name'); + mkdirSync(skillDir); + const longName = 'a'.repeat(65); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: ${longName} +description: A skill with too long name +--- +# Content +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(false); + }); + }); + + describe('warnings', () => { + it('should warn for very long SKILL.md content', () => { + const skillDir = join(testDir, 'long-content'); + mkdirSync(skillDir); + const longContent = Array(600).fill('Line of content').join('\n'); + writeFileSync( + join(skillDir, 'SKILL.md'), + `--- +name: long-content +description: A skill with very long content that should trigger a warning +--- +${longContent} +` + ); + + const result = validateSkill(skillDir); + expect(result.valid).toBe(true); + expect(result.warnings?.some(w => w.includes('lines'))).toBe(true); + }); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..bffce88e --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2022"], + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/tsup.config.ts b/tsup.config.ts new file mode 100644 index 00000000..71ba42ad --- /dev/null +++ b/tsup.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: { + cli: 'src/cli.ts', + index: 'src/index.ts', + }, + format: ['esm'], + target: 'node18', + outDir: 'dist', + clean: true, + dts: true, + sourcemap: true, + splitting: false, + skipNodeModulesBundle: true, + platform: 'node', + // Remove banner - npm handles shebang via package.json bin field + // For local dev, use: node dist/cli.js +}); diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 00000000..3eb080f9 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + globals: true, + environment: 'node', + coverage: { + provider: 'v8', + reporter: ['text', 'json', 'html'], + exclude: ['node_modules', 'dist', '**/*.test.ts', 'vitest.config.ts', 'tsup.config.ts'], + }, + include: ['src/**/*.test.ts', 'tests/**/*.test.ts'], + testTimeout: 30000, + }, +});