Compare commits

...
Author SHA1 Message Date
Rohit Ghumare 79656339c9 docs: add comprehensive documentation section to website
- Create Documentation.tsx component with DeepWiki-sourced content
- Add sections: Overview, Installation, Architecture, Agents, Commands
- Add sections: Configuration, API Reference, Skill Format, Tech Stack
- Include interactive sidebar navigation
- Add Docs link to navbar
- Reference DeepWiki as documentation source

Source: https://deepwiki.com/rohitg00/skillkit
2026-01-28 15:37:08 +00:00
Rohit Ghumare 03d6610e7c fix: address additional review feedback
- validate.ts: Add error when --fix is passed without targets
- index.ts: Skip headers inside fenced code blocks during completeness check
- compute-quality.ts: Use nullish coalescing (??) to preserve zero quality scores
2026-01-28 14:18:27 +00:00
Rohit Ghumare c22e1b3caf Merge main into feat/quality-evaluation 2026-01-28 13:50:18 +00:00
Rohit Ghumare dd3bd07296 fix: address remaining CodeRabbit review suggestions
- Escape regex metacharacters in vague term patterns (fix.ts)
- Improve diff algorithm using set-based comparison (fix.ts)
- Fix validateSkill receiving file path instead of directory (validate.ts)
- Check final section in completeness assessment (index.ts)
- Add error handling and empty skills guard (compute-quality.ts)
2026-01-28 13:47:56 +00:00
Rohit Ghumare d6b76f3abd fix: address CodeRabbit and Devin review suggestions
- Fix .mdc file name extraction in fix.ts (handles both .md and .mdc)
- Add missing advanced field to test fixtures in quality.test.ts
- Fix duplicate header detection in assessCompleteness using regex.exec
- Fix ESM compatibility in compute-quality.ts using import.meta.url
- Add trailing newline to skills.json output
2026-01-28 13:28:29 +00:00
Rohit Ghumare 28c2c0a936 feat(quality): extend quality evaluation system with badges, deeper analysis, and fix command
- Phase 2: Add quality badges to CLI commands (list, recommend, install)
  - formatQualityBadge() helper for color-coded grade badges
  - --quality flag for list command
  - Low-quality skill warnings during install

- Phase 3: Add TUI quality badges
  - Extended SkillItem with quality, grade, warnings fields
  - Quality evaluation in loadSkills()
  - Grade badges in Installed and Recommend screens

- Phase 4: Deeper quality analysis
  - Deprecated pattern detection (CommonJS, class components, var)
  - Security pattern detection (hardcoded credentials, eval, innerHTML)
  - Conflicting instruction detection
  - Completeness assessment (TODOs, empty sections, example coverage)
  - New weight distribution: Structure 35%, Clarity 25%, Specificity 25%, Advanced 15%

- Phase 1: Pre-compute marketplace quality scores
  - Updated schema.json with quality field (0-100)
  - Created scripts/compute-quality.ts for batch computation

- Phase 5: Benchmark against category leaders
  - New benchmark.ts module with category detection
  - Percentile calculation and comparison notes
  - --benchmark flag for validate command

- Phase 6: Fix command for automated quality fixes
  - skillkit fix command with --dry-run and --interactive modes
  - Auto-generates frontmatter, "When to Use", "Boundaries" sections
  - --fix flag alias on validate command
2026-01-28 13:02:51 +00:00
Rohit Ghumare 0a59bcf314 feat(quality): add skill quality evaluation system (#20)
* feat(quality): add skill quality evaluation system

- Add quality scoring module with structure, clarity, and specificity metrics
- Evaluate skills for metadata, triggers, boundaries, code examples
- Detect vague terms and penalize overly long skills
- Update validate command to include quality reports
- Add --verbose, --quality, --issues, --json flags
- Quality scores: A (90+), B (80+), C (70+), D (60+), F (<60)

* fix: address CodeRabbit and Devin review suggestions

- Fix JSON output to return exit code 1 on validation failures
- Add --min-score NaN validation with warning message
- Add directory guard for --all flag with .mdc file support
- Fix CRLF handling in frontmatter extraction
- Fix code blocks double-counting in specificity evaluation
- Fix warning message inconsistency for code examples
- Add try/catch error handling in evaluateSkillFile
- Fix isHighQuality threshold to match UI display (80)
2026-01-28 12:01:32 +00:00
Rohit Ghumare 3f03d0690d fix: address CodeRabbit and Devin review suggestions
- Fix JSON output to return exit code 1 on validation failures
- Add --min-score NaN validation with warning message
- Add directory guard for --all flag with .mdc file support
- Fix CRLF handling in frontmatter extraction
- Fix code blocks double-counting in specificity evaluation
- Fix warning message inconsistency for code examples
- Add try/catch error handling in evaluateSkillFile
- Fix isHighQuality threshold to match UI display (80)
2026-01-28 11:56:52 +00:00
Rohit Ghumare 96f83fdc2e feat(quality): add skill quality evaluation system
- Add quality scoring module with structure, clarity, and specificity metrics
- Evaluate skills for metadata, triggers, boundaries, code examples
- Detect vague terms and penalize overly long skills
- Update validate command to include quality reports
- Add --verbose, --quality, --issues, --json flags
- Quality scores: A (90+), B (80+), C (70+), D (60+), F (<60)
2026-01-28 11:32:15 +00:00
Rohit Ghumare b9a724012a Merge feat/dx-improvements into main 2026-01-28 10:50:47 +00:00
Rohit Ghumare 02989b4021 fix: correct video path in README 2026-01-28 10:49:16 +00:00
Rohit Ghumare b559a2acbf feat: DX improvements - new CLI commands, simplified onboarding, and website updates (#19)
* feat(cli): add check, find, manifest commands and simplified onboarding

New commands:
- skillkit check - Check for available skill updates (dry-run)
- skillkit find - Quick CLI marketplace search with interactive mode
- skillkit manifest - Manage .skills manifest file for declarative skills

Manifest subcommands:
- manifest init - Create new .skills file
- manifest add - Add skill source to manifest
- manifest remove - Remove skill source from manifest
- manifest install - Install all skills from manifest
- manifest generate - Generate manifest from installed skills

Onboarding improvements:
- Add quickAgentSelect() for simplified agent selection
- Same as last time (Recommended) option for returning users
- All detected agents quick option
- Select specific agents for manual selection
- Streamlined install flow with fewer prompts

Other changes:
- Add bullet, arrowUp, arrowDown symbols to theme
- Update version to 1.7.6

* feat(website): showcase full CLI power with Commands section

- Add Commands.tsx with tabbed command showcase (Core, Discovery, Team, Advanced)
- Update Hero terminal demo with new commands (find, ui, check, manifest)
- Update Features section with TUI, Plugins, Manifest, CI/CD, Slash Commands
- Update stats to show 17 agents, 30+ commands, 15K skills
- Update comparison table with .skills manifest and CI/CD
- Bump version display to v1.7.5

* fix: address CodeRabbit review suggestions

- Security: Use execFileSync instead of execSync to prevent command injection in manifest install
- Fix: Remove false positive hasUpdate for remote skills in check command
- Fix: Add missing repoName filter in interactive find search
- Fix: Remove incorrect sourceType→agents mapping in manifest generate
- Perf: Eliminate duplicate findSkill calls in check command

* docs: add demo video and update README

- Add skillkit-demo.mp4 video to README
- Update website badge to agenstskills.com
- Remove old GIF reference
2026-01-28 10:47:02 +00:00
Rohit Ghumare 5cf9178a9f docs: add demo video and update README
- Add skillkit-demo.mp4 video to README
- Update website badge to agenstskills.com
- Remove old GIF reference
2026-01-28 10:44:38 +00:00
Rohit Ghumare 279bc1cd06 fix: address CodeRabbit review suggestions
- Security: Use execFileSync instead of execSync to prevent command injection in manifest install
- Fix: Remove false positive hasUpdate for remote skills in check command
- Fix: Add missing repoName filter in interactive find search
- Fix: Remove incorrect sourceType→agents mapping in manifest generate
- Perf: Eliminate duplicate findSkill calls in check command
2026-01-28 10:42:33 +00:00
Rohit Ghumare 7092e9a0b8 feat(website): showcase full CLI power with Commands section
- Add Commands.tsx with tabbed command showcase (Core, Discovery, Team, Advanced)
- Update Hero terminal demo with new commands (find, ui, check, manifest)
- Update Features section with TUI, Plugins, Manifest, CI/CD, Slash Commands
- Update stats to show 17 agents, 30+ commands, 15K skills
- Update comparison table with .skills manifest and CI/CD
- Bump version display to v1.7.5
2026-01-28 09:20:47 +00:00
Rohit Ghumare 8a0e1f586e feat(cli): add check, find, manifest commands and simplified onboarding
New commands:
- skillkit check - Check for available skill updates (dry-run)
- skillkit find - Quick CLI marketplace search with interactive mode
- skillkit manifest - Manage .skills manifest file for declarative skills

Manifest subcommands:
- manifest init - Create new .skills file
- manifest add - Add skill source to manifest
- manifest remove - Remove skill source from manifest
- manifest install - Install all skills from manifest
- manifest generate - Generate manifest from installed skills

Onboarding improvements:
- Add quickAgentSelect() for simplified agent selection
- Same as last time (Recommended) option for returning users
- All detected agents quick option
- Select specific agents for manual selection
- Streamlined install flow with fewer prompts

Other changes:
- Add bullet, arrowUp, arrowDown symbols to theme
- Update version to 1.7.6
2026-01-28 08:59:27 +00:00
Rohit Ghumare 235130c6ae fix(tui): fix rendering overlap and terminal crash on quit (#18)
- Remove deprecated @types/minimatch dependency (minimatch 10.x has bundled types)
- Fix TUI text rendering overlap by using single text elements instead of multiple
  text elements in box rows (Browse, Installed, Marketplace, SkillList screens)
- Fix terminal crash on 'q' press by properly unmounting React tree and restoring
  terminal state with escape sequences
- Add signal handlers (SIGINT, SIGTERM) for clean exit
- Bump version to 1.7.6
2026-01-28 08:27:46 +00:00
Rohit Ghumare da5a17960d chore: bump version to 1.7.5 2026-01-28 00:57:35 +00:00
Rohit Ghumare fceb23843d fix(cli): update TUI error message with correct bun command 2026-01-28 00:56:02 +00:00
Rohit Ghumare 91ef4b63f4 docs: add interactive CLI screenshot and update README 2026-01-28 00:53:07 +00:00
Rohit Ghumare 7aa566d9b5 chore: bump version to 1.7.4 2026-01-28 00:44:42 +00:00
Rohit Ghumare 803ff5692a chore: bump all packages to 1.7.3 for onboarding UI 2026-01-27 22:24:09 +00:00
Rohit Ghumare f036104c6d docs: add Beautiful CLI Experience section for onboarding UI 2026-01-27 22:14:55 +00:00
Rohit Ghumare 257fe9fbb6 chore: bump version to 1.7.3 2026-01-27 22:14:13 +00:00
Rohit Ghumare a5efe29a6c feat(cli): add beautiful onboarding UI with @clack/prompts (#17)
* feat(cli): add beautiful onboarding UI with @clack/prompts

- Add new onboarding module with theme, logo, prompts, summary, and preferences
- Implement adaptive ASCII logos (full/compact/minimal based on terminal width)
- Add agent icons (⟁ ◫ ◎ ✦ ⬡) and circle-based step indicators (● ○)
- Create agentMultiselect and skillMultiselect with visual formatting
- Add progress bars and score formatting utilities
- Store user preferences in ~/.skillkit/preferences.json
- Update all interactive commands with new UI (init, install, sync, marketplace, recommend)
- Add unit tests (18 tests) and e2e tests (16 tests)
- Replace nested ternaries with if/else for clarity

* fix(cli): address review feedback from CodeRabbit and Devin

- Fix symlink install method: actually create symlinks for subsequent agents
- Fix validate type signature to match @clack/prompts API (string | Error | undefined)
- Handle zero detected agents to avoid empty multiselect blocking
- Clamp divider width to avoid negative repeat counts
- Guard progressBar against invalid totals/values
- Isolate preference tests from real ~/.skillkit state

* fix(cli): TypeScript type compatibility with @clack/prompts

- Cast select options to match Option<T> type signature
- Cast groupMultiselect options for proper Record type
- Fix tasks function return type to Promise<string | void>

* fix(cli): use 'as any' for @clack/prompts type compatibility

The Option<T> type from @clack/prompts has a complex structure that
doesn't match our inline types. Using 'as any' assertion to bypass
strict type checking while maintaining runtime correctness.
2026-01-27 22:09:52 +00:00
Rohit Ghumare 6916c09962 chore: bump version to 1.7.2 2026-01-27 11:04:31 +00:00
Rohit Ghumare 41da423306 feat(ci): add GitHub Packages publishing (#16)
* feat(ci): add GitHub Packages publishing

Adds a new job to publish the main skillkit package to GitHub Packages
(npm.pkg.github.com) as @rohitg00/skillkit after successful npm publish.

- Publish to npm first, then GitHub Packages
- Uses GITHUB_TOKEN for authentication (no additional secrets needed)
- Package available at npm.pkg.github.com/@rohitg00/skillkit

* docs: add GitHub Packages installation instructions

* fix(ci): resolve workspace dependencies before GitHub Packages publish
2026-01-27 10:55:02 +00:00
Rohit Ghumare c5e78b7f83 fix(website): standardize layout to max-w-5xl for consistent alignment 2026-01-27 00:10:38 +00:00
Rohit Ghumare 438bc2720a feat(website): replace npx command with npm logo link in navbar 2026-01-27 00:07:49 +00:00
Rohit Ghumare 85d9eee7e9 chore: bump version to 1.7.1 2026-01-27 00:06:13 +00:00
Rohit Ghumare d14b57c651 Update README.md 2026-01-27 00:04:17 +00:00
Rohit Ghumare 4a6003ec46 feat: single source of truth for skills marketplace (#15)
* feat: single source of truth for skills marketplace

- Consolidate all skills data to marketplace/skills.json (15,062 skills)
- Add marketplace/sources.json for curated repository sources (31 repos)
- Add skillkit publish command for user skill submissions
- Add auto-publish prompt to skillkit init
- Add AI skill caching with localStorage (7-day TTL)
- Add Submit to Marketplace button for AI-generated skills
- Remove duplicate skills.json files (docs, core)
- Remove legacy src/tui/ folder (replaced by packages/tui)
- Update all imports to use single source files

* fix: address CodeRabbit review feedback

- Remove duplicate checklist items in SkillSubmitForm.tsx
- Add missing sources-schema.json file
- Add slugify method for URL-safe skill IDs
- Fix Windows browser open command (empty title param)
- Fix frontmatter parsing for CRLF and multiline tags

* fix: address additional review feedback

- Add TTY check to skip prompts in CI/non-interactive environments
- Guard against empty slug IDs with validation
- Print full URL in fallback (not truncated)
- Fix repo name parsing for names containing dots
- Add cache pruning and max entries limit (50) for localStorage

* fix: filter empty strings from YAML tags array parsing
2026-01-27 00:02:40 +00:00
Rohit Ghumare 6d36a4a3f7 Revert "feat: single source of truth for skills marketplace"
This reverts commit 0c5eb93891.
2026-01-26 23:15:14 +00:00
Rohit Ghumare 0c5eb93891 feat: single source of truth for skills marketplace
- Consolidate all skills data to marketplace/skills.json (15,062 skills)
- Add marketplace/sources.json for curated repository sources (31 repos)
- Add skillkit publish command for user skill submissions
- Add auto-publish prompt to skillkit init
- Add AI skill caching with localStorage (7-day TTL)
- Add Submit to Marketplace button for AI-generated skills
- Remove duplicate skills.json files (docs, core)
- Remove legacy src/tui/ folder (replaced by packages/tui)
- Update all imports to use single source files
2026-01-26 23:12:23 +00:00
Rohit Ghumare 2432410f79 feat: add OG image and meta tags for social preview
- Add og-image.png for social media previews
- Add Open Graph meta tags (title, description, image, url)
- Add Twitter Card meta tags (summary_large_image)
- Add meta description for SEO
2026-01-26 21:14:37 +00:00
Rohit Ghumare 4e3e2b3145 fix: alignment and npx skillkit@latest
- Hero: use items-start for proper top alignment
- Agents: add pl-8 padding to prevent first icon cutoff
- Update all npx commands to use skillkit@latest
2026-01-26 21:07:24 +00:00
Rohit Ghumare 82e4a2ae62 fix: mobile layout improvements
- Validation errors now stack vertically for better readability
- Footer more compact with smaller padding
- Shorter footer text on mobile
- Better responsive breakpoints (sm instead of md)
2026-01-26 20:58:58 +00:00
Rohit Ghumare ff5b3f7b4b fix: compact npx command button layout
- Use inline-flex for tight button sizing
- Remove unnecessary wrapper div and gradient
- Use flex-wrap for responsive layout
- Reduce spacing for cleaner look
2026-01-26 20:57:54 +00:00
Rohit Ghumare 15134cebbb fix: prevent auto-scroll to Skill Finder on page load
- Remove auto-focus on initial page load
- Only focus input after user interaction (SUCCESS state)
- Use preventScroll option to avoid scroll jumps
2026-01-26 20:51:22 +00:00
Rohit Ghumare 6d01413a68 fix: show GitHub icon on mobile nav 2026-01-26 20:49:35 +00:00
Rohit Ghumare a9d6727ca5 fix: improve mobile layout and add Copied feedback
- Hide terminal animation on mobile (only show on lg screens)
- Add 'Copied!' text feedback when clicking npx command
- Make npx button full width on mobile
- Reduce blank space on mobile hero section
2026-01-26 20:49:05 +00:00
Rohit Ghumare 2078be9eb4 fix: constrain all sections to max-w-5xl for consistent layout
- Add max-w-5xl constraint to Agents scrolling section
- All major sections now have consistent max-width
- Reduces stretched appearance on large monitors
2026-01-26 20:01:04 +00:00
Rohit Ghumare 44da0f8592 fix: use window.open for GitHub issue creation
- Change from anchor tag to button with explicit window.open
- Ensures click handler properly opens GitHub issue URL
- Add disabled state to button when form is invalid
2026-01-26 19:44:44 +00:00
Rohit Ghumare 4089e5a0be fix: tighten layout with max-w-5xl constraints for large screens
- Add max-w-5xl mx-auto to Hero grid container
- Add max-w-5xl mx-auto to Features comparison and feature cards grids
- Set fixed terminal width lg:max-w-[420px] for consistent sizing
- Reduce gap on mobile for better spacing
2026-01-26 19:39:26 +00:00
Rohit Ghumare c564d32ea9 fix: constrain max-width to 6xl for better large screen layout 2026-01-26 19:32:33 +00:00
Rohit Ghumare 4f65aecbc9 fix: improve mobile responsiveness for agents and features sections 2026-01-26 19:27:02 +00:00
Rohit Ghumare c1ba42d616 fix: set base path to root for Vercel deployment 2026-01-26 19:24:01 +00:00
Rohit Ghumare c8172097be feat(marketplace): add community skill submission system (#14)
* feat(marketplace): add community skill submission system

- Add marketplace/skills.json with curated skills collection
- Add marketplace/schema.json for skill validation
- Add marketplace/CONTRIBUTING.md with submission guidelines
- Add skill submission issue template for community contributions
- Add workflow to auto-process approved skill submissions
- Add bundled skills data in core package for offline access

Community members can now submit skills via GitHub Issues, which are
automatically added to the marketplace when approved by maintainers.

* fix: address CodeRabbit review suggestions for marketplace PR

Workflow improvements:
- Add concurrency block to prevent parallel push conflicts
- Fix authorGithub extraction to preserve hyphens in usernames
- Filter empty tags and validate at least one tag exists

Schema improvements:
- Allow dots in repository names (e.g., user/repo.js)
- Copy schema.json to core package data folder for validation

Documentation:
- Add 'text' language tag to code block in CONTRIBUTING.md

Data sync:
- Add skills.json and schema.json to docs/skillkit/data/
2026-01-26 19:20:20 +00:00
Rohit Ghumare 80e41e517c chore: add vercel.json for deployment configuration 2026-01-26 19:20:11 +00:00
Rohit Ghumare 26ea7e9002 refactor(docs): simplify website components and update README (#12)
* refactor(docs): simplify website components and update README

Website Code Simplification:
- Convert arrow functions to named function declarations with explicit return types
- Extract inline styles to module-level constants (BASE_STYLES, VARIANT_STYLES, etc.)
- Extract SVG icons to constants (GITHUB_ICON, CHECK_ICON, COPY_ICON)
- Extract CSS animations to constants (FADE_ANIMATION_STYLES, SCROLL_ANIMATION_STYLES)
- Add explicit TypeScript interfaces (Feature, Agent, TerminalLine, etc.)
- Replace nested ternaries with switch statements for clarity
- Extract inline handlers to named functions (scrollToTop, openGitHub, etc.)
- Improve variable naming (idx -> index, cap -> feature)
- Use meaningful React keys instead of index-only keys

README Updates:
- Remove "What's New in v1.6" section (release notes should be in CHANGELOG)

Components updated:
- App.tsx, Button.tsx, Card.tsx, Terminal.tsx, Footer.tsx
- Features.tsx, Agents.tsx, Hero.tsx
- SkillSubmitForm.tsx, SkillGenerator.tsx

* fix: address CodeRabbit review suggestions

Security:
- Add noopener,noreferrer to window.open in Hero.tsx
- Handle clipboard API errors with try/catch

Accessibility:
- Add Space key support to Card.tsx for keyboard navigation
- Add aria-label to GitHub icon link in Footer.tsx

Error Handling:
- Fix useCallback dependency for processMarkdownFile in SkillSubmitForm
- Add input validation for topic in geminiService.ts

Data Validation:
- Add defensive checks for malformed source URLs in skills-index.ts
- Generate proper skill ID for upload mode in SkillSubmitForm

Type Safety:
- Replace unsafe 'as any' cast with proper type annotation in geminiService

Code Quality:
- Use array filter pattern for class concatenation in Button.tsx
2026-01-26 19:17:21 +00:00
Rohit Ghumare 1b5722a8c0 chore: bump version to 1.7.0 2026-01-26 12:37:17 +00:00
Rohit Ghumare 0210556634 feat(tui): migrate to OpenTUI with monochromatic design (#11)
* feat(tui): migrate to OpenTUI with monochromatic design

## Summary
- Migrate TUI from Ink to OpenTUI framework (requires Bun >=1.2.0)
- Implement monochromatic B&W design with colored accents
- Add Help screen accessible via `/` key
- Fix terminal cleanup on exit (no more escape code garbage)
- Clean up code: remove unnecessary comments, simplify components
- Add 9 unit tests for TUI state, theme, and utilities

## Breaking Changes
- TUI now requires Bun runtime (>=1.2.0) for OpenTUI
- Help moved from `?` (requires Shift) to `/` key

## Changes
- **index.tsx**: Clean exit handler with ANSI terminal restore
- **App.tsx**: Simplified screen routing with switch statement
- **Help.tsx**: New help screen with keyboard shortcuts reference
- **Home.tsx**: Extract FEATURES constant, simplified agent width logic
- **Sidebar.tsx**: Removed unused onNavigate prop usage
- **state/types.ts**: Consolidated type definitions, added help screen
- **README.md**: Updated with Bun requirement and new architecture

## Test Coverage
- 757 tests passing (664 core + 80 agents + 9 tui + 1 cli + 3 app)

## Code Quality
- Removed all JSDoc comments describing obvious code
- Extracted reusable ShortcutSection component
- Replaced nested ternaries with clearer if/else
- Moved static data outside components to prevent recreation

* fix: address CodeRabbit review issues

- AgentGrid: prevent infinite loop when columns <= 0
- Splash: clamp progress width to prevent negative repeat
- StatsCard: reset animation state when items change
- Help: clamp contentWidth to minimum 1
- Browse: add useKeyboard handler for navigation and search
- Installed: add useKeyboard handler for toggle functionality
- Marketplace: add useKeyboard handler and clamp contentWidth
- Recommend: fix spinner interval, add keyboard handler
- Settings: add keyboard handler, fix SETTINGS -> settings state
- Sync: add keyboard handler and sync flow implementation
- Workflow: add keyboard handler and clamp contentWidth
- skills.ts: add path validation to prevent directory traversal

* fix: address additional CodeRabbit review issues

Splash.tsx:
- Change generateParticles from useMemo to useCallback for fresh random rows

Browse.tsx:
- Clamp maxLen to avoid negative slicing
- Add Enter/Return handler to open selected repo

Installed.tsx:
- Wire up 'd' key to toggle handler
- Update shortcuts label from "delete" to "disable"

Marketplace.tsx:
- Add handleInstall callback for Enter key
- Add 'b' key handler to navigate to browse

Recommend.tsx:
- Add handleInstall callback for Enter key

Settings.tsx:
- Update shortcuts label from "enter edit" to "enter toggle"

Sync.tsx:
- Add useRef for timeout cleanup on unmount
- Clamp selectedIndex when agents list shrinks

Workflow.tsx:
- Remove unimplemented shortcuts from display string

* fix: address performance and stale closure issues

Splash.tsx:
- Cache getVersion() with useMemo to avoid repeated sync file I/O

Installed.tsx:
- Wrap keyboard handler in useCallback to prevent stale closures

Settings.tsx:
- Wrap keyboard handler in useCallback with proper dependencies

Workflow.tsx:
- Remove "Press 'n' to create one" text since 'n' key isn't implemented
2026-01-26 12:35:30 +00:00
161 changed files with 142784 additions and 6308 deletions
@@ -0,0 +1,89 @@
name: Skill Submission
description: Submit a new skill to the SkillKit marketplace
title: "[Skill Submission] "
labels: ["skill-submission"]
body:
- type: markdown
attributes:
value: |
## Submit Your Skill to SkillKit Marketplace
Thanks for contributing! Please fill out the details below.
**Tip:** You can also use our [web form](https://rohitg00.github.io/skillkit/) to submit skills.
- type: input
id: skill-name
attributes:
label: Skill Name
description: A descriptive name for your skill
placeholder: e.g., React Best Practices
validations:
required: true
- type: textarea
id: description
attributes:
label: Description
description: What does this skill teach AI agents?
placeholder: A brief description of your skill...
validations:
required: true
- type: input
id: repo-owner
attributes:
label: GitHub Owner
description: The owner of the repository (username or organization)
placeholder: e.g., your-username
validations:
required: true
- type: input
id: repo-name
attributes:
label: Repository Name
description: The name of the repository containing the skill
placeholder: e.g., my-agent-skills
validations:
required: true
- type: input
id: skill-path
attributes:
label: Skill Path
description: Path to SKILL.md in the repository
placeholder: skills/my-skill/SKILL.md
validations:
required: true
- type: input
id: tags
attributes:
label: Tags
description: Comma-separated tags for categorization
placeholder: react, typescript, frontend
validations:
required: true
- type: input
id: author-github
attributes:
label: Author GitHub Username
description: Your GitHub username
placeholder: your-username
validations:
required: true
- type: checkboxes
id: checklist
attributes:
label: Checklist
description: Please confirm the following
options:
- label: Repository is public
required: true
- label: SKILL.md follows the agentskills.io standard format
required: true
- label: Skill has been tested with at least one AI agent
required: false
@@ -0,0 +1,180 @@
name: Process Skill Submission
on:
issues:
types: [labeled]
permissions:
contents: write
issues: write
concurrency:
group: process-submission-${{ github.event.issue.number }}
cancel-in-progress: false
jobs:
process-submission:
if: github.event.label.name == 'approved'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Parse Issue and Update skills.json
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const issue = context.payload.issue;
const body = issue.body;
// Parse issue body for skill details
const parseField = (label) => {
const regex = new RegExp(`\\*\\*${label}:\\*\\*\\s*(.+?)(?:\\n|$)`, 'i');
const match = body.match(regex);
return match ? match[1].trim() : '';
};
const parseCheckbox = (text) => {
const regex = new RegExp(`- \\[(x|X)\\]\\s*${text}`, 'i');
return regex.test(body);
};
// Extract fields from form-based issue
let skillName, description, repoOwner, repoName, skillPath, tags, authorGithub;
if (body.includes('### Skill Name')) {
// YAML form format
const sections = body.split('###').filter(s => s.trim());
for (const section of sections) {
const lines = section.trim().split('\n');
const header = lines[0].trim().toLowerCase();
const value = lines.slice(1).join('\n').trim();
if (header.includes('skill name')) skillName = value;
if (header.includes('description')) description = value;
if (header.includes('github owner')) repoOwner = value;
if (header.includes('repository name')) repoName = value;
if (header.includes('skill path')) skillPath = value;
if (header.includes('tags')) tags = value;
if (header.includes('author github')) authorGithub = value;
}
} else {
// Markdown format from web form
skillName = parseField('Name');
description = parseField('Description');
repoOwner = parseField('Owner');
repoName = parseField('Repo');
skillPath = parseField('Skill Path');
tags = parseField('Tags');
const authorField = parseField('Author') || '';
authorGithub = authorField.replace(/^@/, '').trim();
}
if (!skillName || !repoOwner || !repoName) {
console.log('Missing required fields');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: '❌ Could not parse skill details. Missing required fields (name, owner, or repo).'
});
return;
}
// Generate skill ID
const skillSlug = skillName.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
const skillId = `${repoOwner}/${repoName}/${skillSlug}`;
// Read current skills.json
const skillsPath = 'marketplace/skills.json';
const skillsData = JSON.parse(fs.readFileSync(skillsPath, 'utf-8'));
// Check for duplicates
if (skillsData.skills.some(s => s.id === skillId)) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: `⚠️ Skill with ID \`${skillId}\` already exists in the marketplace.`
});
return;
}
// Parse and validate tags
const filteredTags = tags
? tags.split(',').map(t => t.trim().toLowerCase()).filter(t => t.length > 0)
: [];
if (filteredTags.length === 0) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issue.number,
body: '❌ At least one tag is required. Please add tags to your submission.'
});
return;
}
// Add new skill
const newSkill = {
id: skillId,
name: skillName,
description: description || '',
source: `${repoOwner}/${repoName}`,
tags: filteredTags,
author: authorGithub
};
skillsData.skills.push(newSkill);
skillsData.updatedAt = new Date().toISOString().split('T')[0];
// Write updated skills.json
fs.writeFileSync(skillsPath, JSON.stringify(skillsData, null, 2) + '\n');
// Also update docs copy
const docsCopyPath = 'docs/skillkit/data/skills.json';
fs.writeFileSync(docsCopyPath, JSON.stringify(skillsData, null, 2) + '\n');
// Also update core copy
const coreCopyPath = 'packages/core/src/marketplace/data/skills.json';
fs.writeFileSync(coreCopyPath, JSON.stringify(skillsData, null, 2) + '\n');
console.log(`Added skill: ${skillId}`);
// Set output for commit
core.setOutput('skill_name', skillName);
core.setOutput('skill_id', skillId);
- name: Commit Changes
run: |
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git add marketplace/skills.json docs/skillkit/data/skills.json packages/core/src/marketplace/data/skills.json
git commit -m "feat(marketplace): add skill from #${{ github.event.issue.number }}"
git push
- name: Close Issue with Comment
uses: actions/github-script@v7
with:
script: |
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.issue.number,
body: `✅ **Skill added to marketplace!**\n\nYour skill has been added and will be available in the next release.\n\nThank you for contributing to SkillKit! 🎉`
});
await github.rest.issues.update({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.issue.number,
state: 'closed'
});
+63 -2
View File
@@ -1,4 +1,4 @@
name: Publish to npm
name: Publish to npm and GitHub Packages
on:
push:
@@ -6,7 +6,7 @@ on:
- 'v*'
jobs:
publish:
publish-npm:
runs-on: ubuntu-latest
permissions:
@@ -44,3 +44,64 @@ jobs:
uses: softprops/action-gh-release@v1
with:
generate_release_notes: true
publish-github-packages:
runs-on: ubuntu-latest
needs: publish-npm
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
- name: Setup Node.js for GitHub Packages
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
registry-url: 'https://npm.pkg.github.com'
scope: '@rohitg00'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build
run: pnpm build
- name: Configure npm for GitHub Packages
run: |
echo "@rohitg00:registry=https://npm.pkg.github.com" >> .npmrc
echo "//npm.pkg.github.com/:_authToken=${{ secrets.GITHUB_TOKEN }}" >> .npmrc
- name: Publish main skillkit package to GitHub Packages
working-directory: apps/skillkit
run: |
# Create a temporary package.json with GitHub Packages scope and resolved dependencies
node -e "
const fs = require('fs');
const path = require('path');
const pkg = require('./package.json');
pkg.name = '@rohitg00/skillkit';
pkg.publishConfig = { registry: 'https://npm.pkg.github.com' };
// Resolve workspace:* dependencies to actual versions
for (const [dep, version] of Object.entries(pkg.dependencies || {})) {
if (version.startsWith('workspace:')) {
const depName = dep.replace('@skillkit/', '');
const depPkgPath = path.join('..', '..', 'packages', depName, 'package.json');
const depPkg = JSON.parse(fs.readFileSync(depPkgPath, 'utf8'));
pkg.dependencies[dep] = depPkg.version;
}
}
fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2));
"
npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+29 -12
View File
@@ -1,8 +1,17 @@
# SkillKit
<div align="center">
```
██ SKILLKIT
```
</div>
**Universal Skills for AI Coding Agents**
[![npm version](https://img.shields.io/npm/v/skillkit.svg)](https://www.npmjs.com/package/skillkit)
[![npm downloads](https://img.shields.io/npm/dm/skillkit.svg)](https://www.npmjs.com/package/skillkit)
[![GitHub Package](https://img.shields.io/badge/GitHub%20Package-@rohitg00/skillkit-blue?logo=github)](https://github.com/rohitg00/skillkit/pkgs/npm/skillkit)
[![CI](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml/badge.svg)](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml)
[![Website](https://img.shields.io/badge/Website-agenstskills.com-black)](https://agenstskills.com)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
## Supercharge Every AI Coding Agent
@@ -23,6 +32,10 @@ npm install -g skillkit
## See It In Action
<video src="https://raw.githubusercontent.com/rohitg00/skillkit/main/docs/video/skillkit.mp4" controls width="100%"></video>
> **Note:** If the video doesn't play above, [watch it here](https://raw.githubusercontent.com/rohitg00/skillkit/main/docs/video/skillkit.mp4)
```bash
# Install a skill for ALL your agents at once
skillkit install anthropics/skills --agent claude-code,cursor,windsurf
@@ -37,7 +50,17 @@ skillkit recommend
# > 85% match: nextjs-app-router
```
![SkillKit Demo](https://raw.githubusercontent.com/rohitg00/skillkit/main/skillkit.gif)
## Beautiful CLI Experience
SkillKit features a polished, interactive CLI with visual feedback:
![SkillKit Interactive CLI](docs/img/inital-command.png)
- **Adaptive Logo** - Full ASCII art on wide terminals, compact on narrow
- **Agent Icons** - Visual indicators: ⟁ Claude · ◫ Cursor · ◎ Codex · ✦ Gemini · ⬡ OpenCode
- **Interactive Selection** - Multi-select skills and agents with visual feedback
- **Progress Indicators** - Step trails, spinners, and progress bars
- **Smart Defaults** - Remembers your last selected agents
## What Makes SkillKit Different
@@ -51,16 +74,6 @@ skillkit recommend
| **Session Memory** | Knowledge dies with each session | Persistent learning across agents |
| **Skill Testing** | Hope it works | Test framework with assertions |
## What's New in v1.6
- **Recursive Agent Translation**: Batch translate entire directories of agents with `--recursive` flag
- **Custom AI Sub-Agents**: Create, translate, sync, and validate custom AI sub-agents across 17 coding agents
- **Methodology Framework**: 5 ready-to-use frameworks (Agile, TDD, DevOps, Security-First, Documentation-First)
- **Hooks System**: Event-driven skill triggers - auto-activate on commits, file changes, builds
- **Agent Orchestration**: Multi-agent team coordination with leader/teammate roles
- **Plan System**: Parse, validate, and execute structured development plans
- **Slash Commands**: Generate agent-native `/commands` from natural language
## 5-Minute Quick Start
```bash
@@ -426,6 +439,9 @@ bun add -g skillkit
# npx (no install)
npx skillkit <command>
# GitHub Packages (alternative registry)
npm install -g @rohitg00/skillkit --registry=https://npm.pkg.github.com
```
## Configuration
@@ -456,3 +472,4 @@ Contributions welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md
- [Agent Skills Specification](https://agentskills.io/specification)
- [GitHub Repository](https://github.com/rohitg00/skillkit)
- [NPM Package](https://www.npmjs.com/package/skillkit)
- [GitHub Package](https://github.com/rohitg00/skillkit/pkgs/npm/skillkit)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "skillkit",
"version": "1.6.4",
"version": "1.7.6",
"description": "Supercharge AI coding agents with portable skills. Install, translate, and share skills across Claude Code, Cursor, Codex, Copilot & 13 more",
"type": "module",
"bin": {
+22
View File
@@ -14,6 +14,7 @@ import {
RemoveCommand,
InitCommand,
ValidateCommand,
FixCommand,
CreateCommand,
UICommand,
TranslateCommand,
@@ -39,6 +40,7 @@ import {
CommandCmd,
AICommand,
AuditCommand,
PublishCommand,
AgentCommand,
AgentListCommand,
AgentShowCommand,
@@ -46,6 +48,15 @@ import {
AgentTranslateCommand,
AgentSyncCommand,
AgentValidateCommand,
// New commands (Phase 21)
CheckCommand,
FindCommand,
ManifestCommand,
ManifestInitCommand,
ManifestAddCommand,
ManifestRemoveCommand,
ManifestInstallCommand,
ManifestGenerateCommand,
} from '@skillkit/cli';
const __filename = fileURLToPath(import.meta.url);
@@ -73,6 +84,7 @@ cli.register(UpdateCommand);
cli.register(RemoveCommand);
cli.register(InitCommand);
cli.register(ValidateCommand);
cli.register(FixCommand);
cli.register(CreateCommand);
cli.register(UICommand);
cli.register(TranslateCommand);
@@ -98,6 +110,7 @@ cli.register(PlanCommand);
cli.register(CommandCmd);
cli.register(AICommand);
cli.register(AuditCommand);
cli.register(PublishCommand);
cli.register(AgentCommand);
cli.register(AgentListCommand);
cli.register(AgentShowCommand);
@@ -106,4 +119,13 @@ cli.register(AgentTranslateCommand);
cli.register(AgentSyncCommand);
cli.register(AgentValidateCommand);
cli.register(CheckCommand);
cli.register(FindCommand);
cli.register(ManifestCommand);
cli.register(ManifestInitCommand);
cli.register(ManifestAddCommand);
cli.register(ManifestRemoveCommand);
cli.register(ManifestInstallCommand);
cli.register(ManifestGenerateCommand);
cli.runExit(process.argv.slice(2));
Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+98
View File
@@ -0,0 +1,98 @@
import React from 'react';
import { Hero } from './components/Hero';
import { Features } from './components/Features';
import { Agents } from './components/Agents';
import { Footer } from './components/Footer';
import { SkillGenerator } from './components/SkillGenerator';
import { SkillSubmitForm } from './components/SkillSubmitForm';
import { Commands } from './components/Commands';
import { Documentation } from './components/Documentation';
const GITHUB_ICON = (
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
<path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd" />
</svg>
);
const NPM_ICON = (
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
<path d="M0 7.334v8h6.666v1.332H12v-1.332h12v-8H0zm6.666 6.664H5.334v-4H3.999v4H1.335V8.667h5.331v5.331zm4 0v1.336H8.001V8.667h5.334v5.332h-2.669v-.001zm12.001 0h-1.33v-4h-1.336v4h-1.335v-4h-1.33v4h-2.671V8.667h8.002v5.331zM10.665 10H12v2.667h-1.335V10z" />
</svg>
);
function scrollToTop(e: React.MouseEvent): void {
e.preventDefault();
window.scrollTo({ top: 0, behavior: 'smooth' });
}
export default function App(): React.ReactElement {
return (
<div className="min-h-screen bg-background text-zinc-100 font-sans selection:bg-white selection:text-black">
<nav className="fixed top-0 left-0 right-0 z-50 border-b border-zinc-800 bg-background/90 backdrop-blur-md">
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
<div className="flex h-14 items-center justify-between">
<a href="#" onClick={scrollToTop} className="flex items-center gap-2 cursor-pointer">
<div className="w-4 h-4 bg-white"></div>
<span className="text-base font-bold tracking-tight text-white font-mono">SKILLKIT</span>
</a>
<div className="flex items-center gap-2 sm:gap-4">
<a
href="#docs"
className="text-zinc-400 hover:text-white transition-colors text-sm font-mono hidden sm:block"
>
Docs
</a>
<a
href="https://www.npmjs.com/package/skillkit"
target="_blank"
rel="noreferrer"
className="text-zinc-400 hover:text-red-500 transition-colors p-2"
aria-label="npm"
>
{NPM_ICON}
</a>
<a
href="https://github.com/rohitg00/skillkit"
target="_blank"
rel="noreferrer"
className="text-zinc-400 hover:text-white transition-colors p-2"
aria-label="GitHub"
>
{GITHUB_ICON}
</a>
</div>
</div>
</div>
</nav>
<main className="pt-14">
<Hero />
<Agents />
<Features />
<Commands />
<section id="docs" className="py-12 border-b border-zinc-800 bg-surface">
<Documentation />
</section>
<section id="skills" className="py-12 border-b border-zinc-800">
<SkillGenerator />
</section>
<section id="submit" className="py-12 border-b border-zinc-800 bg-surface">
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
<div className="text-center mb-8">
<h2 className="text-2xl font-bold text-white mb-2 font-mono">Submit Your Skill</h2>
<p className="text-zinc-400 font-mono text-sm">
Share your AI agent skills with the community.
</p>
</div>
<SkillSubmitForm />
</div>
</section>
</main>
<Footer />
</div>
);
}
+39
View File
@@ -0,0 +1,39 @@
# SkillKit Documentation Website
Landing page for SkillKit - the universal CLI for managing AI agent skills.
**Live site:** https://rohitg00.github.io/skillkit/
## Development
**Prerequisites:** Node.js 20+
1. Install dependencies:
```bash
npm install
```
2. (Optional) Set `GEMINI_API_KEY` in `.env.local` for the skill generator feature
3. Run locally:
```bash
npm run dev
```
4. Build for production:
```bash
npm run build
```
## Deployment
The site is automatically deployed to GitHub Pages when changes are pushed to the `main` branch.
The deployment workflow is defined in `.github/workflows/deploy-docs.yml`.
## Tech Stack
- React 19
- Vite
- Tailwind CSS (via CDN)
- TypeScript
File diff suppressed because one or more lines are too long
+53
View File
@@ -0,0 +1,53 @@
import React from 'react';
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'outline' | 'ghost';
fullWidth?: boolean;
isLoading?: boolean;
}
const BASE_STYLES = "inline-flex items-center justify-center px-6 py-3 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-black disabled:opacity-50 font-mono tracking-tight";
const VARIANT_STYLES = {
primary: "bg-white text-black hover:bg-zinc-200 border border-white",
secondary: "bg-zinc-900 text-zinc-100 hover:bg-zinc-800 border border-zinc-800",
outline: "bg-transparent text-zinc-300 border border-zinc-700 hover:border-zinc-500 hover:text-white",
ghost: "bg-transparent text-zinc-400 hover:text-white hover:bg-zinc-900"
} as const;
export function Button({
children,
variant = 'primary',
className = '',
fullWidth = false,
isLoading = false,
disabled,
...props
}: ButtonProps): React.ReactElement {
const widthClass = fullWidth ? 'w-full' : '';
const classes = [
BASE_STYLES,
VARIANT_STYLES[variant],
widthClass,
className,
].filter(Boolean).join(' ');
return (
<button
className={classes}
disabled={disabled || isLoading}
{...props}
>
{isLoading ? (
<>
<svg className="animate-spin -ml-1 mr-2 h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
PROCESSING
</>
) : children}
</button>
);
}
+49
View File
@@ -0,0 +1,49 @@
import React from 'react';
interface CardProps {
children: React.ReactNode;
className?: string;
noPadding?: boolean;
onClick?: () => void;
onDragOver?: (e: React.DragEvent) => void;
onDragLeave?: (e: React.DragEvent) => void;
onDrop?: (e: React.DragEvent) => void;
}
export function Card({
children,
className = '',
noPadding = false,
onClick,
onDragOver,
onDragLeave,
onDrop
}: CardProps): React.ReactElement {
const paddingClass = noPadding ? '' : 'p-6';
const clickableClass = onClick ? 'cursor-pointer' : '';
function handleKeyDown(e: React.KeyboardEvent): void {
if (!onClick) return;
if (e.key === 'Enter' || e.key === ' ') {
if (e.key === ' ') {
e.preventDefault();
}
onClick();
}
}
return (
<div
className={`relative bg-black border border-zinc-800 transition-colors duration-300 ${paddingClass} ${clickableClass} ${className}`}
onClick={onClick}
role={onClick ? 'button' : undefined}
tabIndex={onClick ? 0 : undefined}
onKeyDown={onClick ? handleKeyDown : undefined}
onDragOver={onDragOver}
onDragLeave={onDragLeave}
onDrop={onDrop}
>
{children}
</div>
);
}
+103
View File
@@ -0,0 +1,103 @@
import React, { useState } from 'react';
interface CommandGroup {
name: string;
commands: Array<{ cmd: string; desc: string }>;
}
const COMMAND_GROUPS: CommandGroup[] = [
{
name: 'Core',
commands: [
{ cmd: 'install', desc: 'Install from GitHub/GitLab/local' },
{ cmd: 'sync', desc: 'Sync skills across agents' },
{ cmd: 'translate', desc: 'Convert between agent formats' },
{ cmd: 'update', desc: 'Update installed skills' },
],
},
{
name: 'Discovery',
commands: [
{ cmd: 'find', desc: 'Search marketplace (15K+ skills)' },
{ cmd: 'recommend', desc: 'AI-powered suggestions' },
{ cmd: 'check', desc: 'Dry-run update check' },
{ cmd: 'list', desc: 'View installed skills' },
],
},
{
name: 'Team',
commands: [
{ cmd: 'manifest init', desc: 'Create .skills file' },
{ cmd: 'manifest install', desc: 'Install from manifest' },
{ cmd: 'team share', desc: 'Share skills via Git' },
{ cmd: 'publish', desc: 'Submit to marketplace' },
],
},
{
name: 'Advanced',
commands: [
{ cmd: 'ui', desc: 'Launch terminal UI' },
{ cmd: 'workflow run', desc: 'Execute skill pipelines' },
{ cmd: 'command generate', desc: 'Create /slash commands' },
{ cmd: 'cicd init', desc: 'Generate CI templates' },
],
},
];
export function Commands(): React.ReactElement {
const [activeGroup, setActiveGroup] = useState(0);
const group = COMMAND_GROUPS[activeGroup];
return (
<section className="py-12 border-b border-zinc-800">
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
<div className="text-center mb-8">
<h2 className="text-xl font-bold text-white mb-2 font-mono">30+ Commands</h2>
<p className="text-zinc-500 font-mono text-sm">
Everything you need from the terminal.
</p>
</div>
<div className="flex justify-center gap-2 mb-6">
{COMMAND_GROUPS.map((g, i) => {
const isActive = i === activeGroup;
const buttonClass = isActive
? 'border-white text-white bg-zinc-900'
: 'border-zinc-800 text-zinc-500 hover:border-zinc-600 hover:text-zinc-300';
return (
<button
key={g.name}
onClick={() => setActiveGroup(i)}
className={`px-3 py-1.5 text-xs font-mono border transition-colors ${buttonClass}`}
>
{g.name}
</button>
);
})}
</div>
<div className="border border-zinc-800 bg-black/50 p-4 font-mono text-xs">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
{group.commands.map((c) => (
<div
key={c.cmd}
className="flex items-center gap-3 p-2 hover:bg-zinc-900/50 transition-colors rounded"
>
<span className="text-zinc-600">$</span>
<span className="text-white">skillkit {c.cmd}</span>
<span className="text-zinc-600 hidden sm:inline">→</span>
<span className="text-zinc-500 hidden sm:inline truncate">{c.desc}</span>
</div>
))}
</div>
</div>
<div className="mt-4 text-center">
<span className="text-zinc-600 text-xs font-mono">
Run <span className="text-zinc-400">skillkit --help</span> for all commands
</span>
</div>
</div>
</section>
);
}
+479
View File
@@ -0,0 +1,479 @@
import React, { useState } from 'react';
interface DocSection {
id: string;
title: string;
content: React.ReactNode;
}
const CodeBlock = ({ children, language = 'bash' }: { children: string; language?: string }) => (
<pre className="bg-zinc-900 border border-zinc-800 rounded-lg p-4 overflow-x-auto text-sm font-mono">
<code className="text-zinc-300">{children}</code>
</pre>
);
const Table = ({ headers, rows }: { headers: string[]; rows: string[][] }) => (
<div className="overflow-x-auto">
<table className="w-full text-sm border-collapse">
<thead>
<tr className="border-b border-zinc-700">
{headers.map((h, i) => (
<th key={i} className="text-left py-2 px-3 text-zinc-300 font-mono font-semibold">{h}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, i) => (
<tr key={i} className="border-b border-zinc-800 hover:bg-zinc-900/50">
{row.map((cell, j) => (
<td key={j} className="py-2 px-3 text-zinc-400 font-mono">{cell}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
);
const sections: DocSection[] = [
{
id: 'overview',
title: 'Overview',
content: (
<div className="space-y-4">
<p className="text-zinc-300">
SkillKit is a universal command-line interface (CLI) and programmatic toolkit for managing AI agent skills across 17+ AI coding platforms. It solves the fragmentation problem where each AI agent uses different skill formats and directory structures.
</p>
<h3 className="text-lg font-semibold text-white mt-6">Core Capabilities</h3>
<ul className="list-disc list-inside space-y-2 text-zinc-400">
<li><span className="text-white">Skill Discovery</span> - Browse 15,000+ skills from marketplace with AI-powered recommendations</li>
<li><span className="text-white">Cross-Agent Translation</span> - Automatically convert skills between 17 agent-specific formats</li>
<li><span className="text-white">Team Collaboration</span> - Share skills via .skills manifest files and publish to marketplace</li>
</ul>
</div>
),
},
{
id: 'installation',
title: 'Installation',
content: (
<div className="space-y-4">
<h3 className="text-lg font-semibold text-white">Quick Start</h3>
<CodeBlock>{`# Install globally via npm
npm install -g skillkit
# Or use npx directly
npx skillkit --help
# Or install via pnpm
pnpm add -g skillkit`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Verify Installation</h3>
<CodeBlock>{`skillkit --version
skillkit --help`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">First Steps</h3>
<CodeBlock>{`# Initialize SkillKit in your project
skillkit init
# Browse available skills
skillkit marketplace
# Get AI-powered recommendations
skillkit recommend
# Install skills from a source
skillkit install anthropics/skills`}</CodeBlock>
</div>
),
},
{
id: 'architecture',
title: 'Architecture',
content: (
<div className="space-y-4">
<p className="text-zinc-300">
SkillKit employs a three-tier design with clean separation of concerns:
</p>
<h3 className="text-lg font-semibold text-white mt-6">System Tiers</h3>
<ul className="list-disc list-inside space-y-2 text-zinc-400">
<li><span className="text-white">UI Tier</span> - CLI commands, Terminal UI (OpenTUI-based), and documentation website</li>
<li><span className="text-white">Core Logic Tier</span> - @skillkit/core for business logic; @skillkit/agents for adapter implementations</li>
<li><span className="text-white">Integration Tier</span> - File systems, Git repositories, marketplace APIs, and 17+ AI agents</li>
</ul>
<h3 className="text-lg font-semibold text-white mt-6">Monorepo Structure</h3>
<CodeBlock language="text">{`skillkit-monorepo (pnpm workspace + Turbo)
├── apps/skillkit/ → Main CLI application (bin: skillkit, sk)
├── packages/core/ → Core business logic (no internal dependencies)
├── packages/agents/ → Agent adapters (depends on core)
├── packages/cli/ → Command implementations (depends on core, agents, tui)
├── packages/tui/ → Terminal UI (depends on core, agents)
└── docs/skillkit/ → Documentation website`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Dependency Hierarchy</h3>
<ul className="list-disc list-inside space-y-2 text-zinc-400">
<li><code className="text-emerald-400">@skillkit/core</code> → Foundation (no SkillKit dependencies)</li>
<li><code className="text-emerald-400">@skillkit/agents</code> → Adapters (depends on core)</li>
<li><code className="text-emerald-400">@skillkit/cli</code>, <code className="text-emerald-400">@skillkit/tui</code> → UIs (depend on core and agents)</li>
<li><code className="text-emerald-400">skillkit</code> app → Orchestrates all packages</li>
</ul>
</div>
),
},
{
id: 'agents',
title: 'Supported Agents',
content: (
<div className="space-y-4">
<p className="text-zinc-300">
SkillKit supports 17+ AI coding agents with automatic format translation:
</p>
<Table
headers={['Agent', 'Directory', 'Format']}
rows={[
['Claude Code', '.claude/skills/', 'SKILL.md'],
['Cursor', '.cursor/skills/', '.mdc'],
['GitHub Copilot', '.github/skills/', 'Markdown'],
['Gemini CLI', '.gemini/skills/', 'SKILL.md'],
['Windsurf', '.windsurf/skills/', 'Markdown'],
['Codex', '.codex/skills/', 'SKILL.md'],
['OpenCode', '.opencode/skills/', 'SKILL.md'],
['Antigravity', '.antigravity/skills/', 'SKILL.md'],
['Amp', '.amp/skills/', 'SKILL.md'],
['Clawdbot', '.clawdbot/skills/', 'SKILL.md'],
['Droid', '.droid/skills/', 'SKILL.md'],
['Goose', '.goose/skills/', 'SKILL.md'],
['Kilo', '.kilo/skills/', 'SKILL.md'],
['Kiro CLI', '.kiro/skills/', 'SKILL.md'],
['Roo', '.roo/skills/', 'SKILL.md'],
['Trae', '.trae/skills/', 'SKILL.md'],
['Universal', 'skills/', 'SKILL.md'],
]}
/>
</div>
),
},
{
id: 'commands',
title: 'CLI Commands',
content: (
<div className="space-y-4">
<h3 className="text-lg font-semibold text-white">Skill Management</h3>
<CodeBlock>{`skillkit install <source> # Install skills from source
skillkit remove <skill> # Remove installed skill
skillkit update [skill] # Update skills
skillkit list # List installed skills
skillkit sync # Sync skills across agents
skillkit enable <skill> # Enable a skill
skillkit disable <skill> # Disable a skill`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Discovery</h3>
<CodeBlock>{`skillkit recommend # AI-powered skill recommendations
skillkit marketplace # Browse marketplace skills
skillkit find <query> # Search for skills
skillkit search <term> # Search skill content`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Translation</h3>
<CodeBlock>{`skillkit translate --from claude --to cursor <skill>
skillkit agent translate <skill> --target cursor
skillkit context sync # Sync context across agents`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Team Collaboration</h3>
<CodeBlock>{`skillkit manifest init # Initialize .skills manifest
skillkit manifest add <source> # Add source to manifest
skillkit manifest install # Install from manifest
skillkit publish # Publish skill to marketplace
skillkit cicd init # Setup CI/CD integration`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Advanced</h3>
<CodeBlock>{`skillkit ui # Launch Terminal UI
skillkit workflow # Manage workflows
skillkit memory compress # Compress memory
skillkit memory export # Export memory
skillkit test # Run skill tests
skillkit validate # Validate skill format & quality`}</CodeBlock>
</div>
),
},
{
id: 'configuration',
title: 'Configuration',
content: (
<div className="space-y-4">
<h3 className="text-lg font-semibold text-white">Project Configuration (skillkit.yaml)</h3>
<CodeBlock language="yaml">{`version: 1
agent: cursor
autoSync: true
enabledSkills:
- pdf
- xlsx
disabledSkills:
- deprecated-skill`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Team Manifest (.skills)</h3>
<CodeBlock>{`# Team-wide skill sources
anthropics/skills
vercel-labs/agent-skills
./local-skills
owner/repo@v1.2.3`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">User Preferences (~/.skillkit/preferences.json)</h3>
<CodeBlock language="json">{`{
"lastSelectedAgents": ["claude", "cursor"],
"autoSync": true,
"marketplace": {
"lastRefresh": "2024-01-01T00:00:00Z"
}
}`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">File System Layout</h3>
<CodeBlock language="text">{`project/
├── .skillkit/ # Project config & memory
├── .claude/skills/ # Claude Code skills
├── .cursor/skills/ # Cursor AI skills
├── .github/skills/ # GitHub Copilot skills
├── skills/ # Universal format
└── .skills # Team manifest file
~/.skillkit/ # Global user config
├── preferences.json
├── memory/
└── cache/`}</CodeBlock>
</div>
),
},
{
id: 'api',
title: 'API Reference',
content: (
<div className="space-y-4">
<h3 className="text-lg font-semibold text-white">Package Exports</h3>
<p className="text-zinc-300">@skillkit/core provides multiple entry points for programmatic use:</p>
<CodeBlock language="typescript">{`import { findAllSkills, findSkill } from '@skillkit/core/discovery';
import { parseSkillFile } from '@skillkit/core/parser';
import { translateSkill } from '@skillkit/core/translator';
import { syncContext } from '@skillkit/core/context';
import { getRecommendations } from '@skillkit/core/recommend';
import { evaluateSkillContent, getQualityGrade } from '@skillkit/core/quality';`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Core Functions</h3>
<CodeBlock language="typescript">{`// Discovery
findAllSkills(searchDirs: string[]): SkillInfo[]
findSkill(name: string, searchDirs: string[]): SkillInfo | null
// Parsing
parseSkillFile(filePath: string): ParsedSkill
parseSkillContent(content: string): ParsedSkill
// Translation
translateSkill(skill: ParsedSkill, targetAgent: AgentType): string
getAgentAdapter(agent: AgentType): AgentAdapter
// Quality Evaluation
evaluateSkillContent(content: string): QualityScore
evaluateSkillFile(filePath: string): QualityScore
getQualityGrade(score: number): 'A' | 'B' | 'C' | 'D' | 'F'
isHighQuality(score: QualityScore): boolean
// Recommendations
getRecommendations(context: ProjectContext): Recommendation[]`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Type Definitions</h3>
<CodeBlock language="typescript">{`interface SkillInfo {
name: string;
path: string;
agent: AgentType;
enabled: boolean;
}
interface ParsedSkill {
name: string;
description?: string;
globs?: string[];
triggers?: string[];
content: string;
frontmatter: Record<string, unknown>;
}
interface QualityScore {
overall: number;
structure: StructureScore;
clarity: ClarityScore;
specificity: SpecificityScore;
advanced: AdvancedScore;
warnings: string[];
suggestions: string[];
}
type AgentType =
| 'claude-code' | 'cursor' | 'codex' | 'gemini-cli'
| 'opencode' | 'antigravity' | 'amp' | 'clawdbot'
| 'droid' | 'github-copilot' | 'goose' | 'kilo'
| 'kiro-cli' | 'roo' | 'trae' | 'windsurf' | 'universal';`}</CodeBlock>
</div>
),
},
{
id: 'skill-format',
title: 'Skill Format',
content: (
<div className="space-y-4">
<h3 className="text-lg font-semibold text-white">SKILL.md Structure</h3>
<p className="text-zinc-300">Skills use YAML frontmatter followed by markdown content:</p>
<CodeBlock language="markdown">{`---
name: my-skill
description: A helpful skill for coding tasks
globs:
- "**/*.ts"
- "**/*.tsx"
triggers:
- "when working with TypeScript"
- "when creating React components"
---
# My Skill
## When to Use
Use this skill when:
- Working with TypeScript files
- Creating React components
## Instructions
Follow these guidelines:
1. Always use TypeScript strict mode
2. Prefer functional components
\`\`\`typescript
function Example(): JSX.Element {
return <div>Hello</div>;
}
\`\`\`
## Boundaries
This skill should NOT:
- Modify configuration files without asking
- Delete existing code without confirmation`}</CodeBlock>
<h3 className="text-lg font-semibold text-white mt-6">Quality Scoring</h3>
<p className="text-zinc-300">Skills are evaluated on four dimensions:</p>
<Table
headers={['Dimension', 'Weight', 'Criteria']}
rows={[
['Structure', '35%', 'Metadata, description, triggers, examples, boundaries'],
['Clarity', '25%', 'Line count, token count, headers, readability'],
['Specificity', '25%', 'Concrete commands, file patterns, code examples'],
['Advanced', '15%', 'No deprecated patterns, security issues, completeness'],
]}
/>
<h3 className="text-lg font-semibold text-white mt-6">Grade Scale</h3>
<Table
headers={['Grade', 'Score Range', 'Description']}
rows={[
['A', '90-100', 'Excellent - Production ready'],
['B', '80-89', 'Good - Minor improvements possible'],
['C', '70-79', 'Acceptable - Some issues to address'],
['D', '60-69', 'Poor - Significant improvements needed'],
['F', '0-59', 'Failing - Major revision required'],
]}
/>
</div>
),
},
{
id: 'tech-stack',
title: 'Technology Stack',
content: (
<div className="space-y-4">
<Table
headers={['Layer', 'Technology']}
rows={[
['CLI Framework', 'Clipanion v4'],
['TUI Framework', '@opentui/react v0.1.75'],
['Validation', 'Zod v3.24'],
['YAML Parsing', 'yaml v2.6'],
['Git Operations', 'isomorphic-git v1.27'],
['HTTP Client', 'got v14.4'],
['Build System', 'Turbo v2.3, tsup v8.3, pnpm v9.0'],
['Testing', 'Vitest v2.1'],
['Runtime', 'Node.js 18+, Bun 1.2+ (for TUI)'],
]}
/>
<h3 className="text-lg font-semibold text-white mt-6">Build Commands</h3>
<CodeBlock>{`pnpm build # Build all packages via Turbo
pnpm dev # Watch mode development
pnpm test # Unit tests via Vitest
pnpm test:e2e # End-to-end tests
pnpm typecheck # Type checking
pnpm clean # Remove build artifacts`}</CodeBlock>
</div>
),
},
];
export function Documentation(): React.ReactElement {
const [activeSection, setActiveSection] = useState('overview');
const currentSection = sections.find(s => s.id === activeSection) || sections[0];
return (
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
<div className="text-center mb-8">
<h2 className="text-2xl font-bold text-white mb-2 font-mono">Documentation</h2>
<p className="text-zinc-400 font-mono text-sm">
Complete guide to using SkillKit
</p>
<a
href="https://deepwiki.com/rohitg00/skillkit"
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-2 mt-2 text-xs text-zinc-500 hover:text-zinc-300 transition-colors"
>
<span>Powered by DeepWiki</span>
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
</a>
</div>
<div className="flex flex-col lg:flex-row gap-8">
<nav className="lg:w-48 flex-shrink-0">
<div className="sticky top-20 space-y-1">
{sections.map(section => (
<button
key={section.id}
onClick={() => setActiveSection(section.id)}
className={`w-full text-left px-3 py-2 text-sm font-mono rounded transition-colors ${
activeSection === section.id
? 'bg-white text-black'
: 'text-zinc-400 hover:text-white hover:bg-zinc-800'
}`}
>
{section.title}
</button>
))}
</div>
</nav>
<div className="flex-1 min-w-0">
<div className="bg-surface border border-zinc-800 rounded-lg p-6">
<h2 className="text-xl font-bold text-white mb-6 font-mono">{currentSection.title}</h2>
<div className="prose prose-invert prose-zinc max-w-none">
{currentSection.content}
</div>
</div>
</div>
</div>
</div>
);
}
+145
View File
@@ -0,0 +1,145 @@
import React from 'react';
interface Feature {
title: string;
description: string;
icon: React.ReactNode;
}
const FEATURES: Feature[] = [
{
title: 'Multi-Agent',
description: 'Deploy to 17 AI coding agents with one command.',
icon: (
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
)
},
{
title: 'Terminal UI',
description: 'Beautiful interactive TUI for browsing & installing.',
icon: (
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
)
},
{
title: 'Plugins',
description: 'Extend with custom plugins & hooks.',
icon: (
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 14v6m-3-3h6M6 10h2a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v2a2 2 0 002 2zm10 0h2a2 2 0 002-2V6a2 2 0 00-2-2h-2a2 2 0 00-2 2v2a2 2 0 002 2zM6 20h2a2 2 0 002-2v-2a2 2 0 00-2-2H6a2 2 0 00-2 2v2a2 2 0 002 2z" />
</svg>
)
},
{
title: 'Manifest',
description: '.skills file for team-wide consistency.',
icon: (
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
)
},
{
title: 'CI/CD',
description: 'GitHub, GitLab, CircleCI templates included.',
icon: (
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
)
},
{
title: 'Slash Commands',
description: 'Generate /commands for Claude, Cursor & more.',
icon: (
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" />
</svg>
)
}
];
const COMPARISONS = [
['Agents', '1', '17'],
['Translation', 'Manual', 'Auto'],
['Sharing', 'Copy/paste', '.skills manifest'],
['Discovery', 'Forums', 'CLI + AI'],
['CI/CD', 'Custom', 'Templates'],
] as const;
export function Features(): React.ReactElement {
return (
<section id="features" className="py-12 border-b border-zinc-800 bg-surface">
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
<div className="grid grid-cols-1 lg:grid-cols-5 gap-6 lg:gap-8 mb-10">
<div className="lg:col-span-2">
<h2 className="text-xl font-bold text-white mb-2 font-mono">Why SkillKit?</h2>
<p className="text-zinc-500 font-mono text-sm mb-6">
Universal bridge for AI coding agents.
</p>
<div className="flex gap-6 sm:gap-8">
<div>
<div className="text-2xl sm:text-3xl font-bold text-white font-mono">17</div>
<div className="text-zinc-600 text-[10px] sm:text-xs font-mono">Agents</div>
</div>
<div>
<div className="text-2xl sm:text-3xl font-bold text-white font-mono">30+</div>
<div className="text-zinc-600 text-[10px] sm:text-xs font-mono">Commands</div>
</div>
<div>
<div className="text-2xl sm:text-3xl font-bold text-white font-mono">15K</div>
<div className="text-zinc-600 text-[10px] sm:text-xs font-mono">Skills</div>
</div>
</div>
</div>
<div className="lg:col-span-3 border border-zinc-800 bg-black/50 p-4 font-mono text-xs backdrop-blur-sm">
<div className="grid grid-cols-3 gap-2 border-b border-zinc-800 pb-2 mb-3 text-zinc-500 uppercase tracking-wider text-[10px]">
<div>Feature</div>
<div className="text-center">Without</div>
<div className="text-right">SkillKit</div>
</div>
<div className="space-y-1">
{COMPARISONS.map(([feature, without, withSkillKit], index) => (
<div
key={feature}
className="grid grid-cols-3 gap-2 items-center py-1.5 hover:bg-zinc-900/50 transition-colors -mx-2 px-2 rounded"
style={{ animationDelay: `${index * 100}ms` }}
>
<div className="text-zinc-300">{feature}</div>
<div className="text-center text-zinc-600">{without}</div>
<div className="text-right text-white font-medium">{withSkillKit}</div>
</div>
))}
</div>
</div>
</div>
<div className="grid grid-cols-1 xs:grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
{FEATURES.map((feature, index) => (
<div
key={feature.title}
className="group relative p-4 border border-zinc-800 bg-zinc-900/30 hover:bg-zinc-900/80 hover:border-zinc-700 transition-all duration-300 cursor-default"
style={{ animationDelay: `${index * 50}ms` }}
>
<div className="absolute inset-0 bg-gradient-to-b from-zinc-800/0 to-zinc-800/20 opacity-0 group-hover:opacity-100 transition-opacity"></div>
<div className="relative">
<div className="text-zinc-500 group-hover:text-white transition-colors mb-2">
{feature.icon}
</div>
<h4 className="text-xs font-bold text-white mb-1 font-mono">{feature.title}</h4>
<p className="text-zinc-600 text-[10px] leading-relaxed font-mono group-hover:text-zinc-400 transition-colors">
{feature.description}
</p>
</div>
</div>
))}
</div>
</div>
</section>
);
}
+41
View File
@@ -0,0 +1,41 @@
import React from 'react';
const GITHUB_ICON = (
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
<path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd" />
</svg>
);
export function Footer(): React.ReactElement {
const currentYear = new Date().getFullYear();
return (
<footer className="border-t border-border py-6 bg-black">
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 flex flex-col sm:flex-row justify-between items-center gap-3">
<div className="flex flex-col sm:flex-row items-center gap-2 sm:gap-4 text-center sm:text-left">
<p className="text-zinc-500 text-xs font-mono">
&copy; {currentYear} SKILLKIT
</p>
<span className="hidden sm:inline text-zinc-700">•</span>
<a
href="https://agentskills.io"
target="_blank"
rel="noreferrer"
className="text-zinc-600 hover:text-zinc-400 text-xs font-mono transition-colors"
>
Agent Skills standard
</a>
</div>
<a
href="https://github.com/rohitg00/skillkit"
target="_blank"
rel="noopener noreferrer"
aria-label="SkillKit on GitHub"
className="text-zinc-500 hover:text-white transition-colors"
>
{GITHUB_ICON}
</a>
</div>
</footer>
);
}
+211
View File
@@ -0,0 +1,211 @@
import React, { useState, useEffect } from 'react';
import { Button } from './Button';
const ASCII_LOGO = `███████╗██╗ ██╗██╗██╗ ██╗ ██╗ ██╗██╗████████╗
██╔════╝██║ ██╔╝██║██║ ██║ ██║ ██╔╝██║╚══██╔══╝
███████╗█████╔╝ ██║██║ ██║ █████╔╝ ██║ ██║
╚════██║██╔═██╗ ██║██║ ██║ ██╔═██╗ ██║ ██║
███████║██║ ██╗██║███████╗███████╗██║ ██╗██║ ██║
╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝`;
interface TerminalLine {
type: 'cmd' | 'out';
text: string;
}
const TERMINAL_LINES: TerminalLine[] = [
{ type: 'cmd', text: 'skillkit find react' },
{ type: 'out', text: ' ■ react-patterns ★★★★★' },
{ type: 'out', text: ' ■ react-testing ★★★★☆' },
{ type: 'cmd', text: 'skillkit install anthropics/skills' },
{ type: 'out', text: '→ 3 skills → 5 agents' },
{ type: 'cmd', text: 'skillkit ui' },
{ type: 'out', text: '→ Launching TUI...' },
{ type: 'cmd', text: 'skillkit check' },
{ type: 'out', text: ' ✓ All skills up to date' },
{ type: 'cmd', text: 'skillkit manifest install' },
{ type: 'out', text: '→ 12 skills from .skills' },
];
const FADE_ANIMATION_STYLES = `
@keyframes fade-in {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-fade-in {
animation: fade-in 0.6s ease-out forwards;
}
.animate-fade-in-delay {
animation: fade-in 0.6s ease-out 0.2s forwards;
opacity: 0;
}
`;
const CHECK_ICON = (
<svg className="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
);
const COPY_ICON = (
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
</svg>
);
export function Hero(): React.ReactElement {
const [copied, setCopied] = useState(false);
const [visibleLines, setVisibleLines] = useState(0);
const [typingIndex, setTypingIndex] = useState(0);
const [currentText, setCurrentText] = useState('');
useEffect(() => {
if (visibleLines >= TERMINAL_LINES.length) {
const resetTimer = setTimeout(() => {
setVisibleLines(0);
setTypingIndex(0);
setCurrentText('');
}, 3000);
return () => clearTimeout(resetTimer);
}
const line = TERMINAL_LINES[visibleLines];
if (line.type === 'cmd') {
if (typingIndex < line.text.length) {
const timer = setTimeout(() => {
setCurrentText(line.text.slice(0, typingIndex + 1));
setTypingIndex(typingIndex + 1);
}, 40);
return () => clearTimeout(timer);
}
const timer = setTimeout(() => {
setVisibleLines(visibleLines + 1);
setTypingIndex(0);
setCurrentText('');
}, 200);
return () => clearTimeout(timer);
}
const timer = setTimeout(() => {
setVisibleLines(visibleLines + 1);
}, 150);
return () => clearTimeout(timer);
}, [visibleLines, typingIndex]);
async function copyInstall(): Promise<void> {
try {
await navigator.clipboard.writeText('npx skillkit@latest');
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
// Clipboard API failed, silently ignore
}
}
function openGitHub(): void {
window.open('https://github.com/rohitg00/skillkit', '_blank', 'noopener,noreferrer');
}
const isTyping = visibleLines < TERMINAL_LINES.length && TERMINAL_LINES[visibleLines].type === 'cmd';
const isComplete = visibleLines >= TERMINAL_LINES.length;
return (
<div className="relative border-b border-zinc-800 overflow-hidden">
<div className="absolute inset-0 bg-gradient-to-b from-zinc-900/50 to-transparent pointer-events-none"></div>
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 pt-8 pb-10 relative">
<div className="hidden lg:block mb-6 overflow-hidden">
<pre className="text-zinc-800 text-[8px] leading-none font-mono select-none animate-pulse">
{ASCII_LOGO}
</pre>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8 items-start">
<div className="animate-fade-in">
<div className="inline-flex items-center space-x-2 border border-zinc-800 bg-zinc-900/50 px-2 py-0.5 mb-3 backdrop-blur-sm">
<span className="flex h-1.5 w-1.5 bg-white rounded-full"></span>
<span className="text-xs font-mono text-zinc-400">v1.7.5</span>
</div>
<h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold tracking-tight text-white mb-3 font-mono">
Universal Skills for<br />
<span className="text-zinc-500">AI Coding Agents</span>
</h1>
<p className="text-sm text-zinc-400 mb-5 max-w-lg font-mono leading-relaxed">
One CLI to install, sync, and manage skills across Claude Code, Cursor,
Windsurf, Copilot, and 13 more agents. 15,000+ skills ready to use.
</p>
<div className="flex flex-wrap items-center gap-3 mb-4">
<button
onClick={copyInstall}
className="inline-flex items-center bg-black border border-zinc-700 px-3 py-2 hover:border-zinc-500 transition-colors"
>
<span className="text-zinc-500 mr-2 select-none">$</span>
<span className="font-mono text-zinc-100 text-sm">npx skillkit@latest</span>
<span className="ml-2 text-zinc-500 hover:text-white transition-colors flex items-center gap-1">
{copied ? (
<>
{CHECK_ICON}
<span className="text-xs text-green-400">Copied!</span>
</>
) : (
COPY_ICON
)}
</span>
</button>
<Button variant="outline" onClick={openGitHub}>
GITHUB
</Button>
</div>
</div>
<div className="hidden lg:block relative animate-fade-in-delay w-full">
<div className="absolute -inset-1 bg-gradient-to-r from-zinc-800 via-zinc-700 to-zinc-800 rounded-lg opacity-20 blur-lg"></div>
<div className="relative border border-zinc-800 bg-black rounded-lg overflow-hidden">
<div className="flex items-center gap-1.5 px-3 py-2 border-b border-zinc-800 bg-zinc-900/50">
<div className="w-2.5 h-2.5 rounded-full bg-zinc-700"></div>
<div className="w-2.5 h-2.5 rounded-full bg-zinc-700"></div>
<div className="w-2.5 h-2.5 rounded-full bg-zinc-700"></div>
<span className="ml-2 text-zinc-500 text-xs font-mono">skillkit</span>
</div>
<div className="p-4 font-mono text-xs min-h-[200px] max-h-[280px]">
{TERMINAL_LINES.slice(0, visibleLines).map((line, index) => (
<div key={index} className="mb-1">
{line.type === 'cmd' ? (
<div className="flex items-center">
<span className="text-zinc-600 mr-2">$</span>
<span className="text-zinc-100">{line.text}</span>
</div>
) : (
<div className="pl-4 text-zinc-500">
<span className="text-zinc-400">{line.text.slice(0, 1)}</span>
{line.text.slice(1)}
</div>
)}
</div>
))}
{isTyping && (
<div className="flex items-center">
<span className="text-zinc-600 mr-2">$</span>
<span className="text-zinc-100">{currentText}</span>
<span className="w-2 h-4 bg-zinc-400 ml-0.5 animate-pulse"></span>
</div>
)}
{isComplete && (
<div className="flex items-center mt-1">
<span className="text-zinc-600 mr-2">$</span>
<span className="w-2 h-4 bg-zinc-600 animate-pulse"></span>
</div>
)}
</div>
</div>
</div>
</div>
</div>
<style>{FADE_ANIMATION_STYLES}</style>
</div>
);
}
+650
View File
@@ -0,0 +1,650 @@
import React, { useState, useRef, useEffect } from 'react';
import { Button } from './Button';
import { Card } from './Card';
import { generateAgentSkill } from '../services/geminiService';
import { searchSkills, IndexedSkill } from '../data/skills-index';
import { AgentSkill, LoadingState } from '../types';
interface PriorityBadgeProps {
priority: string;
}
type ViewMode = 'search' | 'marketplace' | 'generated' | 'content';
const PRIORITY_COLORS = {
must: 'bg-red-900/50 text-red-300 border-red-800',
should: 'bg-yellow-900/50 text-yellow-300 border-yellow-800',
may: 'bg-blue-900/50 text-blue-300 border-blue-800',
} as const;
function PriorityBadge({ priority }: PriorityBadgeProps): React.ReactElement {
const colorClass = PRIORITY_COLORS[priority as keyof typeof PRIORITY_COLORS] || PRIORITY_COLORS.may;
return (
<span className={`text-xs px-2 py-0.5 border font-mono uppercase ${colorClass}`}>
{priority}
</span>
);
}
function generateSkillMd(skill: AgentSkill): string {
const frontmatter = `---
name: "${skill.name}"
description: "${skill.description}"
version: "${skill.version}"
tags: [${skill.tags.map(t => `"${t}"`).join(', ')}]
${skill.filePatterns?.length ? `globs: [${skill.filePatterns.map(p => `"${p}"`).join(', ')}]` : ''}
---`;
const principlesSection = skill.principles.map(p =>
`### ${p.priority.toUpperCase()}: ${p.title}\n\n${p.description}`
).join('\n\n');
const patternsSection = skill.patterns.map(p =>
`### ${p.name}\n\n${p.description}\n\n\`\`\`${p.language || 'typescript'}\n${p.example}\n\`\`\``
).join('\n\n');
const antiPatternsSection = skill.antiPatterns.map(ap => {
let content = `### ${ap.name}\n\n${ap.description}`;
if (ap.badExample) {
content += `\n\n**Bad:**\n\`\`\`typescript\n${ap.badExample}\n\`\`\``;
}
if (ap.goodExample) {
content += `\n\n**Good:**\n\`\`\`typescript\n${ap.goodExample}\n\`\`\``;
}
return content;
}).join('\n\n');
const content = `# ${skill.title}
${skill.description}
## When to Apply
${skill.applicability}
${skill.filePatterns?.length ? `**File patterns:** ${skill.filePatterns.map(p => `\`${p}\``).join(', ')}` : ''}
## Principles
${principlesSection}
## Patterns
${patternsSection}
## Anti-Patterns
${antiPatternsSection}
${skill.references?.length ? `## References\n\n${skill.references.map(r => `- ${r}`).join('\n')}` : ''}
`;
return `${frontmatter}\n\n${content}`;
}
function downloadContent(content: string, filename: string): void {
const blob = new Blob([content], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// localStorage cache for AI-generated skills
const CACHE_KEY = 'skillkit_ai_cache';
const CACHE_VERSION = 1;
const MAX_CACHE_ENTRIES = 50;
const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
interface CachedSkill {
skill: AgentSkill;
query: string;
timestamp: number;
}
interface SkillCache {
version: number;
skills: Record<string, CachedSkill>;
}
function normalizeQuery(query: string): string {
return query.toLowerCase().trim().replace(/\s+/g, ' ');
}
function getSkillCache(): SkillCache {
try {
const cached = localStorage.getItem(CACHE_KEY);
if (cached) {
const parsed = JSON.parse(cached) as SkillCache;
if (parsed.version === CACHE_VERSION) {
// Prune expired entries
const now = Date.now();
let mutated = false;
for (const [key, value] of Object.entries(parsed.skills)) {
if (!value?.timestamp || now - value.timestamp >= CACHE_TTL_MS) {
delete parsed.skills[key];
mutated = true;
}
}
if (mutated) {
localStorage.setItem(CACHE_KEY, JSON.stringify(parsed));
}
return parsed;
}
}
} catch {
// Ignore parse errors
}
return { version: CACHE_VERSION, skills: {} };
}
function getCachedSkill(query: string): AgentSkill | null {
const cache = getSkillCache();
const key = normalizeQuery(query);
const cached = cache.skills[key];
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
return cached.skill;
}
return null;
}
function setCachedSkill(query: string, skill: AgentSkill): void {
try {
const cache = getSkillCache();
const key = normalizeQuery(query);
cache.skills[key] = {
skill,
query: key,
timestamp: Date.now(),
};
// Enforce max entries limit
const entries = Object.entries(cache.skills);
if (entries.length > MAX_CACHE_ENTRIES) {
entries
.sort((a, b) => a[1].timestamp - b[1].timestamp)
.slice(0, entries.length - MAX_CACHE_ENTRIES)
.forEach(([k]) => delete cache.skills[k]);
}
localStorage.setItem(CACHE_KEY, JSON.stringify(cache));
} catch {
// Ignore storage errors (quota exceeded, etc.)
}
}
export function SkillGenerator(): React.ReactElement {
const [input, setInput] = useState('');
const [status, setStatus] = useState<LoadingState>(LoadingState.IDLE);
const [viewMode, setViewMode] = useState<ViewMode>('search');
const [marketplaceResults, setMarketplaceResults] = useState<IndexedSkill[]>([]);
const [selectedSkill, setSelectedSkill] = useState<IndexedSkill | null>(null);
const [skillContent, setSkillContent] = useState<string | null>(null);
const [generatedSkill, setGeneratedSkill] = useState<AgentSkill | null>(null);
const [isFromCache, setIsFromCache] = useState(false);
const [activeTab, setActiveTab] = useState<'principles' | 'patterns' | 'antipatterns'>('principles');
const [error, setError] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
function handleSearch(e: React.FormEvent): void {
e.preventDefault();
if (!input.trim()) return;
setError(null);
setSelectedSkill(null);
setSkillContent(null);
setGeneratedSkill(null);
const results = searchSkills(input);
setMarketplaceResults(results);
setViewMode(results.length > 0 ? 'marketplace' : 'search');
setStatus(LoadingState.SUCCESS);
}
async function handleViewSkill(skill: IndexedSkill): Promise<void> {
setSelectedSkill(skill);
setSkillContent(null);
setViewMode('content');
if (skill.rawUrl) {
setStatus(LoadingState.LOADING);
try {
const response = await fetch(skill.rawUrl);
if (response.ok) {
const content = await response.text();
setSkillContent(content);
}
} catch {
// Silently handle fetch errors
}
setStatus(LoadingState.SUCCESS);
}
}
async function handleGenerateWithAI(): Promise<void> {
setError(null);
// Check cache first
const cached = getCachedSkill(input);
if (cached) {
setGeneratedSkill(cached);
setIsFromCache(true);
setViewMode('generated');
setStatus(LoadingState.SUCCESS);
return;
}
setStatus(LoadingState.LOADING);
setIsFromCache(false);
try {
const result = await generateAgentSkill(input);
setGeneratedSkill(result);
setCachedSkill(input, result); // Cache the result
setViewMode('generated');
setStatus(LoadingState.SUCCESS);
} catch {
setError("Failed to generate skill. Please try again.");
setStatus(LoadingState.ERROR);
}
}
function submitToMarketplace(): void {
if (!generatedSkill) return;
const slug = generatedSkill.name.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
const skillContent = generateSkillMd(generatedSkill);
const body = `## 📤 AI-Generated Skill: ${generatedSkill.title}
### Skill Details
- **Name:** ${generatedSkill.name}
- **Description:** ${generatedSkill.description}
- **Tags:** ${generatedSkill.tags.join(', ')}
- **Version:** ${generatedSkill.version}
### SKILL.md Content
<details>
<summary>Click to expand</summary>
\`\`\`markdown
${skillContent.slice(0, 4000)}${skillContent.length > 4000 ? '\n...(truncated)' : ''}
\`\`\`
</details>
### Checklist for Maintainer
- [ ] Review skill content for quality
- [ ] Add to \`marketplace/skills.json\`
---
**Generated via:** AI Skill Generator
**Search query:** "${input}"`;
const title = encodeURIComponent(`[AI Skill] ${generatedSkill.title}`);
const encodedBody = encodeURIComponent(body);
const url = `https://github.com/rohitg00/skillkit/issues/new?title=${title}&body=${encodedBody}&labels=ai-generated,skill-submission`;
window.open(url, '_blank', 'noopener,noreferrer');
}
function handleBack(): void {
switch (viewMode) {
case 'content':
setViewMode('marketplace');
setSelectedSkill(null);
setSkillContent(null);
break;
case 'generated':
setViewMode(marketplaceResults.length > 0 ? 'marketplace' : 'search');
setGeneratedSkill(null);
break;
default:
setViewMode('search');
setMarketplaceResults([]);
}
}
function downloadSkillMd(): void {
if (skillContent) {
downloadContent(skillContent, 'SKILL.md');
}
}
function downloadGeneratedSkillMd(): void {
if (generatedSkill) {
downloadContent(generateSkillMd(generatedSkill), 'SKILL.md');
}
}
// Focus input only after user interaction, not on initial page load
useEffect(() => {
if (status === LoadingState.SUCCESS && inputRef.current) {
inputRef.current.focus({ preventScroll: true });
}
}, [status]);
return (
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 py-8">
<div className="mb-6">
<h2 className="text-xl font-bold text-white mb-1 font-sans">Skill Finder</h2>
<p className="text-zinc-400 font-mono text-xs">
Search the marketplace or generate new skills with AI.
</p>
</div>
<form onSubmit={handleSearch} className="mb-6">
<div className="flex flex-col sm:flex-row gap-3">
<input
ref={inputRef}
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="e.g., React hooks, TypeScript, Next.js..."
className="flex-1 bg-surface border border-zinc-700 text-white px-4 py-3 focus:ring-2 focus:ring-white focus:border-transparent outline-none font-mono text-sm placeholder-zinc-600"
disabled={status === LoadingState.LOADING}
/>
<Button type="submit" isLoading={status === LoadingState.LOADING} className="sm:w-auto w-full">
SEARCH
</Button>
</div>
{error && <p className="mt-2 text-red-400 font-mono text-xs">{error}</p>}
</form>
{viewMode !== 'search' && status !== LoadingState.LOADING && (
<button
onClick={handleBack}
className="mb-6 text-zinc-400 hover:text-white font-mono text-sm flex items-center gap-2 transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
Back
</button>
)}
{viewMode === 'marketplace' && status === LoadingState.SUCCESS && (
<div className="animate-fade-in-up">
<div className="flex items-center justify-between mb-6">
<h3 className="text-lg font-mono text-zinc-300">
Found {marketplaceResults.length} skill{marketplaceResults.length !== 1 ? 's' : ''} in marketplace
</h3>
</div>
<div className="space-y-3 mb-8">
{marketplaceResults.map((skill) => (
<Card
key={skill.id}
className="hover:border-zinc-500 cursor-pointer transition-all"
onClick={() => handleViewSkill(skill)}
>
<div className="flex items-start justify-between">
<div className="flex-1">
<h4 className="text-lg font-semibold text-white mb-1">{skill.name}</h4>
<p className="text-zinc-400 text-sm mb-2">{skill.description || 'No description'}</p>
<div className="flex items-center gap-2 text-xs text-zinc-500 font-mono">
<span>{skill.source}</span>
</div>
</div>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-zinc-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</div>
{skill.tags.length > 0 && (
<div className="flex flex-wrap gap-1 mt-3">
{skill.tags.slice(0, 5).map((tag, idx) => (
<span key={idx} className="text-xs bg-zinc-900 text-zinc-500 px-2 py-0.5 border border-zinc-800">
{tag}
</span>
))}
</div>
)}
</Card>
))}
</div>
<div className="border-t border-zinc-800 pt-6">
<p className="text-zinc-500 font-mono text-sm mb-4">
Don't see what you need? Generate a custom skill with AI.
</p>
<Button onClick={handleGenerateWithAI} isLoading={status === LoadingState.LOADING}>
GENERATE WITH AI
</Button>
</div>
</div>
)}
{viewMode === 'search' && status === LoadingState.SUCCESS && marketplaceResults.length === 0 && input && (
<div className="animate-fade-in-up text-center py-4">
<div className="text-zinc-500 font-mono text-sm mb-4">
No skills found for "{input}" in the marketplace.
</div>
<Button onClick={handleGenerateWithAI}>
GENERATE WITH AI
</Button>
</div>
)}
{viewMode === 'content' && selectedSkill && (
<div className="animate-fade-in-up">
<div className="flex items-start justify-between mb-6 border-b border-zinc-800 pb-6">
<div>
<h3 className="text-2xl font-bold text-white mb-2">{selectedSkill.name}</h3>
<p className="text-zinc-400 font-mono text-sm mb-2">{selectedSkill.description}</p>
<div className="flex items-center gap-2 text-xs text-zinc-500 font-mono">
<span>{selectedSkill.source}</span>
{selectedSkill.sourceUrl && (
<>
<span>•</span>
<a href={selectedSkill.sourceUrl} target="_blank" rel="noreferrer" className="hover:text-white">
View on GitHub
</a>
</>
)}
</div>
</div>
{skillContent && (
<button
onClick={downloadSkillMd}
className="flex items-center gap-2 bg-white text-black px-4 py-2 font-mono text-sm hover:bg-zinc-200 transition-colors shrink-0 ml-4"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
DOWNLOAD
</button>
)}
</div>
{status === LoadingState.LOADING ? (
<div className="text-zinc-500 font-mono text-sm">Loading content...</div>
) : skillContent ? (
<pre className="bg-zinc-950 border border-zinc-800 p-6 overflow-x-auto text-sm max-h-[600px] overflow-y-auto">
<code className="text-zinc-300 font-mono whitespace-pre-wrap">{skillContent}</code>
</pre>
) : (
<div className="bg-zinc-950 border border-zinc-800 p-6">
<p className="text-zinc-400 font-mono text-sm mb-4">
Skill content not available for direct preview.
</p>
<a
href={selectedSkill.sourceUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-2 bg-zinc-800 text-white px-4 py-2 font-mono text-sm hover:bg-zinc-700 transition-colors"
>
View on GitHub
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
</a>
</div>
)}
<div className="mt-6 pt-6 border-t border-zinc-800">
<p className="text-zinc-500 font-mono text-sm mb-3">Install with SkillKit:</p>
<pre className="bg-zinc-950 border border-zinc-800 p-4 text-sm overflow-x-auto">
<code className="text-zinc-300 font-mono text-xs sm:text-sm whitespace-nowrap">
npx skillkit install {selectedSkill.id.split('/').slice(0, 2).join('/')}
</code>
</pre>
</div>
</div>
)}
{viewMode === 'generated' && generatedSkill && (
<div className="animate-fade-in-up">
<div className="flex items-start justify-between mb-8 border-b border-zinc-800 pb-6">
<div className="flex-1">
<div className="flex flex-wrap items-center gap-2 mb-2">
<h3 className="text-xl sm:text-2xl font-bold text-white">{generatedSkill.title}</h3>
<span className="text-xs font-mono text-zinc-500 bg-zinc-900 px-2 py-1 border border-zinc-800">
v{generatedSkill.version}
</span>
<span className="text-xs font-mono text-purple-400 bg-purple-900/30 px-2 py-1 border border-purple-800/50">
AI Generated
</span>
{isFromCache && (
<span className="text-xs font-mono text-green-400 bg-green-900/30 px-2 py-1 border border-green-800/50">
Cached
</span>
)}
</div>
<p className="text-zinc-400 font-mono text-sm mb-4">{generatedSkill.description}</p>
<div className="flex flex-wrap gap-2">
{generatedSkill.tags.map((tag, idx) => (
<span key={idx} className="text-xs bg-zinc-900 text-zinc-400 px-2 py-1 border border-zinc-800">
{tag}
</span>
))}
</div>
</div>
<div className="flex flex-col sm:flex-row gap-2 shrink-0 ml-4">
<button
onClick={downloadGeneratedSkillMd}
className="flex items-center justify-center gap-2 bg-white text-black px-4 py-2 font-mono text-sm hover:bg-zinc-200 transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
DOWNLOAD
</button>
<button
onClick={submitToMarketplace}
className="flex items-center justify-center gap-2 bg-purple-600 text-white px-4 py-2 font-mono text-sm hover:bg-purple-500 transition-colors"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
</svg>
SUBMIT
</button>
</div>
</div>
<Card className="mb-6">
<h4 className="text-sm font-mono text-zinc-500 uppercase tracking-wider mb-2">When to Apply</h4>
<p className="text-zinc-300">{generatedSkill.applicability}</p>
{generatedSkill.filePatterns && generatedSkill.filePatterns.length > 0 && (
<div className="mt-3 flex flex-wrap gap-2">
{generatedSkill.filePatterns.map((pattern, idx) => (
<code key={idx} className="text-xs bg-zinc-900 text-zinc-300 px-2 py-1 border border-zinc-800">
{pattern}
</code>
))}
</div>
)}
</Card>
<div className="flex border-b border-zinc-800 mb-6">
{(['principles', 'patterns', 'antipatterns'] as const).map((tab) => (
<button
key={tab}
onClick={() => setActiveTab(tab)}
className={`px-6 py-3 font-mono text-sm uppercase tracking-wider transition-colors ${
activeTab === tab
? 'text-white border-b-2 border-white -mb-px'
: 'text-zinc-500 hover:text-zinc-300'
}`}
>
{tab === 'antipatterns' ? 'Anti-Patterns' : tab}
<span className="ml-2 text-xs text-zinc-600">
({tab === 'principles' ? generatedSkill.principles.length : tab === 'patterns' ? generatedSkill.patterns.length : generatedSkill.antiPatterns.length})
</span>
</button>
))}
</div>
<div className="space-y-4">
{activeTab === 'principles' && generatedSkill.principles.map((principle, idx) => (
<Card key={idx} className="hover:border-zinc-600 transition-colors">
<div className="flex items-start justify-between gap-4 mb-2">
<h4 className="text-lg font-semibold text-white">{principle.title}</h4>
<PriorityBadge priority={principle.priority} />
</div>
<p className="text-zinc-400 leading-relaxed">{principle.description}</p>
</Card>
))}
{activeTab === 'patterns' && generatedSkill.patterns.map((pattern, idx) => (
<Card key={idx} className="hover:border-zinc-600 transition-colors">
<h4 className="text-lg font-semibold text-white mb-2">{pattern.name}</h4>
<p className="text-zinc-400 mb-4">{pattern.description}</p>
<pre className="bg-zinc-950 border border-zinc-800 p-4 overflow-x-auto text-sm">
<code className="text-zinc-300 font-mono">{pattern.example}</code>
</pre>
</Card>
))}
{activeTab === 'antipatterns' && generatedSkill.antiPatterns.map((ap, idx) => (
<Card key={idx} className="hover:border-zinc-600 transition-colors border-red-900/30">
<h4 className="text-lg font-semibold text-white mb-2">{ap.name}</h4>
<p className="text-zinc-400 mb-4">{ap.description}</p>
{ap.badExample && (
<div className="mb-4">
<div className="text-xs font-mono text-red-400 mb-1 uppercase">Bad</div>
<pre className="bg-red-950/20 border border-red-900/30 p-4 overflow-x-auto text-sm">
<code className="text-red-300 font-mono">{ap.badExample}</code>
</pre>
</div>
)}
{ap.goodExample && (
<div>
<div className="text-xs font-mono text-zinc-300 mb-1 uppercase">Good</div>
<pre className="bg-zinc-900/50 border border-zinc-700 p-4 overflow-x-auto text-sm">
<code className="text-zinc-200 font-mono">{ap.goodExample}</code>
</pre>
</div>
)}
</Card>
))}
</div>
{generatedSkill.references && generatedSkill.references.length > 0 && (
<div className="mt-8 pt-6 border-t border-zinc-800">
<h4 className="text-sm font-mono text-zinc-500 uppercase tracking-wider mb-3">References</h4>
<ul className="space-y-1">
{generatedSkill.references.map((ref, idx) => (
<li key={idx}>
<a
href={ref}
target="_blank"
rel="noreferrer"
className="text-zinc-400 hover:text-white font-mono text-sm transition-colors"
>
{ref}
</a>
</li>
))}
</ul>
</div>
)}
</div>
)}
</div>
);
}
@@ -0,0 +1,551 @@
import React, { useState, useCallback } from 'react';
import { Card } from './Card';
type Mode = 'upload' | 'import';
interface SkillFormData {
slug: string;
displayName: string;
description: string;
version: string;
tags: string;
repoOwner: string;
repoName: string;
skillPath: string;
authorGithub: string;
skillContent: string;
}
const INITIAL_FORM: SkillFormData = {
slug: '',
displayName: '',
description: '',
version: '1.0.0',
tags: '',
repoOwner: '',
repoName: '',
skillPath: '',
authorGithub: '',
skillContent: '',
};
const TAG_SUGGESTIONS = [
'react', 'typescript', 'nextjs', 'python', 'rust', 'go',
'testing', 'api', 'database', 'devops', 'security', 'mobile',
] as const;
const GITHUB_ICON = (
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
<path fillRule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clipRule="evenodd" />
</svg>
);
export function SkillSubmitForm(): React.ReactElement {
const [mode, setMode] = useState<Mode>('import');
const [form, setForm] = useState<SkillFormData>(INITIAL_FORM);
const [isDragging, setIsDragging] = useState(false);
const [fileName, setFileName] = useState<string | null>(null);
const [githubUrl, setGithubUrl] = useState('');
const [isDetecting, setIsDetecting] = useState(false);
const [detectError, setDetectError] = useState<string | null>(null);
function updateField(field: keyof SkillFormData, value: string): void {
setForm(prev => {
const updated = { ...prev, [field]: value };
if (field === 'displayName' && !prev.slug) {
updated.slug = value.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
}
return updated;
});
}
function addTag(tag: string): void {
const currentTags = form.tags.split(',').map(t => t.trim()).filter(Boolean);
if (!currentTags.includes(tag)) {
updateField('tags', [...currentTags, tag].join(', '));
}
}
function parseSkillContent(content: string): void {
const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
if (frontmatterMatch) {
const fm = frontmatterMatch[1];
const nameMatch = fm.match(/name:\s*["']?([^"'\n]+)["']?/);
const descMatch = fm.match(/description:\s*["']?([^"'\n]+)["']?/);
const tagsMatch = fm.match(/tags:\s*\[([^\]]+)\]/);
const versionMatch = fm.match(/version:\s*["']?([^"'\n]+)["']?/);
if (nameMatch) updateField('displayName', nameMatch[1].trim());
if (descMatch) updateField('description', descMatch[1].trim());
if (versionMatch) updateField('version', versionMatch[1].trim());
if (tagsMatch) {
const tags = tagsMatch[1].replace(/["']/g, '').split(',').map(t => t.trim()).join(', ');
updateField('tags', tags);
}
}
updateField('skillContent', content);
}
async function handleDetect(): Promise<void> {
if (!githubUrl) return;
setIsDetecting(true);
setDetectError(null);
try {
const urlMatch = githubUrl.match(/github\.com\/([^\/]+)\/([^\/]+)(?:\/(?:tree|blob)\/[^\/]+\/(.+))?/);
if (!urlMatch) {
throw new Error('Invalid GitHub URL');
}
const [, owner, repo, path = ''] = urlMatch;
const apiUrl = `https://api.github.com/repos/${owner}/${repo}`;
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('Repository not found or not public');
}
const repoData = await response.json();
updateField('repoOwner', owner);
updateField('repoName', repo);
updateField('authorGithub', owner);
updateField('displayName', repoData.name.replace(/-/g, ' ').replace(/\b\w/g, (c: string) => c.toUpperCase()));
updateField('description', repoData.description || '');
const slug = path ? path.split('/').filter(Boolean).pop() || repo : repo;
updateField('slug', slug.toLowerCase().replace(/[^a-z0-9-]/g, '-'));
if (repoData.topics && repoData.topics.length > 0) {
updateField('tags', repoData.topics.slice(0, 5).join(', '));
} else {
const inferredTags: string[] = [];
const nameLC = (repo + ' ' + (repoData.description || '')).toLowerCase();
if (nameLC.includes('react')) inferredTags.push('react');
if (nameLC.includes('typescript') || nameLC.includes('ts')) inferredTags.push('typescript');
if (nameLC.includes('python')) inferredTags.push('python');
if (nameLC.includes('skill')) inferredTags.push('skills');
if (inferredTags.length > 0) {
updateField('tags', inferredTags.join(', '));
}
}
updateField('skillContent', `[Linked from GitHub: ${owner}/${repo}]`);
updateField('skillPath', path || '/');
} catch (err) {
setDetectError(err instanceof Error ? err.message : 'Detection failed');
} finally {
setIsDetecting(false);
}
}
const handleDragOver = useCallback(function(e: React.DragEvent): void {
e.preventDefault();
setIsDragging(true);
}, []);
const handleDragLeave = useCallback(function(e: React.DragEvent): void {
e.preventDefault();
setIsDragging(false);
}, []);
const processMarkdownFile = useCallback(function(file: File): void {
setFileName(file.name);
const reader = new FileReader();
reader.onload = (event) => {
parseSkillContent(event.target?.result as string);
};
reader.readAsText(file);
}, []);
const handleDrop = useCallback(function(e: React.DragEvent): void {
e.preventDefault();
setIsDragging(false);
const files = Array.from(e.dataTransfer.files);
const mdFile = files.find(f => f.name.endsWith('.md'));
if (mdFile) {
processMarkdownFile(mdFile);
}
}, [processMarkdownFile]);
function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>): void {
const file = e.target.files?.[0];
if (file && file.name.endsWith('.md')) {
processMarkdownFile(file);
}
}
const validation = {
slug: !form.slug ? 'Slug is required.' : null,
displayName: !form.displayName ? 'Display name is required.' : null,
content: mode === 'upload' && !form.skillContent ? 'Upload a SKILL.md file.' : null,
repo: mode === 'import' && (!form.repoOwner || !form.repoName) ? 'Click Detect to import repo.' : null,
tags: !form.tags ? 'Add at least one tag.' : null,
};
const isImported = mode === 'import' && form.repoOwner && form.repoName;
const errors = Object.values(validation).filter(Boolean);
const isValid = errors.length === 0;
const tagsArray = form.tags.split(',').map(t => t.trim()).filter(Boolean);
function generateIssueUrl(): string {
const skillId = form.repoOwner && form.repoName
? `${form.repoOwner}/${form.repoName}/${form.slug}`
: `community/${form.authorGithub || 'anonymous'}/${form.slug}`;
const jsonEntry = JSON.stringify({
id: skillId,
name: form.displayName,
description: form.description || '',
source: `${form.repoOwner}/${form.repoName}`,
tags: tagsArray,
author: form.authorGithub || form.repoOwner
}, null, 2);
const title = isImported
? encodeURIComponent(`[Import] ${form.repoOwner}/${form.repoName}`)
: encodeURIComponent(`[Skill] ${form.displayName}`);
const bodyContent = isImported
? `## 📦 Import Request: ${form.repoOwner}/${form.repoName}
### Repository
🔗 https://github.com/${form.repoOwner}/${form.repoName}
### Add to \`marketplace/skills.json\`
\`\`\`json
${jsonEntry}
\`\`\`
### Checklist for Maintainer
- [ ] Verify repository is public
- [ ] Add JSON entry to \`marketplace/skills.json\`
---
**Submitted by:** @${form.authorGithub || 'anonymous'}
**Owner:** @${form.repoOwner} (retains all rights)`
: `## 📤 Skill Upload: ${form.displayName}
### Add to \`marketplace/skills.json\`
\`\`\`json
${jsonEntry}
\`\`\`
### SKILL.md Content
<details>
<summary>Click to expand</summary>
\`\`\`markdown
${form.skillContent.slice(0, 4000)}${form.skillContent.length > 4000 ? '\n...(truncated)' : ''}
\`\`\`
</details>
### Checklist for Maintainer
- [ ] Review SKILL.md content
- [ ] Add JSON entry to \`marketplace/skills.json\`
---
**Author:** @${form.authorGithub || 'anonymous'}`;
const body = encodeURIComponent(bodyContent);
const labels = isImported ? 'skill-import' : 'skill-submission';
return `https://github.com/rohitg00/skillkit/issues/new?title=${title}&body=${body}&labels=${labels}`;
}
function handleSubmitClick(e: React.MouseEvent): void {
e.preventDefault();
if (isValid) {
const url = generateIssueUrl();
window.open(url, '_blank', 'noopener,noreferrer');
}
}
return (
<div className="space-y-6">
<div className="flex border-b border-zinc-800">
<button
onClick={() => setMode('import')}
className={`px-6 py-3 font-mono text-sm transition-colors ${
mode === 'import'
? 'text-white border-b-2 border-white -mb-px'
: 'text-zinc-500 hover:text-zinc-300'
}`}
>
Import from GitHub
</button>
<button
onClick={() => setMode('upload')}
className={`px-6 py-3 font-mono text-sm transition-colors ${
mode === 'upload'
? 'text-white border-b-2 border-white -mb-px'
: 'text-zinc-500 hover:text-zinc-300'
}`}
>
Upload File
</button>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div className="space-y-6">
{mode === 'import' && (
<Card>
<div className="flex items-center justify-between mb-1">
<label className="text-sm text-zinc-400">GitHub URL</label>
<span className="text-xs text-zinc-600">Repo, tree path, or blob</span>
</div>
<div className="flex gap-3 mt-2">
<input
type="text"
value={githubUrl}
onChange={(e) => setGithubUrl(e.target.value)}
placeholder="https://github.com/owner/repo"
className="flex-1 bg-zinc-900 border border-zinc-700 text-white px-4 py-2.5 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
/>
<button
onClick={handleDetect}
disabled={isDetecting || !githubUrl}
className={`px-5 py-2.5 font-mono text-sm transition-colors ${
isDetecting || !githubUrl
? 'bg-zinc-800 text-zinc-600 cursor-not-allowed'
: 'bg-white text-black hover:bg-zinc-200'
}`}
>
{isDetecting ? 'Detecting...' : 'Detect'}
</button>
</div>
{detectError && (
<p className="text-red-400 text-xs mt-2 font-mono">{detectError}</p>
)}
{isImported && (
<p className="text-zinc-300 text-xs mt-2 font-mono flex items-center gap-1">
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
Repository detected - {form.repoOwner}/{form.repoName}
</p>
)}
<p className="text-zinc-600 text-xs mt-3">
Public repos only. We link to the original - owner retains all rights.
</p>
</Card>
)}
{mode === 'upload' && (
<Card
className={`transition-colors ${isDragging ? 'border-white bg-zinc-900' : ''}`}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<div className="text-center py-6">
<div className="mb-3">
<svg className="w-8 h-8 mx-auto text-zinc-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
</svg>
</div>
<p className="text-zinc-400 text-sm mb-1">
{fileName ? (
<span className="text-white">{fileName}</span>
) : (
'Drop SKILL.md here'
)}
</p>
<p className="text-zinc-600 text-xs mb-3">or</p>
<label className="inline-block cursor-pointer">
<span className="bg-zinc-800 hover:bg-zinc-700 text-white px-4 py-2 text-sm font-mono transition-colors">
Choose file
</span>
<input
type="file"
accept=".md"
onChange={handleFileSelect}
className="hidden"
/>
</label>
</div>
</Card>
)}
<Card>
<div className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm text-zinc-400 mb-1.5">Slug</label>
<input
type="text"
value={form.slug}
onChange={(e) => updateField('slug', e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
placeholder="my-skill"
className="w-full bg-zinc-900 border border-zinc-700 text-white px-3 py-2 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
/>
</div>
<div>
<label className="block text-sm text-zinc-400 mb-1.5">Display name</label>
<input
type="text"
value={form.displayName}
onChange={(e) => updateField('displayName', e.target.value)}
placeholder="My Skill"
className="w-full bg-zinc-900 border border-zinc-700 text-white px-3 py-2 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm text-zinc-400 mb-1.5">Version</label>
<input
type="text"
value={form.version}
onChange={(e) => updateField('version', e.target.value)}
placeholder="1.0.0"
className="w-full bg-zinc-900 border border-zinc-700 text-white px-3 py-2 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
/>
</div>
<div>
<label className="block text-sm text-zinc-400 mb-1.5">Tags</label>
<input
type="text"
value={form.tags}
onChange={(e) => updateField('tags', e.target.value)}
placeholder="react, typescript"
className="w-full bg-zinc-900 border border-zinc-700 text-white px-3 py-2 font-mono text-sm focus:ring-1 focus:ring-white focus:border-white outline-none placeholder-zinc-600"
/>
</div>
</div>
<div className="flex flex-wrap gap-1.5">
{TAG_SUGGESTIONS.map((tag) => (
<button
key={tag}
type="button"
onClick={() => addTag(tag)}
className="text-xs text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800 px-2 py-0.5 border border-zinc-800 transition-colors"
>
+{tag}
</button>
))}
</div>
</div>
</Card>
</div>
<div className="space-y-6">
<Card>
<h4 className="text-sm text-zinc-400 mb-4">Preview</h4>
<div className="bg-zinc-950 border border-zinc-800 p-4">
<div className="flex items-start justify-between mb-3">
<div>
<h5 className="text-white font-semibold">
{form.displayName || 'Skill Name'}
</h5>
<p className="text-zinc-500 text-sm mt-1">
{form.description || 'No description'}
</p>
</div>
<span className="text-xs font-mono text-zinc-600 bg-zinc-900 px-2 py-1">
v{form.version}
</span>
</div>
{(form.repoOwner || form.authorGithub) && (
<div className="flex items-center gap-2 text-xs text-zinc-600 font-mono mb-3">
{form.repoOwner && form.repoName && <span>{form.repoOwner}/{form.repoName}</span>}
{form.authorGithub && (
<>
{form.repoOwner && <span>•</span>}
<span>@{form.authorGithub}</span>
</>
)}
</div>
)}
{tagsArray.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{tagsArray.map((tag, i) => (
<span key={i} className="text-xs bg-zinc-900 text-zinc-500 px-2 py-0.5 border border-zinc-800">
{tag}
</span>
))}
</div>
)}
</div>
</Card>
{isImported ? (
<Card className="border-blue-900/50">
<div className="flex items-center gap-3 mb-3">
<div className="w-8 h-8 bg-blue-900/30 border border-blue-800 flex items-center justify-center">
<svg className="w-4 h-4 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
</svg>
</div>
<div>
<h4 className="text-sm text-white font-medium">Linked Repository</h4>
<p className="text-xs text-zinc-500">Skills hosted by @{form.repoOwner}</p>
</div>
</div>
<a
href={`https://github.com/${form.repoOwner}/${form.repoName}`}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-blue-400 hover:text-blue-300 font-mono flex items-center gap-2"
>
github.com/{form.repoOwner}/{form.repoName}
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
</a>
</Card>
) : form.skillContent && !form.skillContent.startsWith('[Linked') ? (
<Card>
<h4 className="text-sm text-zinc-400 mb-3">SKILL.md</h4>
<pre className="bg-zinc-950 border border-zinc-800 p-3 text-xs font-mono text-zinc-400 max-h-48 overflow-auto">
{form.skillContent.slice(0, 1000)}
{form.skillContent.length > 1000 && '\n...'}
</pre>
</Card>
) : null}
{errors.length > 0 && (
<div className="space-y-1 text-xs font-mono text-yellow-500">
{errors.map((error, i) => (
<div key={i} className="flex items-center gap-1">
<span className="text-yellow-600">•</span> {error}
</div>
))}
</div>
)}
<button
type="button"
onClick={handleSubmitClick}
disabled={!isValid}
className={`flex items-center justify-center gap-3 w-full py-4 font-mono text-sm transition-all ${
isValid
? 'bg-white text-black hover:bg-zinc-200'
: 'bg-zinc-800 text-zinc-600 cursor-not-allowed'
}`}
>
{GITHUB_ICON}
{isImported ? 'Import to marketplace' : 'Publish skill'}
</button>
<p className="text-xs text-zinc-600 text-center font-mono">
{isImported
? 'Links to original repo → Owner retains rights'
: 'Opens GitHub issue → We review → Added to marketplace'}
</p>
</div>
</div>
</div>
);
}
+56
View File
@@ -0,0 +1,56 @@
import React from 'react';
interface TerminalProps {
title?: string;
children: React.ReactNode;
className?: string;
}
interface CodeBlockProps {
code: string;
language?: string;
}
interface CommandProps {
cmd: string;
comment?: string;
}
export function Terminal({ title = 'bash', children, className = '' }: TerminalProps): React.ReactElement {
return (
<div className={`rounded-lg overflow-hidden border border-zinc-800 bg-[#09090b] shadow-2xl ${className}`}>
<div className="flex items-center justify-between px-4 py-2 border-b border-zinc-800 bg-zinc-900/50">
<div className="flex space-x-2">
<div className="w-3 h-3 rounded-full bg-zinc-700"></div>
<div className="w-3 h-3 rounded-full bg-zinc-700"></div>
<div className="w-3 h-3 rounded-full bg-zinc-700"></div>
</div>
<div className="text-xs text-zinc-500 font-mono">{title}</div>
<div className="w-10"></div>
</div>
<div className="p-4 font-mono text-sm overflow-x-auto">
{children}
</div>
</div>
);
}
export function CodeBlock({ code }: CodeBlockProps): React.ReactElement {
return (
<pre className="text-zinc-300 font-mono text-sm leading-relaxed whitespace-pre-wrap">
{code}
</pre>
);
}
export function Command({ cmd, comment }: CommandProps): React.ReactElement {
return (
<div className="mb-2">
<div className="flex text-zinc-100">
<span className="text-zinc-500 mr-2">$</span>
<span>{cmd}</span>
</div>
{comment && <div className="text-zinc-500 text-xs mt-1 ml-4"># {comment}</div>}
</div>
);
}
+99
View File
@@ -0,0 +1,99 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "SkillKit Marketplace",
"description": "Schema for SkillKit marketplace skills index",
"type": "object",
"required": ["version", "skills"],
"properties": {
"version": {
"type": "integer",
"description": "Schema version number"
},
"updatedAt": {
"type": "string",
"format": "date",
"description": "Last update date (YYYY-MM-DD)"
},
"skills": {
"type": "array",
"description": "List of skills in the marketplace",
"items": {
"$ref": "#/definitions/Skill"
}
}
},
"definitions": {
"Skill": {
"type": "object",
"required": ["id", "name", "source", "tags"],
"properties": {
"id": {
"type": "string",
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_-]+$",
"description": "Unique identifier: owner/repo/skill-name"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100,
"description": "Human-readable skill name"
},
"description": {
"type": "string",
"maxLength": 500,
"description": "Brief description of the skill"
},
"source": {
"type": "string",
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+$",
"description": "GitHub repository: owner/repo"
},
"tags": {
"type": "array",
"items": {
"type": "string",
"pattern": "^[a-z0-9-]+$"
},
"minItems": 1,
"maxItems": 10,
"description": "Tags for categorization (lowercase, hyphenated)"
},
"author": {
"type": "string",
"description": "Skill author name or GitHub username"
},
"version": {
"type": "string",
"pattern": "^\\d+\\.\\d+\\.\\d+$",
"description": "Semantic version (e.g., 1.0.0)"
},
"agents": {
"type": "array",
"items": {
"type": "string",
"enum": [
"claude-code",
"cursor",
"codex",
"gemini-cli",
"opencode",
"antigravity",
"amp",
"clawdbot",
"droid",
"github-copilot",
"goose",
"kilo",
"kiro-cli",
"roo",
"trae",
"windsurf",
"universal"
]
},
"description": "Compatible AI agents (omit for universal compatibility)"
}
}
}
}
}
+58
View File
@@ -0,0 +1,58 @@
// Single source of truth: marketplace/skills.json
import skillsData from '../../../marketplace/skills.json';
export interface IndexedSkill {
id: string;
name: string;
description: string;
source: string;
sourceUrl: string;
rawUrl: string;
tags: string[];
}
function buildSkillIndex(): IndexedSkill[] {
return skillsData.skills.map(skill => {
const sourceParts = skill.source?.split('/') || [];
const owner = sourceParts[0] || 'unknown';
const repo = sourceParts[1] || 'unknown';
const skillSlug = skill.id.split('/').pop() || skill.name.toLowerCase().replace(/\s+/g, '-');
return {
id: skill.id,
name: skill.name,
description: skill.description || '',
source: skill.source || '',
sourceUrl: owner !== 'unknown' ? `https://github.com/${skill.source}` : '',
rawUrl: owner !== 'unknown' && repo !== 'unknown'
? `https://raw.githubusercontent.com/${owner}/${repo}/main/skills/${skillSlug}/SKILL.md`
: '',
tags: skill.tags || [],
};
});
}
export const SKILLS_INDEX: IndexedSkill[] = buildSkillIndex();
export function searchSkills(query: string): IndexedSkill[] {
const q = query.toLowerCase().trim();
if (!q) return [];
return SKILLS_INDEX.filter(skill =>
skill.name.toLowerCase().includes(q) ||
skill.description.toLowerCase().includes(q) ||
skill.tags.some(tag => tag.toLowerCase().includes(q))
).slice(0, 20);
}
export function getSkillsByTag(tag: string): IndexedSkill[] {
return SKILLS_INDEX.filter(skill =>
skill.tags.some(t => t.toLowerCase() === tag.toLowerCase())
);
}
export function getAllTags(): string[] {
const tags = new Set<string>();
SKILLS_INDEX.forEach(skill => skill.tags.forEach(tag => tags.add(tag)));
return Array.from(tags).sort();
}
+118
View File
@@ -0,0 +1,118 @@
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SkillKit - Universal Skills for AI Coding Agents</title>
<meta name="description" content="Portable, reusable skills that work across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more AI coding agents.">
<!-- Open Graph -->
<meta property="og:type" content="website">
<meta property="og:url" content="https://skillkit.dev/">
<meta property="og:title" content="SkillKit - Universal Skills for AI Coding Agents">
<meta property="og:description" content="Portable, reusable skills that work across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more AI coding agents.">
<meta property="og:image" content="/og-image.png">
<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="SkillKit - Universal Skills for AI Coding Agents">
<meta name="twitter:description" content="Portable, reusable skills that work across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more AI coding agents.">
<meta name="twitter:image" content="/og-image.png">
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<script>
tailwind.config = {
darkMode: 'class',
theme: {
screens: {
'xs': '475px',
'sm': '640px',
'md': '768px',
'lg': '1024px',
'xl': '1280px',
'2xl': '1536px',
},
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
mono: ['JetBrains Mono', 'monospace'],
},
colors: {
background: '#000000',
surface: '#09090b',
border: '#27272a',
highlight: '#ffffff',
},
animation: {
'cursor-blink': 'blink 1s step-end infinite',
},
keyframes: {
blink: {
'0%, 100%': { opacity: '1' },
'50%': { opacity: '0' },
}
}
}
}
}
</script>
<style>
body {
background-color: #000000;
color: #e4e4e7;
font-family: 'Inter', sans-serif;
}
h1, h2, h3, h4, h5, h6, .font-mono {
font-family: 'JetBrains Mono', monospace;
}
::selection {
background-color: #ffffff;
color: #000000;
}
::-webkit-scrollbar {
width: 10px;
background: #000000;
}
::-webkit-scrollbar-thumb {
background: #27272a;
border: 1px solid #000000;
}
::-webkit-scrollbar-thumb:hover {
background: #3f3f46;
}
.terminal-scanline {
background: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,0) 50%, rgba(0,0,0,0.1) 50%, rgba(0,0,0,0.1));
background-size: 100% 4px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none;
z-index: 10;
opacity: 0.1;
}
</style>
<script type="importmap">
{
"imports": {
"react/": "https://esm.sh/react@^19.2.3/",
"react": "https://esm.sh/react@^19.2.3",
"@google/genai": "https://esm.sh/@google/genai@^1.38.0",
"react-dom/": "https://esm.sh/react-dom@^19.2.3/"
}
}
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/index.tsx"></script>
</body>
</html>
+15
View File
@@ -0,0 +1,15 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const rootElement = document.getElementById('root');
if (!rootElement) {
throw new Error("Could not find root element to mount to");
}
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
+5
View File
@@ -0,0 +1,5 @@
{
"name": "SkillKit",
"description": "Supercharge Every AI Coding Agent. Translate, manage, and sync skills across Claude, Cursor, Windsurf, and 17+ agents.",
"requestFramePermissions": []
}
+2709
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "skillkit",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^19.2.3",
"@google/genai": "^1.38.0",
"react-dom": "^19.2.3"
},
"devDependencies": {
"@types/node": "^22.14.0",
"@vitejs/plugin-react": "^5.0.0",
"typescript": "~5.8.2",
"vite": "^6.2.0"
}
}
+23
View File
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SkillKit</title>
<script type="text/javascript">
// Single Page Apps for GitHub Pages
// MIT License
// https://github.com/rafgraph/spa-github-pages
var pathSegmentsToKeep = 1;
var l = window.location;
l.replace(
l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
l.pathname.split('/').slice(0, 1 + pathSegmentsToKeep).join('/') + '/?/' +
l.pathname.slice(1).split('/').slice(pathSegmentsToKeep).join('/').replace(/&/g, '~and~') +
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
l.hash
);
</script>
</head>
<body>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 437 B

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<rect width="32" height="32" fill="#000000"/>
<rect x="8" y="8" width="16" height="16" fill="#ffffff"/>
</svg>

After

Width:  |  Height:  |  Size: 176 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.
+124
View File
@@ -0,0 +1,124 @@
import { GoogleGenAI, Type, Schema } from "@google/genai";
import { AgentSkill } from "../types";
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const agentSkillSchema: Schema = {
type: Type.OBJECT,
properties: {
name: { type: Type.STRING, description: "Skill name in slug format (e.g., 'react-best-practices')" },
title: { type: Type.STRING, description: "Human readable title" },
description: { type: Type.STRING, description: "Brief description of what this skill teaches AI agents" },
version: { type: Type.STRING, description: "Semantic version (e.g., '1.0.0')" },
tags: {
type: Type.ARRAY,
items: { type: Type.STRING },
description: "Tags for categorization"
},
applicability: { type: Type.STRING, description: "When the AI agent should apply this skill (e.g., 'Apply when working with React components')" },
principles: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
title: { type: Type.STRING },
description: { type: Type.STRING, description: "Detailed instruction for the AI agent" },
priority: { type: Type.STRING, description: "must, should, or may" }
},
required: ["title", "description", "priority"]
},
description: "Core principles and guidelines (5-8 items)"
},
patterns: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
name: { type: Type.STRING },
description: { type: Type.STRING },
example: { type: Type.STRING, description: "Code example demonstrating the pattern" },
language: { type: Type.STRING, description: "Programming language for syntax highlighting" }
},
required: ["name", "description", "example"]
},
description: "Code patterns with examples (3-5 items)"
},
antiPatterns: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
name: { type: Type.STRING },
description: { type: Type.STRING },
badExample: { type: Type.STRING, description: "Code showing what NOT to do" },
goodExample: { type: Type.STRING, description: "Code showing the correct approach" }
},
required: ["name", "description"]
},
description: "Anti-patterns to avoid (2-4 items)"
},
filePatterns: {
type: Type.ARRAY,
items: { type: Type.STRING },
description: "Glob patterns for files this skill applies to (e.g., '*.tsx', 'src/components/**')"
},
references: {
type: Type.ARRAY,
items: { type: Type.STRING },
description: "Links to official documentation or resources"
}
},
required: ["name", "title", "description", "version", "tags", "applicability", "principles", "patterns", "antiPatterns"]
};
export const generateAgentSkill = async (topic: string): Promise<AgentSkill> => {
const sanitizedTopic = topic?.trim().slice(0, 500) || '';
if (!sanitizedTopic) {
throw new Error("Topic is required");
}
try {
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: `Create a comprehensive AI coding agent skill for: "${sanitizedTopic}"
This skill will be used by AI coding assistants (like Claude Code, Cursor, GitHub Copilot) to provide better code suggestions and follow best practices.
The skill should include:
1. Clear principles that tell the AI WHAT to do and WHEN
2. Code patterns with REAL, WORKING examples (not pseudocode)
3. Anti-patterns showing common mistakes and how to fix them
4. Specific file patterns where this skill applies
Make the instructions actionable and specific. The AI agent should be able to directly apply these guidelines when writing code.
Focus on practical, production-ready patterns used in modern development.`,
config: {
responseMimeType: "application/json",
responseSchema: agentSkillSchema,
systemInstruction: `You are an expert software architect creating AI agent skills.
Your skills are used by AI coding assistants to write better code.
Guidelines:
- Write instructions as commands to the AI (e.g., "Always use...", "Never...", "Prefer...")
- Include REAL code examples, not pseudocode
- Be specific and actionable
- Focus on modern best practices (2024+)
- Include edge cases and error handling patterns
- Make principles enforceable and testable`
}
});
if (!response.text) {
throw new Error("No response from Gemini.");
}
const data = JSON.parse(response.text) as AgentSkill;
return data;
} catch (error) {
console.error("Gemini API Error:", error);
throw error;
}
};
export const generateLearningPath: (topic: string) => Promise<AgentSkill> = generateAgentSkill;
+29
View File
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "ES2022",
"experimentalDecorators": true,
"useDefineForClassFields": false,
"module": "ESNext",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"skipLibCheck": true,
"types": [
"node"
],
"moduleResolution": "bundler",
"isolatedModules": true,
"moduleDetection": "force",
"allowJs": true,
"jsx": "react-jsx",
"paths": {
"@/*": [
"./*"
]
},
"allowImportingTsExtensions": true,
"noEmit": true
}
}
+57
View File
@@ -0,0 +1,57 @@
export interface LearningStep {
title: string;
description: string;
duration: string;
keyConcepts: string[];
}
export interface LearningPath {
skill: string;
description: string;
steps: LearningStep[];
}
export interface GenerateSkillResponse {
learningPath: LearningPath;
}
export enum LoadingState {
IDLE = 'IDLE',
LOADING = 'LOADING',
SUCCESS = 'SUCCESS',
ERROR = 'ERROR'
}
export interface AgentSkill {
name: string;
title: string;
description: string;
version: string;
tags: string[];
applicability: string;
principles: SkillPrinciple[];
patterns: SkillPattern[];
antiPatterns: SkillAntiPattern[];
filePatterns?: string[];
references?: string[];
}
export interface SkillPrinciple {
title: string;
description: string;
priority: 'must' | 'should' | 'may';
}
export interface SkillPattern {
name: string;
description: string;
example: string;
language?: string;
}
export interface SkillAntiPattern {
name: string;
description: string;
badExample?: string;
goodExample?: string;
}
+6
View File
@@ -0,0 +1,6 @@
{
"buildCommand": "npm run build",
"outputDirectory": "dist",
"installCommand": "npm install",
"framework": "vite"
}
+28
View File
@@ -0,0 +1,28 @@
import path from 'path';
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, '.', '');
return {
base: '/',
server: {
port: 3000,
host: '0.0.0.0',
},
plugins: [react()],
define: {
'process.env.API_KEY': JSON.stringify(env.GEMINI_API_KEY),
'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY)
},
resolve: {
alias: {
'@': path.resolve(__dirname, '.'),
}
},
build: {
outDir: 'dist',
emptyOutDir: true,
}
};
});
Binary file not shown.
+271
View File
@@ -0,0 +1,271 @@
/**
* E2E Tests: Onboarding UI
*
* Tests for the new @clack/prompts based CLI onboarding experience
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { join } from 'node:path';
import { mkdirSync, writeFileSync } from 'node:fs';
import {
runCli,
createTestDir,
cleanupTestDir,
createTestSkill,
testFileExists,
} from './helpers/cli-runner.js';
describe('E2E: Onboarding UI', () => {
let testDir: string;
beforeEach(() => {
testDir = createTestDir();
});
afterEach(() => {
cleanupTestDir(testDir);
});
describe('skillkit init --list', () => {
it('should display agents with icons', async () => {
const result = await runCli(['init', '--list']);
const output = result.stdout + result.stderr;
// Should show agent icons
expect(output).toContain('Claude Code');
expect(output).toContain('Cursor');
expect(output).toContain('Codex');
// Should show Skills dir info
expect(output).toContain('Skills dir');
expect(output).toContain('Config');
// Should complete successfully
expect(result.success).toBe(true);
});
it('should display all 17 agents', async () => {
const result = await runCli(['init', '--list']);
const output = result.stdout + result.stderr;
const agents = [
'Claude Code',
'Cursor',
'Codex',
'Gemini',
'OpenCode',
'Copilot',
'Windsurf',
'Droid',
'Goose',
'Amp',
'Kilo',
'Kiro',
'Roo',
'Trae',
'Antigravity',
'Clawdbot',
'Universal',
];
for (const agent of agents) {
expect(output.toLowerCase()).toContain(agent.toLowerCase());
}
});
});
describe('skillkit install --list', () => {
it('should list skills with visual formatting', async () => {
// Create a test repo-like structure
const skillsDir = join(testDir, 'test-skills');
mkdirSync(skillsDir, { recursive: true });
createTestSkill(skillsDir, 'skill-one');
createTestSkill(skillsDir, 'skill-two');
const result = await runCli(['install', testDir, '--list'], { cwd: testDir });
const output = result.stdout + result.stderr;
// Should show skills found
expect(output.toLowerCase()).toMatch(/skill|found|available/);
});
});
describe('skillkit marketplace', () => {
it('should display marketplace header', async () => {
const result = await runCli(['marketplace', '--json']);
const output = result.stdout + result.stderr;
// JSON output should contain marketplace data
if (result.success) {
try {
const data = JSON.parse(result.stdout.trim().split('\n').pop() || '{}');
expect(data).toHaveProperty('totalSkills');
expect(data).toHaveProperty('sources');
} catch {
// Non-JSON output is also acceptable
}
}
});
it('should show popular tags with progress bars', async () => {
const result = await runCli(['marketplace', 'tags', '--json']);
if (result.success && result.stdout.trim().startsWith('[')) {
const tags = JSON.parse(result.stdout);
expect(Array.isArray(tags)).toBe(true);
if (tags.length > 0) {
expect(tags[0]).toHaveProperty('tag');
expect(tags[0]).toHaveProperty('count');
}
}
});
});
describe('skillkit sync', () => {
it('should sync with formatted output', async () => {
// Create skills to sync
const skillsDir = join(testDir, 'skills');
mkdirSync(skillsDir, { recursive: true });
createTestSkill(skillsDir, 'sync-skill-1');
createTestSkill(skillsDir, 'sync-skill-2');
const result = await runCli(['sync', '--agent', 'claude-code', '-y'], { cwd: testDir });
const output = result.stdout + result.stderr;
// Should show sync operation
expect(output.toLowerCase()).toMatch(/sync|skill|claude/);
});
it('should show skill status indicators', async () => {
const skillsDir = join(testDir, 'skills');
mkdirSync(skillsDir, { recursive: true });
createTestSkill(skillsDir, 'enabled-skill');
const result = await runCli(['sync', '--agent', 'claude-code', '-y'], { cwd: testDir });
const output = result.stdout + result.stderr;
// Should complete without error
expect(result.exitCode).toBeDefined();
});
});
describe('skillkit recommend', () => {
it('should show project analysis with spinner', async () => {
// Create a node project
writeFileSync(
join(testDir, 'package.json'),
JSON.stringify({ name: 'test-project', version: '1.0.0' }, null, 2)
);
const result = await runCli(['recommend', '--quiet'], { cwd: testDir });
const output = result.stdout + result.stderr;
// Should show some output about recommendations or project
expect(
output.toLowerCase().includes('project') ||
output.toLowerCase().includes('skill') ||
output.toLowerCase().includes('recommend') ||
output.toLowerCase().includes('index') ||
result.exitCode !== undefined
).toBe(true);
});
it('should format scores with progress bars', async () => {
// Create a TypeScript project
writeFileSync(
join(testDir, 'package.json'),
JSON.stringify({
name: 'test-project',
dependencies: { typescript: '^5.0.0' },
}, null, 2)
);
writeFileSync(join(testDir, 'tsconfig.json'), '{}');
const result = await runCli(['recommend', '--json'], { cwd: testDir });
if (result.success && result.stdout.includes('"recommendations"')) {
const data = JSON.parse(result.stdout);
expect(data).toHaveProperty('recommendations');
}
});
});
describe('Non-interactive mode', () => {
it('should work with --yes flag', async () => {
const skillsDir = join(testDir, 'skills');
mkdirSync(skillsDir, { recursive: true });
createTestSkill(skillsDir, 'test-skill');
const result = await runCli(['sync', '--agent', 'claude-code', '-y'], { cwd: testDir });
// Should complete without prompting
expect(result.exitCode).toBeDefined();
});
it('should work with --quiet flag', async () => {
const result = await runCli(['init', '--list', '-q']);
const output = result.stdout + result.stderr;
// Should still show content but without extra formatting
expect(output).toContain('Claude Code');
});
it('should work with --json flag', async () => {
const result = await runCli(['marketplace', '--json']);
// Should output valid JSON
if (result.success) {
const jsonLine = result.stdout.trim().split('\n').pop() || '';
if (jsonLine.startsWith('{') || jsonLine.startsWith('[')) {
expect(() => JSON.parse(jsonLine)).not.toThrow();
}
}
});
});
describe('Error handling', () => {
it('should show formatted errors', async () => {
const result = await runCli(['install', 'nonexistent-source-12345']);
const output = result.stdout + result.stderr;
// Should show some error message
expect(
output.toLowerCase().includes('error') ||
output.toLowerCase().includes('fail') ||
output.toLowerCase().includes('not found') ||
!result.success
).toBe(true);
});
it('should handle missing skills gracefully', async () => {
const result = await runCli(['read', 'nonexistent-skill'], { cwd: testDir });
// Should not crash
expect(result.exitCode).toBeDefined();
});
});
describe('Visual elements', () => {
it('should use Unicode symbols in output', async () => {
const result = await runCli(['init', '--list']);
const output = result.stdout + result.stderr;
// Should contain Unicode agent icons (any of the defined icons)
const unicodePatterns = [
/[\u2500-\u257F]/, // Box drawing
/[\u25A0-\u25FF]/, // Geometric shapes
/[\u2700-\u27BF]/, // Dingbats
];
const hasUnicode = unicodePatterns.some(pattern => pattern.test(output));
// Unicode support depends on terminal, so just check it doesn't crash
expect(result.exitCode).toBe(0);
});
it('should handle narrow terminal gracefully', async () => {
// Even with narrow output, should not crash
const result = await runCli(['init', '--list'], {
env: { COLUMNS: '40' },
});
expect(result.exitCode).toBeDefined();
});
});
});
+94
View File
@@ -0,0 +1,94 @@
# Contributing Skills to SkillKit Marketplace
## How to Add Your Skill
1. Fork this repository
2. Add your skill to `marketplace/skills.json`
3. Submit a Pull Request
## Skill Format
```json
{
"id": "your-username/your-repo/skill-name",
"name": "Your Skill Name",
"description": "Brief description of what the skill does",
"source": "your-username/your-repo",
"tags": ["tag1", "tag2"]
}
```
## Field Reference
| Field | Required | Description |
|-------|----------|-------------|
| `id` | Yes | Unique identifier: `owner/repo/skill-name` |
| `name` | Yes | Human-readable name (max 100 chars) |
| `description` | No | Brief description (max 500 chars) |
| `source` | Yes | GitHub repository: `owner/repo` |
| `tags` | Yes | 1-10 lowercase tags for categorization |
| `author` | No | Your name or GitHub username |
| `version` | No | Semantic version (e.g., `1.0.0`) |
| `agents` | No | Compatible agents (omit for universal) |
## Skill Repository Structure
Your skill repository should contain a `SKILL.md` file:
```text
your-repo/
├── skills/
│ └── skill-name/
│ └── SKILL.md
└── README.md
```
## SKILL.md Format
```markdown
---
name: "skill-name"
description: "What this skill does"
version: "1.0.0"
tags: ["tag1", "tag2"]
globs: ["**/*.tsx", "**/*.ts"]
---
# Skill Title
Instructions for AI agents...
## Principles
- Principle 1
- Principle 2
## Patterns
### Pattern Name
Description and examples...
```
## Guidelines
- **Be specific**: Skills should focus on one topic
- **Include examples**: Code examples help AI agents understand patterns
- **Test your skill**: Verify it works with at least one agent
- **Keep it updated**: Maintain compatibility with latest agent versions
## Supported Agents
Skills can target specific agents or be universal:
- `claude-code` - Anthropic Claude Code
- `cursor` - Cursor IDE
- `codex` - OpenAI Codex CLI
- `gemini-cli` - Google Gemini CLI
- `windsurf` - Codeium Windsurf
- `github-copilot` - GitHub Copilot
- `universal` - All agents
## Questions?
Open an issue or join our Discord community.
+105
View File
@@ -0,0 +1,105 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "SkillKit Marketplace",
"description": "Schema for SkillKit marketplace skills index",
"type": "object",
"required": ["version", "skills"],
"properties": {
"version": {
"type": "integer",
"description": "Schema version number"
},
"updatedAt": {
"type": "string",
"format": "date",
"description": "Last update date (YYYY-MM-DD)"
},
"skills": {
"type": "array",
"description": "List of skills in the marketplace",
"items": {
"$ref": "#/definitions/Skill"
}
}
},
"definitions": {
"Skill": {
"type": "object",
"required": ["id", "name", "source", "tags"],
"properties": {
"id": {
"type": "string",
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_-]+$",
"description": "Unique identifier: owner/repo/skill-name"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100,
"description": "Human-readable skill name"
},
"description": {
"type": "string",
"maxLength": 500,
"description": "Brief description of the skill"
},
"source": {
"type": "string",
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+$",
"description": "GitHub repository: owner/repo"
},
"tags": {
"type": "array",
"items": {
"type": "string",
"pattern": "^[a-z0-9-]+$"
},
"minItems": 1,
"maxItems": 10,
"description": "Tags for categorization (lowercase, hyphenated)"
},
"author": {
"type": "string",
"description": "Skill author name or GitHub username"
},
"version": {
"type": "string",
"pattern": "^\\d+\\.\\d+\\.\\d+$",
"description": "Semantic version (e.g., 1.0.0)"
},
"agents": {
"type": "array",
"items": {
"type": "string",
"enum": [
"claude-code",
"cursor",
"codex",
"gemini-cli",
"opencode",
"antigravity",
"amp",
"clawdbot",
"droid",
"github-copilot",
"goose",
"kilo",
"kiro-cli",
"roo",
"trae",
"windsurf",
"universal"
]
},
"description": "Compatible AI agents (omit for universal compatibility)"
},
"quality": {
"type": "integer",
"minimum": 0,
"maximum": 100,
"description": "Pre-computed quality score (0-100). Verified sources default to 85."
}
}
}
}
}
+125561
View File
File diff suppressed because it is too large Load Diff
+49
View File
@@ -0,0 +1,49 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "SkillKit Sources",
"description": "Schema for curated skill repository sources",
"type": "object",
"required": ["version", "sources"],
"properties": {
"$schema": {
"type": "string",
"description": "Schema reference"
},
"version": {
"type": "integer",
"description": "Schema version"
},
"updatedAt": {
"type": "string",
"format": "date",
"description": "Last update date"
},
"description": {
"type": "string",
"description": "Description of this file"
},
"sources": {
"type": "array",
"description": "List of curated skill sources",
"items": {
"type": "object",
"required": ["source", "name"],
"properties": {
"source": {
"type": "string",
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+$",
"description": "GitHub owner/repo format"
},
"name": {
"type": "string",
"description": "Display name for the source"
},
"official": {
"type": "boolean",
"description": "Whether this is an official source"
}
}
}
}
}
}
+39
View File
@@ -0,0 +1,39 @@
{
"$schema": "./sources-schema.json",
"version": 1,
"updatedAt": "2026-01-26",
"description": "Curated skill repository sources - THE SINGLE SOURCE OF TRUTH",
"sources": [
{ "source": "anthropics/skills", "name": "Anthropic Official", "official": true },
{ "source": "vercel-labs/agent-skills", "name": "Vercel Labs", "official": true },
{ "source": "expo/skills", "name": "Expo / React Native", "official": true },
{ "source": "remotion-dev/skills", "name": "Remotion Video", "official": true },
{ "source": "supabase/agent-skills", "name": "Supabase", "official": true },
{ "source": "stripe/ai", "name": "Stripe Payments", "official": true },
{ "source": "ComposioHQ/awesome-claude-skills", "name": "Composio Awesome" },
{ "source": "travisvn/awesome-claude-skills", "name": "Travis Awesome" },
{ "source": "mhattingpete/claude-skills-marketplace", "name": "Skills Marketplace" },
{ "source": "coreyhaines31/marketingskills", "name": "Marketing Skills" },
{ "source": "obra/superpowers", "name": "Superpowers TDD" },
{ "source": "softaworks/agent-toolkit", "name": "Softaworks Toolkit" },
{ "source": "wshobson/agents", "name": "Dev Patterns" },
{ "source": "langgenius/dify", "name": "Dify Frontend" },
{ "source": "trailofbits/skills", "name": "Trail of Bits Security" },
{ "source": "better-auth/skills", "name": "Better Auth" },
{ "source": "onmax/nuxt-skills", "name": "Nuxt / Vue" },
{ "source": "hyf0/vue-skills", "name": "Vue Best Practices" },
{ "source": "jezweb/claude-skills", "name": "Cloudflare / TanStack" },
{ "source": "elysiajs/skills", "name": "ElysiaJS / Bun" },
{ "source": "kadajett/agent-nestjs-skills", "name": "NestJS" },
{ "source": "callstackincubator/agent-skills", "name": "React Native" },
{ "source": "cloudai-x/threejs-skills", "name": "Three.js" },
{ "source": "emalorenzo/three-agent-skills", "name": "Three.js Advanced" },
{ "source": "dimillian/skills", "name": "SwiftUI iOS" },
{ "source": "waynesutton/convexskills", "name": "Convex Backend" },
{ "source": "kepano/obsidian-skills", "name": "Obsidian Notes" },
{ "source": "jimliu/baoyu-skills", "name": "Baoyu Tools" },
{ "source": "giuseppe-trisciuoglio/developer-kit", "name": "Shadcn / Radix" },
{ "source": "openrouterteam/agent-skills", "name": "OpenRouter SDK" },
{ "source": "intellectronica/agent-skills", "name": "Context7" }
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "skillkit-monorepo",
"version": "1.6.4",
"version": "1.7.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "skillkit-monorepo",
"version": "1.6.4",
"version": "1.7.2",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^22.10.5",
+4 -2
View File
@@ -1,12 +1,13 @@
{
"name": "skillkit-monorepo",
"version": "1.6.4",
"version": "1.7.2",
"private": true,
"description": "Universal skills loader for AI coding agents - Monorepo",
"type": "module",
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev",
"ui": "pnpm --filter skillkit exec bun skillkit ui",
"test": "turbo run test",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
@@ -53,5 +54,6 @@
"turbo": "^2.3.4",
"typescript": "^5.7.2",
"vitest": "^2.1.8"
}
},
"pnpm": {}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/agents",
"version": "1.6.4",
"version": "1.7.6",
"description": "Agent adapters for SkillKit - supports 17+ AI coding agents",
"type": "module",
"main": "./dist/index.js",
+3 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/cli",
"version": "1.6.4",
"version": "1.7.6",
"description": "CLI commands for SkillKit",
"type": "module",
"main": "./dist/index.js",
@@ -21,6 +21,7 @@
"test": "vitest run"
},
"dependencies": {
"@clack/prompts": "^0.11.0",
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"@skillkit/tui": "workspace:*",
@@ -29,6 +30,7 @@
"got": "^14.4.1",
"isomorphic-git": "^1.27.1",
"ora": "^8.1.0",
"picocolors": "^1.1.1",
"yaml": "^2.7.0"
},
"devDependencies": {
@@ -0,0 +1,326 @@
/**
* Unit Tests: Onboarding Module
*
* Tests for the CLI onboarding experience components
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { existsSync, mkdirSync, rmSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { mkdtempSync } from 'node:fs';
describe('Onboarding Module', () => {
describe('theme', () => {
it('should export agent icons', async () => {
const { AGENT_ICONS, AGENT_NAMES } = await import('../onboarding/theme.js');
expect(AGENT_ICONS).toBeDefined();
expect(AGENT_ICONS['claude-code']).toBe('\u27c1'); // ⟁
expect(AGENT_ICONS['cursor']).toBe('\u25eb'); // ◫
expect(AGENT_ICONS['codex']).toBe('\u25ce'); // ◎
expect(AGENT_NAMES).toBeDefined();
expect(AGENT_NAMES['claude-code']).toBe('Claude Code');
expect(AGENT_NAMES['cursor']).toBe('Cursor');
});
it('should export symbols', async () => {
const { symbols } = await import('../onboarding/theme.js');
expect(symbols).toBeDefined();
expect(symbols.stepPending).toBe('\u25cb'); // ○
expect(symbols.stepActive).toBe('\u25cf'); // ●
expect(symbols.success).toBe('\u2713'); // ✓
expect(symbols.error).toBe('\u2717'); // ✗
});
it('should export color utilities', async () => {
const { colors } = await import('../onboarding/theme.js');
expect(colors).toBeDefined();
expect(typeof colors.accent).toBe('function');
expect(typeof colors.primary).toBe('function');
expect(typeof colors.success).toBe('function');
expect(typeof colors.error).toBe('function');
});
it('should format agent with icon', async () => {
const { formatAgent, getAgentIcon } = await import('../onboarding/theme.js');
const formatted = formatAgent('claude-code');
expect(formatted).toContain('\u27c1'); // ⟁
expect(formatted).toContain('Claude Code');
const icon = getAgentIcon('cursor');
expect(icon).toBe('\u25eb'); // ◫
});
it('should generate progress bars', async () => {
const { progressBar } = await import('../onboarding/theme.js');
const bar50 = progressBar(50, 100, 10);
expect(bar50).toContain('\u2588'); // █ (filled)
expect(bar50).toContain('\u2591'); // ░ (empty)
expect(bar50.length).toBe(10);
const bar100 = progressBar(100, 100, 6);
expect(bar100).toBe('\u2588'.repeat(6));
const bar0 = progressBar(0, 100, 6);
expect(bar0).toBe('\u2591'.repeat(6));
});
it('should format score with visual bar', async () => {
const { formatScore } = await import('../onboarding/theme.js');
const score = formatScore(75);
expect(score).toContain('75%');
expect(score).toContain('\u2588'); // progress bar
});
});
describe('logo', () => {
it('should export logo functions', async () => {
const { getLogo, getFullLogo, getCompactLogo, getMinimalLogo, getHeader, getDivider } =
await import('../onboarding/logo.js');
expect(typeof getLogo).toBe('function');
expect(typeof getFullLogo).toBe('function');
expect(typeof getCompactLogo).toBe('function');
expect(typeof getMinimalLogo).toBe('function');
expect(typeof getHeader).toBe('function');
expect(typeof getDivider).toBe('function');
});
it('should generate full logo with version', async () => {
const { getFullLogo } = await import('../onboarding/logo.js');
const logo = getFullLogo('1.7.2', 17);
// Full logo uses block characters (███), not literal text
expect(logo).toContain('\u2588'); // █ block character
expect(logo).toContain('v1.7.2');
expect(logo).toContain('17 agents');
});
it('should generate compact logo', async () => {
const { getCompactLogo } = await import('../onboarding/logo.js');
const logo = getCompactLogo('1.7.2');
// Compact logo has spaced letters: S K I L L K I T
expect(logo).toContain('S K I L L K I T');
expect(logo).toContain('v1.7.2');
});
it('should generate minimal logo', async () => {
const { getMinimalLogo } = await import('../onboarding/logo.js');
const logo = getMinimalLogo('1.7.2');
expect(logo).toContain('SKILLKIT');
expect(logo).toContain('\u25c7'); // ◇ diamond
});
it('should generate header', async () => {
const { getHeader } = await import('../onboarding/logo.js');
const header = getHeader('Test Title');
expect(header).toContain('SkillKit');
expect(header).toContain('Test Title');
});
it('should generate divider', async () => {
const { getDivider } = await import('../onboarding/logo.js');
const divider = getDivider(20);
expect(divider).toContain('\u2500'); // ─
});
});
describe('preferences', () => {
let testDir: string;
let originalHome: string | undefined;
let originalUserProfile: string | undefined;
beforeEach(() => {
vi.resetModules();
testDir = mkdtempSync(join(tmpdir(), 'skillkit-prefs-test-'));
originalHome = process.env.HOME;
originalUserProfile = process.env.USERPROFILE;
process.env.HOME = testDir;
process.env.USERPROFILE = testDir;
});
afterEach(() => {
if (existsSync(testDir)) {
rmSync(testDir, { recursive: true, force: true });
}
if (originalHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = originalHome;
}
if (originalUserProfile === undefined) {
delete process.env.USERPROFILE;
} else {
process.env.USERPROFILE = originalUserProfile;
}
vi.resetModules();
});
it('should export preference functions', async () => {
const {
loadPreferences,
savePreferences,
isOnboardingComplete,
completeOnboarding,
saveLastAgents,
getLastAgents,
saveInstallMethod,
getInstallMethod,
} = await import('../onboarding/preferences.js');
expect(typeof loadPreferences).toBe('function');
expect(typeof savePreferences).toBe('function');
expect(typeof isOnboardingComplete).toBe('function');
expect(typeof completeOnboarding).toBe('function');
expect(typeof saveLastAgents).toBe('function');
expect(typeof getLastAgents).toBe('function');
expect(typeof saveInstallMethod).toBe('function');
expect(typeof getInstallMethod).toBe('function');
});
it('should return default preferences when file does not exist', async () => {
const { loadPreferences } = await import('../onboarding/preferences.js');
const prefs = loadPreferences();
expect(prefs).toBeDefined();
expect(prefs.onboardingComplete).toBe(false);
expect(prefs.lastSelectedAgents).toEqual([]);
expect(prefs.defaultInstallMethod).toBe('symlink');
});
});
describe('summary', () => {
it('should export summary functions', async () => {
const {
showInstallSummary,
showNextSteps,
showAgentSummary,
showProjectSummary,
showSyncSummary,
showSkillList,
showMarketplaceInfo,
} = await import('../onboarding/summary.js');
expect(typeof showInstallSummary).toBe('function');
expect(typeof showNextSteps).toBe('function');
expect(typeof showAgentSummary).toBe('function');
expect(typeof showProjectSummary).toBe('function');
expect(typeof showSyncSummary).toBe('function');
expect(typeof showSkillList).toBe('function');
expect(typeof showMarketplaceInfo).toBe('function');
});
});
describe('prompts', () => {
it('should export prompt functions', async () => {
const {
isCancel,
intro,
outro,
cancel,
note,
log,
step,
success,
warn,
error,
spinner,
text,
password,
confirm,
select,
agentMultiselect,
skillMultiselect,
stepTrail,
selectInstallMethod,
} = await import('../onboarding/prompts.js');
expect(typeof isCancel).toBe('function');
expect(typeof intro).toBe('function');
expect(typeof outro).toBe('function');
expect(typeof cancel).toBe('function');
expect(typeof note).toBe('function');
expect(typeof log).toBe('function');
expect(typeof step).toBe('function');
expect(typeof success).toBe('function');
expect(typeof warn).toBe('function');
expect(typeof error).toBe('function');
expect(typeof spinner).toBe('function');
expect(typeof text).toBe('function');
expect(typeof password).toBe('function');
expect(typeof confirm).toBe('function');
expect(typeof select).toBe('function');
expect(typeof agentMultiselect).toBe('function');
expect(typeof skillMultiselect).toBe('function');
expect(typeof stepTrail).toBe('function');
expect(typeof selectInstallMethod).toBe('function');
});
it('should generate step trail', async () => {
const { stepTrail } = await import('../onboarding/prompts.js');
const trail = stepTrail([
{ label: 'Step 1', status: 'complete' },
{ label: 'Step 2', status: 'active' },
{ label: 'Step 3', status: 'pending' },
]);
expect(trail).toContain('Step 1');
expect(trail).toContain('Step 2');
expect(trail).toContain('Step 3');
expect(trail).toContain('\u25cf'); // ● (filled circle)
expect(trail).toContain('\u25cb'); // ○ (empty circle)
});
});
describe('index exports', () => {
it('should re-export all modules', async () => {
const onboarding = await import('../onboarding/index.js');
// Theme exports
expect(onboarding.AGENT_ICONS).toBeDefined();
expect(onboarding.AGENT_NAMES).toBeDefined();
expect(onboarding.symbols).toBeDefined();
expect(onboarding.colors).toBeDefined();
expect(onboarding.formatAgent).toBeDefined();
expect(onboarding.getAgentIcon).toBeDefined();
expect(onboarding.progressBar).toBeDefined();
expect(onboarding.formatScore).toBeDefined();
// Logo exports
expect(onboarding.getLogo).toBeDefined();
expect(onboarding.getHeader).toBeDefined();
expect(onboarding.getDivider).toBeDefined();
// Prompts exports
expect(onboarding.isCancel).toBeDefined();
expect(onboarding.spinner).toBeDefined();
expect(onboarding.agentMultiselect).toBeDefined();
expect(onboarding.skillMultiselect).toBeDefined();
// Summary exports
expect(onboarding.showInstallSummary).toBeDefined();
expect(onboarding.showNextSteps).toBeDefined();
// Preferences exports
expect(onboarding.loadPreferences).toBeDefined();
expect(onboarding.savePreferences).toBeDefined();
// Main functions
expect(onboarding.welcome).toBeDefined();
expect(onboarding.header).toBeDefined();
expect(onboarding.showCompletion).toBeDefined();
});
});
});
+211
View File
@@ -0,0 +1,211 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { Command, Option } from 'clipanion';
import { findAllSkills, findSkill, detectProvider, isLocalPath } from '@skillkit/core';
import { getSearchDirs, loadSkillMetadata } from '../helpers.js';
import {
colors,
symbols,
spinner,
step,
success,
warn,
header,
} from '../onboarding/index.js';
interface UpdateInfo {
name: string;
currentVersion?: string;
hasUpdate: boolean;
error?: string;
}
export class CheckCommand extends Command {
static override paths = [['check']];
static override usage = Command.Usage({
description: 'Check for available skill updates (dry-run)',
details: `
Checks if installed skills have updates available from their sources.
Does not modify any files - just reports what would be updated.
`,
examples: [
['Check all skills for updates', '$0 check'],
['Check specific skills', '$0 check pdf xlsx'],
['Show detailed output', '$0 check --verbose'],
],
});
skills = Option.Rest();
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed information',
});
quiet = Option.Boolean('--quiet,-q', false, {
description: 'Minimal output',
});
async execute(): Promise<number> {
const searchDirs = getSearchDirs();
const s = spinner();
if (!this.quiet) {
header('Check Updates');
}
let skillsToCheck;
if (this.skills.length > 0) {
const foundSkills = this.skills.map(name => ({
name,
skill: findSkill(name, searchDirs),
}));
skillsToCheck = foundSkills
.filter((s): s is { name: string; skill: NonNullable<typeof s.skill> } => s.skill !== null)
.map(s => s.skill);
const notFound = foundSkills.filter(s => s.skill === null).map(s => s.name);
if (notFound.length > 0) {
warn(`Skills not found: ${notFound.join(', ')}`);
}
} else {
skillsToCheck = findAllSkills(searchDirs);
}
if (skillsToCheck.length === 0) {
warn('No skills to check');
return 0;
}
if (!this.quiet) {
step(`Checking ${skillsToCheck.length} skill(s) for updates...`);
console.log('');
}
const results: UpdateInfo[] = [];
let updatesAvailable = 0;
for (const skill of skillsToCheck) {
const metadata = loadSkillMetadata(skill.path);
if (!metadata) {
results.push({
name: skill.name,
hasUpdate: false,
error: 'No metadata (reinstall needed)',
});
continue;
}
if (this.verbose) {
s.start(`Checking ${skill.name}...`);
}
try {
if (isLocalPath(metadata.source)) {
const localPath = metadata.subpath
? join(metadata.source, metadata.subpath)
: metadata.source;
if (!existsSync(localPath)) {
results.push({
name: skill.name,
hasUpdate: false,
error: 'Local source missing',
});
if (this.verbose) s.stop(`${skill.name}: source missing`);
continue;
}
const sourceSkillMd = join(localPath, 'SKILL.md');
const installedSkillMd = join(skill.path, 'SKILL.md');
if (existsSync(sourceSkillMd) && existsSync(installedSkillMd)) {
const { statSync } = await import('node:fs');
const sourceTime = statSync(sourceSkillMd).mtime;
const installedTime = statSync(installedSkillMd).mtime;
if (sourceTime > installedTime) {
results.push({ name: skill.name, hasUpdate: true });
updatesAvailable++;
if (this.verbose) s.stop(`${skill.name}: update available`);
} else {
results.push({ name: skill.name, hasUpdate: false });
if (this.verbose) s.stop(`${skill.name}: up to date`);
}
} else {
results.push({ name: skill.name, hasUpdate: false });
if (this.verbose) s.stop(`${skill.name}: up to date`);
}
} else {
const provider = detectProvider(metadata.source);
if (!provider) {
results.push({
name: skill.name,
hasUpdate: false,
error: 'Unknown provider',
});
if (this.verbose) s.stop(`${skill.name}: unknown provider`);
continue;
}
results.push({
name: skill.name,
hasUpdate: false,
currentVersion: metadata.updatedAt || metadata.installedAt,
});
if (this.verbose) s.stop(`${skill.name}: remote source (run update to sync)`);
}
} catch (err) {
results.push({
name: skill.name,
hasUpdate: false,
error: err instanceof Error ? err.message : 'Check failed',
});
if (this.verbose) s.stop(`${skill.name}: error`);
}
}
console.log('');
const withUpdates = results.filter(r => r.hasUpdate);
const upToDate = results.filter(r => !r.hasUpdate && !r.error);
const withErrors = results.filter(r => r.error);
if (withUpdates.length > 0) {
console.log(colors.primary('Updates available:'));
for (const r of withUpdates) {
console.log(` ${colors.success(symbols.arrowUp)} ${colors.primary(r.name)}`);
}
console.log('');
}
if (upToDate.length > 0 && this.verbose) {
console.log(colors.muted('Up to date:'));
for (const r of upToDate) {
console.log(` ${colors.muted(symbols.success)} ${colors.muted(r.name)}`);
}
console.log('');
}
if (withErrors.length > 0) {
console.log(colors.warning('Could not check:'));
for (const r of withErrors) {
console.log(` ${colors.warning(symbols.warning)} ${r.name}: ${colors.muted(r.error || 'unknown')}`);
}
console.log('');
}
if (updatesAvailable > 0) {
success(`${updatesAvailable} update(s) available`);
console.log(colors.muted('Run `skillkit update` to install updates'));
} else {
success('All skills are up to date');
}
return 0;
}
}
+181
View File
@@ -0,0 +1,181 @@
import { Command, Option } from 'clipanion';
import {
colors,
symbols,
spinner,
step,
isCancel,
select,
header,
} from '../onboarding/index.js';
interface SkillResult {
name: string;
description?: string;
source: string;
repoName: string;
}
import skillsData from '../../../../marketplace/skills.json' with { type: 'json' };
import sourcesData from '../../../../marketplace/sources.json' with { type: 'json' };
export class FindCommand extends Command {
static override paths = [['find'], ['search']];
static override usage = Command.Usage({
description: 'Search for skills in the marketplace',
details: `
Quickly find and install skills from the marketplace.
Interactive mode lets you browse and install in one step.
`,
examples: [
['Interactive search', '$0 find'],
['Search for specific skill', '$0 find pdf'],
['Search with keyword', '$0 find "nextjs"'],
['List top skills', '$0 find --top'],
],
});
query = Option.String({ required: false });
top = Option.Boolean('--top,-t', false, {
description: 'Show top/featured skills',
});
limit = Option.String('--limit,-l', '10', {
description: 'Maximum results to show',
});
install = Option.Boolean('--install,-i', false, {
description: 'Prompt to install after finding',
});
quiet = Option.Boolean('--quiet,-q', false, {
description: 'Minimal output (just list skills)',
});
async execute(): Promise<number> {
const s = spinner();
const limit = parseInt(this.limit, 10) || 10;
if (!this.quiet) {
header('Find Skills');
}
const allSkills: SkillResult[] = (skillsData.skills || []).map((skill: { name: string; description?: string; source?: string; repo?: string }) => ({
name: skill.name,
description: skill.description,
source: skill.source || '',
repoName: skill.repo || skill.source?.split('/').pop() || '',
}));
let results: SkillResult[];
if (this.top) {
const featured = sourcesData.sources
.filter((s: { official?: boolean }) => s.official)
.slice(0, 5);
results = allSkills
.filter(skill => featured.some((f: { source: string }) => skill.source.includes(f.source)))
.slice(0, limit);
if (!this.quiet) {
step('Showing featured skills');
}
} else if (this.query) {
const query = this.query.toLowerCase();
s.start('Searching...');
results = allSkills.filter(skill =>
skill.name.toLowerCase().includes(query) ||
skill.description?.toLowerCase().includes(query) ||
skill.source.toLowerCase().includes(query) ||
skill.repoName.toLowerCase().includes(query)
).slice(0, limit);
s.stop(`Found ${results.length} skill(s)`);
} else {
if (!this.quiet) {
step('Enter a search term or browse featured skills');
}
const { text } = await import('../onboarding/prompts.js');
const searchResult = await text({
message: 'Search skills',
placeholder: 'e.g., pdf, nextjs, testing',
});
if (isCancel(searchResult)) {
return 0;
}
const query = (searchResult as string).toLowerCase();
if (query) {
s.start('Searching...');
results = allSkills.filter(skill =>
skill.name.toLowerCase().includes(query) ||
skill.description?.toLowerCase().includes(query) ||
skill.source.toLowerCase().includes(query) ||
skill.repoName.toLowerCase().includes(query)
).slice(0, limit);
s.stop(`Found ${results.length} skill(s)`);
} else {
results = allSkills.slice(0, limit);
}
}
if (results.length === 0) {
console.log(colors.muted('No skills found matching your search'));
console.log('');
console.log(colors.muted('Try:'));
console.log(colors.muted(' skillkit find --top # Show featured skills'));
console.log(colors.muted(' skillkit ui # Browse in TUI'));
return 0;
}
console.log('');
for (const skill of results) {
const desc = skill.description
? colors.muted(` - ${skill.description.slice(0, 50)}${skill.description.length > 50 ? '...' : ''}`)
: '';
console.log(` ${colors.success(symbols.bullet)} ${colors.primary(skill.name)}${desc}`);
if (!this.quiet && skill.source) {
console.log(` ${colors.muted(skill.source)}`);
}
}
console.log('');
console.log(colors.muted(`Showing ${results.length} of ${allSkills.length} skills`));
console.log('');
if (this.install || (!this.query && !this.top && process.stdin.isTTY)) {
const installResult = await select({
message: 'Install a skill?',
options: [
{ value: 'none', label: 'No, just browsing' },
...results.slice(0, 5).map(skill => ({
value: skill.source,
label: skill.name,
hint: skill.repoName,
})),
],
initialValue: 'none',
});
if (!isCancel(installResult) && installResult !== 'none') {
console.log('');
console.log(colors.cyan('To install, run:'));
console.log(` ${colors.bold(`skillkit install ${installResult}`)}`);
}
} else {
console.log(colors.muted('To install: skillkit install <source>'));
}
return 0;
}
}
+384
View File
@@ -0,0 +1,384 @@
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join, resolve, basename } from 'node:path';
import { Command, Option } from 'clipanion';
import {
evaluateSkillFile,
findAllSkills,
type QualityScore,
} from '@skillkit/core';
import { getSearchDirs } from '../helpers.js';
import {
colors,
symbols,
success,
warn,
error,
header,
confirm,
} from '../onboarding/index.js';
interface FixSuggestion {
type: 'add' | 'replace' | 'format';
description: string;
original?: string;
replacement: string;
line?: number;
automatic: boolean;
}
const FRONTMATTER_TEMPLATE = `---
name: {{NAME}}
description: {{DESCRIPTION}}
globs:
- "**/*"
---
`;
const WHEN_TO_USE_TEMPLATE = `
## When to Use
Use this skill when:
- [Add specific trigger conditions]
- [Add relevant patterns to detect]
`;
const BOUNDARIES_TEMPLATE = `
## Boundaries
This skill should NOT:
- [Add constraints and limitations]
- [Specify what the agent should never do]
`;
const VAGUE_TERM_REPLACEMENTS: Record<string, string> = {
'be helpful': 'follow the specific instructions below',
'assist the user': 'complete the requested task',
'help with': 'handle',
'try to': '',
'attempt to': '',
'do your best': 'follow these guidelines',
'as needed': 'when the following conditions are met',
'when appropriate': 'when',
'if necessary': 'when required',
'general purpose': 'designed for',
'various tasks': 'the following tasks',
'many things': 'the following',
'etc.': '',
'and so on': '',
'stuff like that': '',
};
function generateFixes(content: string, quality: QualityScore, skillName: string): FixSuggestion[] {
const fixes: FixSuggestion[] = [];
if (!quality.structure.hasMetadata) {
const template = FRONTMATTER_TEMPLATE
.replace('{{NAME}}', skillName)
.replace('{{DESCRIPTION}}', 'Add a description for this skill');
fixes.push({
type: 'add',
description: 'Add YAML frontmatter template',
replacement: template,
automatic: true,
});
}
if (!quality.structure.hasTriggers && !quality.structure.hasWhenToUse) {
fixes.push({
type: 'add',
description: 'Add "When to Use" section scaffold',
replacement: WHEN_TO_USE_TEMPLATE,
automatic: true,
});
}
if (!quality.structure.hasBoundaries) {
fixes.push({
type: 'add',
description: 'Add "Boundaries" section scaffold',
replacement: BOUNDARIES_TEMPLATE,
automatic: true,
});
}
for (const [vague, replacement] of Object.entries(VAGUE_TERM_REPLACEMENTS)) {
const escaped = vague.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(escaped, 'gi');
if (regex.test(content)) {
fixes.push({
type: 'replace',
description: `Replace vague term "${vague}"`,
original: vague,
replacement: replacement || '[be specific]',
automatic: false,
});
}
}
const codeBlockPattern = /```(\s*\n[\s\S]*?```)/g;
let match;
while ((match = codeBlockPattern.exec(content)) !== null) {
if (match[1].startsWith('\n') && !content.slice(match.index, match.index + 10).match(/```\w/)) {
fixes.push({
type: 'format',
description: 'Add language tag to code block',
original: '```',
replacement: '```typescript',
automatic: false,
});
break;
}
}
return fixes;
}
function applyFixes(content: string, fixes: FixSuggestion[]): string {
let result = content;
const hasFrontmatter = /^---\s*\n/.test(content);
for (const fix of fixes) {
if (fix.type === 'add') {
if (fix.description.includes('frontmatter') && !hasFrontmatter) {
result = fix.replacement + result;
} else if (fix.description.includes('When to Use') || fix.description.includes('Boundaries')) {
result = result.trimEnd() + '\n' + fix.replacement;
}
} else if (fix.type === 'replace' && fix.original && fix.automatic) {
const escaped = fix.original.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(escaped, 'gi');
result = result.replace(regex, fix.replacement);
}
}
return result;
}
export class FixCommand extends Command {
static override paths = [['fix']];
static override usage = Command.Usage({
description: 'Automatically fix common skill quality issues',
details: `
The fix command analyzes skills and applies automatic fixes for common quality issues.
Fixes that can be automated:
- Add missing YAML frontmatter template
- Add "When to Use" section scaffold
- Add "Boundaries" section scaffold
- Format code blocks with language tags
Interactive mode prompts before each fix.
`,
examples: [
['Fix a specific skill', '$0 fix my-skill'],
['Fix skill file', '$0 fix ./path/to/SKILL.md'],
['Preview fixes without applying', '$0 fix my-skill --dry-run'],
['Apply all fixes without prompts', '$0 fix my-skill --yes'],
],
});
targets = Option.Rest();
dryRun = Option.Boolean('--dry-run,-d', false, {
description: 'Show proposed changes without applying',
});
yes = Option.Boolean('--yes,-y', false, {
description: 'Apply all automatic fixes without prompting',
});
interactive = Option.Boolean('--interactive,-i', {
description: 'Prompt for each fix (default when not using --yes)',
});
async execute(): Promise<number> {
const isInteractive = this.interactive !== false && !this.yes && !this.dryRun && process.stdin.isTTY;
if (this.targets.length === 0) {
error('Please specify a skill to fix');
console.log(colors.muted('Usage: skillkit fix <skill-name> or skillkit fix ./path/to/SKILL.md'));
return 1;
}
header('Skill Quality Fixer');
let totalFixes = 0;
let filesFixed = 0;
for (const target of this.targets) {
const resolved = resolve(target);
let filePath: string | null = null;
let skillName = basename(target);
if (existsSync(resolved)) {
if (resolved.endsWith('.md') || resolved.endsWith('.mdc')) {
filePath = resolved;
const fileName = basename(resolved);
if (fileName.endsWith('.mdc')) {
skillName = fileName.slice(0, -4);
} else if (fileName.endsWith('.md')) {
skillName = fileName.slice(0, -3);
} else {
skillName = fileName;
}
} else {
const skillMd = join(resolved, 'SKILL.md');
const indexMdc = join(resolved, 'index.mdc');
if (existsSync(skillMd)) {
filePath = skillMd;
} else if (existsSync(indexMdc)) {
filePath = indexMdc;
}
}
} else {
const searchDirs = getSearchDirs();
const skills = findAllSkills(searchDirs);
const found = skills.find(s => s.name === target);
if (found) {
const skillMd = join(found.path, 'SKILL.md');
const indexMdc = join(found.path, 'index.mdc');
if (existsSync(skillMd)) {
filePath = skillMd;
} else if (existsSync(indexMdc)) {
filePath = indexMdc;
}
skillName = found.name;
}
}
if (!filePath || !existsSync(filePath)) {
warn(`Skill not found: ${target}`);
continue;
}
const content = readFileSync(filePath, 'utf-8');
const quality = evaluateSkillFile(filePath);
if (!quality) {
warn(`Could not evaluate: ${target}`);
continue;
}
console.log('');
console.log(colors.bold(skillName));
console.log(colors.muted(`Score: ${quality.overall}/100`));
const fixes = generateFixes(content, quality, skillName);
const automaticFixes = fixes.filter(f => f.automatic);
const manualFixes = fixes.filter(f => !f.automatic);
if (fixes.length === 0) {
console.log(colors.success(`${symbols.success} No automatic fixes needed`));
continue;
}
console.log('');
console.log(colors.muted(`Found ${fixes.length} potential fix(es):`));
for (const fix of automaticFixes) {
console.log(` ${colors.success(symbols.success)} ${fix.description} ${colors.muted('(automatic)')}`);
}
for (const fix of manualFixes) {
console.log(` ${colors.warning(symbols.warning)} ${fix.description} ${colors.muted('(manual review)')}`);
}
if (this.dryRun) {
console.log('');
console.log(colors.muted('Dry run - no changes applied'));
if (automaticFixes.length > 0) {
console.log('');
console.log(colors.muted('Preview of automatic fixes:'));
const preview = applyFixes(content, automaticFixes);
const diff = generateDiff(content, preview);
console.log(diff);
}
continue;
}
if (automaticFixes.length > 0) {
let shouldApply = this.yes;
if (isInteractive && !this.yes) {
console.log('');
const confirmResult = await confirm({
message: `Apply ${automaticFixes.length} automatic fix(es)?`,
initialValue: true,
});
shouldApply = confirmResult === true;
}
if (shouldApply) {
const fixed = applyFixes(content, automaticFixes);
writeFileSync(filePath, fixed, 'utf-8');
totalFixes += automaticFixes.length;
filesFixed++;
console.log(colors.success(`${symbols.success} Applied ${automaticFixes.length} fix(es)`));
} else {
console.log(colors.muted('Skipped'));
}
}
if (manualFixes.length > 0) {
console.log('');
console.log(colors.muted('Manual fixes required:'));
for (const fix of manualFixes) {
if (fix.original) {
console.log(` ${colors.warning(symbols.bullet)} Replace "${fix.original}" with "${fix.replacement}"`);
} else {
console.log(` ${colors.warning(symbols.bullet)} ${fix.description}`);
}
}
}
}
console.log('');
if (totalFixes > 0) {
success(`Fixed ${totalFixes} issue(s) in ${filesFixed} file(s)`);
console.log(colors.muted('Run "skillkit validate" to verify improvements'));
} else if (!this.dryRun) {
console.log(colors.muted('No fixes applied'));
}
return 0;
}
}
function generateDiff(original: string, modified: string): string {
const originalLines = original.split('\n');
const modifiedLines = modified.split('\n');
const originalSet = new Set(originalLines);
const modifiedSet = new Set(modifiedLines);
const added = modifiedLines.filter(line => !originalSet.has(line));
const removed = originalLines.filter(line => !modifiedSet.has(line));
const diff: string[] = [];
for (const line of removed.slice(0, 5)) {
diff.push(colors.error(`- ${line}`));
}
if (removed.length > 5) {
diff.push(colors.muted(` ... and ${removed.length - 5} more removed`));
}
for (const line of added.slice(0, 10)) {
diff.push(colors.success(`+ ${line}`));
}
if (added.length > 10) {
diff.push(colors.muted(` ... and ${added.length - 10} more added`));
}
if (diff.length === 0) {
diff.push(colors.muted(' (no visible changes)'));
}
return diff.join('\n');
}
+13
View File
@@ -8,6 +8,7 @@ export { RemoveCommand } from './remove.js';
export { InstallCommand } from './install.js';
export { UpdateCommand } from './update.js';
export { ValidateCommand } from './validate.js';
export { FixCommand } from './fix.js';
export { CreateCommand } from './create.js';
export { UICommand } from './ui.js';
export { TranslateCommand } from './translate.js';
@@ -31,6 +32,7 @@ export { PlanCommand } from './plan.js';
export { CommandCmd } from './command.js';
export { AICommand } from './ai.js';
export { AuditCommand } from './audit.js';
export { PublishCommand } from './publish.js';
export {
AgentCommand,
AgentListCommand,
@@ -40,3 +42,14 @@ export {
AgentSyncCommand,
AgentValidateCommand,
} from './agent.js';
export { CheckCommand } from './check.js';
export { FindCommand } from './find.js';
export {
ManifestCommand,
ManifestInitCommand,
ManifestAddCommand,
ManifestRemoveCommand,
ManifestInstallCommand,
ManifestGenerateCommand,
} from './manifest.js';
+135 -25
View File
@@ -1,8 +1,27 @@
import chalk from 'chalk';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { Command, Option } from 'clipanion';
import type { AgentType } from '@skillkit/core';
import { detectAgent, getAdapter, getAllAdapters } from '@skillkit/agents';
import { initProject } from '../helpers.js';
import {
welcome,
header,
colors,
symbols,
formatAgent,
isCancel,
spinner,
select,
confirm,
outro,
cancel,
step,
note,
showNextSteps,
isOnboardingComplete,
completeOnboarding,
} from '../onboarding/index.js';
export class InitCommand extends Command {
static override paths = [['init']];
@@ -24,56 +43,147 @@ export class InitCommand extends Command {
description: 'List supported agents',
});
quiet = Option.Boolean('--quiet,-q', false, {
description: 'Minimal output (no logo)',
});
async execute(): Promise<number> {
const isInteractive = process.stdin.isTTY;
// List mode
if (this.list) {
console.log(chalk.cyan('Supported agents:\n'));
if (!this.quiet) {
header('Supported Agents');
}
const adapters = getAllAdapters();
console.log('');
for (const adapter of adapters) {
console.log(` ${chalk.green(adapter.type)}`);
console.log(` Name: ${adapter.name}`);
console.log(` Skills dir: ${adapter.skillsDir}`);
console.log(` Config file: ${adapter.configFile}`);
console.log();
console.log(` ${formatAgent(adapter.type)}`);
console.log(` ${colors.muted('Skills dir:')} ${adapter.skillsDir}`);
console.log(` ${colors.muted('Config:')} ${adapter.configFile}`);
console.log('');
}
return 0;
}
try {
// Show welcome for first-time users
const isFirstRun = !isOnboardingComplete();
if (isInteractive && isFirstRun && !this.quiet) {
welcome();
} else if (!this.quiet) {
header('Initialize');
}
let agentType: AgentType;
const s = spinner();
if (this.agent) {
// Use specified agent
agentType = this.agent as AgentType;
} else if (isInteractive) {
// Auto-detect and let user confirm/change
s.start('Detecting agent...');
const detected = await detectAgent();
s.stop(`Detected: ${formatAgent(detected)}`);
const allAgents = getAllAdapters().map(a => a.type);
// Let user confirm or select different agent
const agentResult = await select({
message: 'Initialize for which agent?',
options: allAgents.map(a => ({
value: a,
label: formatAgent(a),
hint: a === detected ? '(detected)' : undefined,
})),
initialValue: detected,
});
if (isCancel(agentResult)) {
cancel('Initialization cancelled');
return 0;
}
agentType = agentResult as AgentType;
} else {
console.log(chalk.dim('Auto-detecting agent...'));
// Non-interactive: auto-detect
s.start('Detecting agent...');
agentType = await detectAgent();
s.stop(`Detected: ${formatAgent(agentType)}`);
}
const adapter = getAdapter(agentType);
console.log(chalk.cyan(`Initializing for ${adapter.name}...`));
// Initialize project
s.start(`Initializing for ${adapter.name}...`);
await initProject(agentType);
s.stop(`Initialized for ${adapter.name}`);
console.log();
console.log(chalk.green('Initialized successfully!'));
console.log();
console.log(chalk.dim('Created:'));
console.log(chalk.dim(` - ${adapter.skillsDir}/ (skills directory)`));
console.log(chalk.dim(` - skillkit.yaml (config file)`));
console.log(chalk.dim(` - ${adapter.configFile} (agent config)`));
console.log();
console.log(chalk.cyan('Next steps:'));
console.log(chalk.dim(' 1. Install skills: skillkit install owner/repo'));
console.log(chalk.dim(' 2. Sync config: skillkit sync'));
console.log(chalk.dim(' 3. Use skills: skillkit read <skill-name>'));
// Show what was created
note(
[
`${symbols.success} ${adapter.skillsDir}/ ${colors.muted('(skills directory)')}`,
`${symbols.success} skillkit.yaml ${colors.muted('(config file)')}`,
`${symbols.success} ${adapter.configFile} ${colors.muted('(agent config)')}`,
].join('\n'),
'Created'
);
// Mark onboarding complete
if (isFirstRun) {
completeOnboarding();
}
// Check for SKILL.md to offer publishing
await this.checkAndPromptPublish();
outro('Initialization complete!');
showNextSteps({
skillNames: [],
agentTypes: [agentType],
});
return 0;
} catch (error) {
console.error(chalk.red('Initialization failed'));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
} catch (err) {
console.log(colors.error('Initialization failed'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
private async checkAndPromptPublish(): Promise<void> {
if (!process.stdin.isTTY) return;
const skillMdLocations = [
join(process.cwd(), 'SKILL.md'),
join(process.cwd(), 'skills', 'SKILL.md'),
join(process.cwd(), '.claude', 'skills', 'SKILL.md'),
join(process.cwd(), '.cursor', 'skills', 'SKILL.md'),
];
const foundSkillMd = skillMdLocations.find(loc => existsSync(loc));
if (!foundSkillMd) return;
console.log('');
step(`Found SKILL.md in your project`);
const publishResult = await confirm({
message: 'Would you like to publish it to the SkillKit marketplace?',
initialValue: false,
});
if (isCancel(publishResult) || !publishResult) {
return;
}
console.log('');
console.log(colors.cyan('To publish your skill, run:'));
console.log(` ${colors.bold(`skillkit publish ${foundSkillMd}`)}`);
console.log('');
}
}
+234 -69
View File
@@ -1,13 +1,37 @@
import { existsSync, mkdirSync, cpSync, rmSync } from 'node:fs';
import { existsSync, mkdirSync, cpSync, rmSync, symlinkSync } from 'node:fs';
import { join } from 'node:path';
import chalk from 'chalk';
import ora from 'ora';
import { Command, Option } from 'clipanion';
import { detectProvider, isLocalPath, getProvider } from '@skillkit/core';
import { detectProvider, isLocalPath, getProvider, evaluateSkillDirectory } from '@skillkit/core';
import type { SkillMetadata, GitProvider, AgentType } from '@skillkit/core';
import { isPathInside } from '@skillkit/core';
import { getAdapter, detectAgent } from '@skillkit/agents';
import { getAdapter, detectAgent, getAllAdapters } from '@skillkit/agents';
import { getInstallDir, saveSkillMetadata } from '../helpers.js';
import {
welcome,
colors,
symbols,
formatAgent,
getAgentIcon,
isCancel,
spinner,
quickAgentSelect,
skillMultiselect,
selectInstallMethod,
confirm,
outro,
cancel,
step,
success,
error,
warn,
showInstallSummary,
showNextSteps,
saveLastAgents,
getLastAgents,
formatQualityBadge,
getQualityGradeFromScore,
type InstallResult,
} from '../onboarding/index.js';
export class InstallCommand extends Command {
static override paths = [['install'], ['i']];
@@ -61,10 +85,20 @@ export class InstallCommand extends Command {
description: 'Target specific agents (can specify multiple)',
});
quiet = Option.Boolean('--quiet,-q', false, {
description: 'Minimal output (no logo)',
});
async execute(): Promise<number> {
const spinner = ora();
const isInteractive = process.stdin.isTTY && !this.skills && !this.all && !this.yes;
const s = spinner();
try {
// Show welcome logo for interactive mode
if (isInteractive && !this.quiet) {
welcome();
}
let providerAdapter = detectProvider(this.source);
if (this.provider) {
@@ -72,40 +106,44 @@ export class InstallCommand extends Command {
}
if (!providerAdapter) {
console.error(chalk.red(`Could not detect provider for: ${this.source}`));
console.error(chalk.dim('Use --provider flag or specify source as:'));
console.error(chalk.dim(' GitHub: owner/repo or https://github.com/owner/repo'));
console.error(chalk.dim(' GitLab: gitlab:owner/repo or https://gitlab.com/owner/repo'));
console.error(chalk.dim(' Bitbucket: bitbucket:owner/repo'));
console.error(chalk.dim(' Local: ./path or ~/path'));
error(`Could not detect provider for: ${this.source}`);
console.log(colors.muted('Use --provider flag or specify source as:'));
console.log(colors.muted(' GitHub: owner/repo or https://github.com/owner/repo'));
console.log(colors.muted(' GitLab: gitlab:owner/repo or https://gitlab.com/owner/repo'));
console.log(colors.muted(' Bitbucket: bitbucket:owner/repo'));
console.log(colors.muted(' Local: ./path or ~/path'));
return 1;
}
spinner.start(`Fetching from ${providerAdapter.name}...`);
s.start(`Fetching from ${providerAdapter.name}...`);
const result = await providerAdapter.clone(this.source, '', { depth: 1 });
if (!result.success || !result.path) {
spinner.fail(chalk.red(result.error || 'Failed to fetch source'));
s.stop(colors.error(result.error || 'Failed to fetch source'));
return 1;
}
spinner.succeed(`Found ${result.skills?.length || 0} skill(s)`);
s.stop(`Found ${result.skills?.length || 0} skill(s)`);
const discoveredSkills = result.discoveredSkills || [];
// List mode - just show skills and exit
if (this.list) {
if (discoveredSkills.length === 0) {
console.log(chalk.yellow('\nNo skills found in this repository'));
warn('No skills found in this repository');
} else {
console.log(chalk.cyan('\nAvailable skills:\n'));
console.log('');
console.log(colors.bold('Available skills:'));
console.log('');
for (const skill of discoveredSkills) {
console.log(` ${chalk.green(skill.name)}`);
const quality = evaluateSkillDirectory(skill.path);
const qualityBadge = quality ? ` ${formatQualityBadge(quality.overall)}` : '';
console.log(` ${colors.success(symbols.stepActive)} ${colors.primary(skill.name)}${qualityBadge}`);
}
console.log();
console.log(chalk.dim(`Total: ${discoveredSkills.length} skill(s)`));
console.log(chalk.dim('\nTo install specific skills: skillkit install <source> --skills=skill1,skill2'));
console.log(chalk.dim('To install all skills: skillkit install <source> --all'));
console.log('');
console.log(colors.muted(`Total: ${discoveredSkills.length} skill(s)`));
console.log(colors.muted('To install: skillkit install <source> --skills=skill1,skill2'));
}
const cleanupPath = result.tempRoot || result.path;
@@ -118,83 +156,185 @@ export class InstallCommand extends Command {
let skillsToInstall = discoveredSkills;
// Non-interactive: use --skills filter
if (this.skills) {
const requestedSkills = this.skills.split(',').map(s => s.trim());
const available = discoveredSkills.map(s => s.name);
const notFound = requestedSkills.filter(s => !available.includes(s));
if (notFound.length > 0) {
console.error(chalk.red(`Skills not found: ${notFound.join(', ')}`));
console.error(chalk.dim(`Available: ${available.join(', ')}`));
error(`Skills not found: ${notFound.join(', ')}`);
console.log(colors.muted(`Available: ${available.join(', ')}`));
return 1;
}
skillsToInstall = discoveredSkills.filter(s => requestedSkills.includes(s.name));
} else if (this.all || this.yes) {
skillsToInstall = discoveredSkills;
} else {
skillsToInstall = discoveredSkills;
} else if (isInteractive && discoveredSkills.length > 1) {
// Interactive skill selection
step(`Source: ${colors.cyan(this.source)}`);
if (skillsToInstall.length > 0) {
console.log(chalk.cyan('\nSkills to install:'));
skillsToInstall.forEach(s => console.log(chalk.dim(` - ${s.name}`)));
console.log();
const skillResult = await skillMultiselect({
message: 'Select skills to install',
skills: discoveredSkills.map(s => ({ name: s.name })),
initialValues: discoveredSkills.map(s => s.name),
});
if (isCancel(skillResult)) {
cancel('Installation cancelled');
return 0;
}
skillsToInstall = discoveredSkills.filter(s => (skillResult as string[]).includes(s.name));
}
if (skillsToInstall.length === 0) {
console.log(chalk.yellow('No skills to install'));
warn('No skills to install');
return 0;
}
// Determine target agents
let targetAgents: AgentType[];
if (this.agent && this.agent.length > 0) {
// Explicitly specified agents
targetAgents = this.agent as AgentType[];
} else if (isInteractive) {
const allAgentTypes = getAllAdapters().map(a => a.type);
const lastAgents = getLastAgents();
step(`Detected ${allAgentTypes.length} agents`);
const agentResult = await quickAgentSelect({
message: 'Install to',
agents: allAgentTypes,
lastSelected: lastAgents,
});
if (isCancel(agentResult)) {
cancel('Installation cancelled');
return 0;
}
targetAgents = (agentResult as { agents: string[] }).agents as AgentType[];
// Save selection for next time
saveLastAgents(targetAgents);
} else {
// Non-interactive: use detected agent
const detectedAgent = await detectAgent();
targetAgents = [detectedAgent];
}
// Interactive: select installation method
let installMethod: 'symlink' | 'copy' = 'copy';
if (isInteractive && targetAgents.length > 1) {
const methodResult = await selectInstallMethod({});
if (isCancel(methodResult)) {
cancel('Installation cancelled');
return 0;
}
installMethod = methodResult as 'symlink' | 'copy';
}
// Check for low-quality skills and warn
const lowQualitySkills: Array<{ name: string; score: number; warnings: string[] }> = [];
for (const skill of skillsToInstall) {
const quality = evaluateSkillDirectory(skill.path);
if (quality && quality.overall < 60) {
lowQualitySkills.push({
name: skill.name,
score: quality.overall,
warnings: quality.warnings.slice(0, 2),
});
}
}
// Confirm installation
if (isInteractive && !this.yes) {
console.log('');
// Show low-quality warning if any
if (lowQualitySkills.length > 0) {
console.log(colors.warning(`${symbols.warning} Warning: ${lowQualitySkills.length} skill(s) have low quality scores (< 60)`));
for (const lq of lowQualitySkills) {
const grade = getQualityGradeFromScore(lq.score);
const warningText = lq.warnings.length > 0 ? ` - ${lq.warnings.join(', ')}` : '';
console.log(colors.muted(` - ${lq.name} [${grade}]${warningText}`));
}
console.log('');
}
const agentDisplay = targetAgents.length <= 3
? targetAgents.map(formatAgent).join(', ')
: `${targetAgents.slice(0, 2).map(formatAgent).join(', ')} +${targetAgents.length - 2} more`;
const confirmResult = await confirm({
message: `Install ${skillsToInstall.length} skill(s) to ${agentDisplay}?`,
initialValue: true,
});
if (isCancel(confirmResult) || !confirmResult) {
cancel('Installation cancelled');
return 0;
}
}
// Perform installation
let totalInstalled = 0;
const installResults: { agent: string; dir: string; count: number }[] = [];
const installResults: InstallResult[] = [];
for (const agentType of targetAgents) {
const adapter = getAdapter(agentType);
const installDir = getInstallDir(this.global, agentType);
for (const skill of skillsToInstall) {
const skillName = skill.name;
const sourcePath = skill.path;
const installedAgents: string[] = [];
let primaryPath: string | null = null;
if (!existsSync(installDir)) {
mkdirSync(installDir, { recursive: true });
}
for (const agentType of targetAgents) {
const adapter = getAdapter(agentType);
const installDir = getInstallDir(this.global, agentType);
if (targetAgents.length > 1) {
console.log(chalk.cyan(`\nInstalling to ${adapter.name}...`));
}
if (!existsSync(installDir)) {
mkdirSync(installDir, { recursive: true });
}
let installed = 0;
for (const skill of skillsToInstall) {
const skillName = skill.name;
const sourcePath = skill.path;
const targetPath = join(installDir, skillName);
if (existsSync(targetPath) && !this.force) {
console.log(chalk.yellow(` Skipping ${skillName} (already exists, use --force to overwrite)`));
if (!this.quiet) {
warn(`Skipping ${skillName} for ${adapter.name} (already exists, use --force)`);
}
continue;
}
const securityRoot = result.tempRoot || result.path;
if (!isPathInside(sourcePath, securityRoot)) {
console.log(chalk.red(` Skipping ${skillName} (path traversal detected)`));
error(`Skipping ${skillName} (path traversal detected)`);
continue;
}
spinner.start(`Installing ${skillName}...`);
const isSymlinkMode = installMethod === 'symlink' && targetAgents.length > 1;
const useSymlink = isSymlinkMode && primaryPath !== null;
s.start(`Installing ${skillName} to ${adapter.name}${useSymlink ? ' (symlink)' : ''}...`);
try {
if (existsSync(targetPath)) {
rmSync(targetPath, { recursive: true, force: true });
}
cpSync(sourcePath, targetPath, { recursive: true, dereference: true });
if (useSymlink && primaryPath) {
symlinkSync(primaryPath, targetPath, 'dir');
} else {
cpSync(sourcePath, targetPath, { recursive: true, dereference: true });
if (isSymlinkMode && primaryPath === null) {
primaryPath = targetPath;
}
}
const metadata: SkillMetadata = {
name: skillName,
@@ -207,41 +347,66 @@ export class InstallCommand extends Command {
};
saveSkillMetadata(targetPath, metadata);
spinner.succeed(chalk.green(`Installed ${skillName}`));
installed++;
} catch (error) {
spinner.fail(chalk.red(`Failed to install ${skillName}`));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
installedAgents.push(agentType);
s.stop(`Installed ${skillName} to ${adapter.name}${useSymlink ? ' (symlink)' : ''}`);
} catch (err) {
s.stop(colors.error(`Failed to install ${skillName} to ${adapter.name}`));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
}
}
totalInstalled += installed;
installResults.push({ agent: adapter.name, dir: installDir, count: installed });
if (installedAgents.length > 0) {
totalInstalled++;
installResults.push({
skillName,
method: installMethod,
agents: installedAgents,
path: join(getInstallDir(this.global, installedAgents[0] as AgentType), skillName),
});
}
}
// Cleanup temp directory
const cleanupPath = result.tempRoot || result.path;
if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) {
rmSync(cleanupPath, { recursive: true, force: true });
}
console.log();
if (targetAgents.length > 1) {
console.log(chalk.green(`Installed ${totalInstalled} skill(s) across ${targetAgents.length} agents:`));
for (const r of installResults) {
console.log(chalk.dim(` - ${r.agent}: ${r.count} skill(s) to ${r.dir}`));
// Show summary
if (totalInstalled > 0) {
if (isInteractive) {
showInstallSummary({
totalSkills: totalInstalled,
totalAgents: targetAgents.length,
results: installResults,
source: this.source,
});
outro('Installation complete!');
if (!this.yes) {
showNextSteps({
skillNames: installResults.map(r => r.skillName),
agentTypes: targetAgents,
syncNeeded: true,
});
}
} else {
success(`Installed ${totalInstalled} skill(s) to ${targetAgents.length} agent(s)`);
for (const r of installResults) {
console.log(colors.muted(` ${symbols.success} ${r.skillName} ${symbols.arrowRight} ${r.agents.map(getAgentIcon).join(' ')}`));
}
console.log('');
console.log(colors.muted('Run `skillkit sync` to update agent configs'));
}
} else {
console.log(chalk.green(`Installed ${totalInstalled} skill(s) to ${installResults[0]?.dir}`));
}
if (!this.yes) {
console.log(chalk.dim('\nRun `skillkit sync` to update your agent config'));
warn('No skills were installed');
}
return 0;
} catch (error) {
spinner.fail(chalk.red('Installation failed'));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
} catch (err) {
s.stop(colors.error('Installation failed'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
+35 -8
View File
@@ -1,7 +1,8 @@
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { findAllSkills } from '@skillkit/core';
import { findAllSkills, evaluateSkillDirectory } from '@skillkit/core';
import { getSearchDirs } from '../helpers.js';
import { formatQualityBadge, colors } from '../onboarding/index.js';
export class ListCommand extends Command {
static override paths = [['list'], ['ls'], ['l']];
@@ -23,6 +24,10 @@ export class ListCommand extends Command {
description: 'Show only disabled skills',
});
quality = Option.Boolean('--quality,-q', false, {
description: 'Show quality scores and grades',
});
json = Option.Boolean('--json,-j', false, {
description: 'Output as JSON',
});
@@ -44,8 +49,18 @@ export class ListCommand extends Command {
return a.name.localeCompare(b.name);
});
const skillsWithQuality = this.quality || this.json
? skills.map(s => {
const quality = evaluateSkillDirectory(s.path);
return {
...s,
quality: quality?.overall ?? null,
};
})
: skills.map(s => ({ ...s, quality: null as number | null }));
if (this.json) {
console.log(JSON.stringify(skills, null, 2));
console.log(JSON.stringify(skillsWithQuality, null, 2));
return 0;
}
@@ -57,13 +72,13 @@ export class ListCommand extends Command {
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');
const projectSkills = skillsWithQuality.filter(s => s.location === 'project');
const globalSkills = skillsWithQuality.filter(s => s.location === 'global');
if (projectSkills.length > 0) {
console.log(chalk.blue('Project skills:'));
for (const skill of projectSkills) {
printSkill(skill);
printSkill(skill, this.quality);
}
console.log();
}
@@ -71,7 +86,7 @@ export class ListCommand extends Command {
if (globalSkills.length > 0) {
console.log(chalk.dim('Global skills:'));
for (const skill of globalSkills) {
printSkill(skill);
printSkill(skill, this.quality);
}
console.log();
}
@@ -86,16 +101,28 @@ export class ListCommand extends Command {
)
);
if (this.quality) {
const qualityScores = skillsWithQuality.filter(s => s.quality !== null).map(s => s.quality!);
if (qualityScores.length > 0) {
const avgQuality = Math.round(qualityScores.reduce((a, b) => a + b, 0) / qualityScores.length);
console.log(colors.muted(`Average quality: ${avgQuality}/100`));
}
}
return 0;
}
}
function printSkill(skill: { name: string; description: string; enabled: boolean; location: string }) {
function printSkill(
skill: { name: string; description: string; enabled: boolean; location: string; quality: number | null },
showQuality = false
) {
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));
const qualityBadge = showQuality && skill.quality !== null ? ` ${formatQualityBadge(skill.quality)}` : '';
console.log(` ${status} ${name}`);
console.log(` ${status} ${name}${qualityBadge}`);
if (skill.description) {
console.log(` ${desc}`);
}
+325
View File
@@ -0,0 +1,325 @@
import { Command, Option } from 'clipanion';
import {
loadManifest,
saveManifest,
initManifest,
addToManifest,
removeFromManifest,
findManifestPath,
generateManifestFromInstalled,
findAllSkills,
} from '@skillkit/core';
import { getSearchDirs, loadSkillMetadata } from '../helpers.js';
import {
colors,
symbols,
spinner,
step,
success,
warn,
error,
header,
confirm,
isCancel,
} from '../onboarding/index.js';
export class ManifestCommand extends Command {
static override paths = [['manifest']];
static override usage = Command.Usage({
description: 'Manage .skills manifest file',
details: `
The .skills manifest file allows declarative skill management.
Commit this file to version control to share skill configurations.
`,
examples: [
['Show current manifest', '$0 manifest'],
['Initialize manifest', '$0 manifest init'],
['Add skill to manifest', '$0 manifest add owner/repo'],
['Remove skill from manifest', '$0 manifest remove owner/repo'],
['Install from manifest', '$0 manifest install'],
['Generate from installed', '$0 manifest generate'],
],
});
async execute(): Promise<number> {
const manifestPath = findManifestPath();
if (!manifestPath) {
warn('No .skills manifest found');
console.log('');
console.log(colors.muted('Create one with:'));
console.log(` ${colors.cyan('skillkit manifest init')}`);
console.log('');
console.log(colors.muted('Or generate from installed skills:'));
console.log(` ${colors.cyan('skillkit manifest generate')}`);
return 0;
}
const manifest = loadManifest(manifestPath);
if (!manifest) {
error('Failed to load manifest');
return 1;
}
header('.skills Manifest');
console.log(colors.muted(`Path: ${manifestPath}`));
console.log('');
if (manifest.skills.length === 0) {
console.log(colors.muted('No skills defined'));
} else {
console.log(colors.primary('Skills:'));
for (const skill of manifest.skills) {
const status = skill.enabled === false ? colors.muted('(disabled)') : '';
console.log(` ${colors.success(symbols.bullet)} ${skill.source} ${status}`);
if (skill.skills) {
console.log(` ${colors.muted(`Skills: ${skill.skills.join(', ')}`)}`);
}
if (skill.agents) {
console.log(` ${colors.muted(`Agents: ${skill.agents.join(', ')}`)}`);
}
}
}
console.log('');
if (manifest.agents) {
console.log(`${colors.muted('Default agents:')} ${manifest.agents.join(', ')}`);
}
if (manifest.installMethod) {
console.log(`${colors.muted('Install method:')} ${manifest.installMethod}`);
}
if (manifest.updatedAt) {
console.log(`${colors.muted('Updated:')} ${manifest.updatedAt}`);
}
console.log('');
console.log(colors.muted('Commands: init, add, remove, install, generate'));
return 0;
}
}
export class ManifestInitCommand extends Command {
static override paths = [['manifest', 'init']];
static override usage = Command.Usage({
description: 'Initialize a new .skills manifest',
});
force = Option.Boolean('--force,-f', false, {
description: 'Overwrite existing manifest',
});
async execute(): Promise<number> {
const existingPath = findManifestPath();
if (existingPath && !this.force) {
warn(`Manifest already exists: ${existingPath}`);
console.log(colors.muted('Use --force to overwrite'));
return 1;
}
initManifest();
success('Created .skills manifest');
console.log('');
console.log(colors.muted('Add skills with:'));
console.log(` ${colors.cyan('skillkit manifest add owner/repo')}`);
return 0;
}
}
export class ManifestAddCommand extends Command {
static override paths = [['manifest', 'add']];
static override usage = Command.Usage({
description: 'Add a skill source to the manifest',
});
source = Option.String({ required: true });
skills = Option.String('--skills,-s', {
description: 'Specific skills to include (comma-separated)',
});
agents = Option.String('--agents,-a', {
description: 'Target agents (comma-separated)',
});
async execute(): Promise<number> {
const options: { skills?: string[]; agents?: string[] } = {};
if (this.skills) {
options.skills = this.skills.split(',').map(s => s.trim());
}
if (this.agents) {
options.agents = this.agents.split(',').map(s => s.trim());
}
addToManifest(this.source, options);
success(`Added ${this.source} to manifest`);
return 0;
}
}
export class ManifestRemoveCommand extends Command {
static override paths = [['manifest', 'remove']];
static override usage = Command.Usage({
description: 'Remove a skill source from the manifest',
});
source = Option.String({ required: true });
async execute(): Promise<number> {
const result = removeFromManifest(this.source);
if (!result) {
error('No manifest found');
return 1;
}
success(`Removed ${this.source} from manifest`);
return 0;
}
}
export class ManifestInstallCommand extends Command {
static override paths = [['manifest', 'install']];
static override usage = Command.Usage({
description: 'Install all skills defined in the manifest',
});
yes = Option.Boolean('--yes,-y', false, {
description: 'Skip confirmation',
});
async execute(): Promise<number> {
const manifest = loadManifest();
if (!manifest) {
error('No .skills manifest found');
console.log(colors.muted('Create one with: skillkit manifest init'));
return 1;
}
const enabledSkills = manifest.skills.filter(s => s.enabled !== false);
if (enabledSkills.length === 0) {
warn('No skills to install');
return 0;
}
header('Install from Manifest');
console.log(`Installing ${enabledSkills.length} source(s):`);
for (const skill of enabledSkills) {
console.log(` ${colors.success(symbols.bullet)} ${skill.source}`);
}
console.log('');
if (!this.yes && process.stdin.isTTY) {
const confirmResult = await confirm({
message: 'Proceed with installation?',
initialValue: true,
});
if (isCancel(confirmResult) || !confirmResult) {
return 0;
}
}
const s = spinner();
for (const skill of enabledSkills) {
s.start(`Installing ${skill.source}...`);
try {
const args = ['install', skill.source];
if (skill.skills) {
args.push('--skills', skill.skills.join(','));
}
if (skill.agents || manifest.agents) {
const agents = skill.agents || manifest.agents || [];
for (const agent of agents) {
args.push('--agent', agent);
}
}
args.push('--yes');
const { execFileSync } = await import('node:child_process');
execFileSync('skillkit', args, {
stdio: 'pipe',
encoding: 'utf-8',
});
s.stop(`Installed ${skill.source}`);
} catch (err) {
s.stop(colors.error(`Failed: ${skill.source}`));
if (err instanceof Error) {
console.log(colors.muted(err.message));
}
}
}
success('Manifest installation complete');
return 0;
}
}
export class ManifestGenerateCommand extends Command {
static override paths = [['manifest', 'generate']];
static override usage = Command.Usage({
description: 'Generate manifest from currently installed skills',
});
output = Option.String('--output,-o', {
description: 'Output file path (default: .skills)',
});
async execute(): Promise<number> {
const searchDirs = getSearchDirs();
const installedSkills = findAllSkills(searchDirs);
if (installedSkills.length === 0) {
warn('No installed skills found');
return 0;
}
step(`Found ${installedSkills.length} installed skill(s)`);
const skillsWithMeta = installedSkills.map(skill => {
const metadata = loadSkillMetadata(skill.path);
return {
name: skill.name,
source: metadata?.source || '',
};
}).filter(s => s.source);
const manifest = generateManifestFromInstalled(skillsWithMeta);
const outputPath = this.output || '.skills';
saveManifest(manifest, outputPath);
success(`Generated ${outputPath} with ${manifest.skills.length} source(s)`);
console.log('');
console.log(colors.muted('Commit this file to share skill configuration with your team.'));
return 0;
}
}
+101 -63
View File
@@ -1,14 +1,18 @@
import { Command, Option } from 'clipanion';
import chalk from 'chalk';
import ora from 'ora';
import {
createMarketplaceAggregator,
type MarketplaceSearchOptions,
} from '@skillkit/core';
import {
header,
colors,
spinner,
warn,
showMarketplaceInfo,
showSkillList,
progressBar,
} from '../onboarding/index.js';
/**
* Marketplace command - browse and install skills from the marketplace
*/
export class MarketplaceCommand extends Command {
static override paths = [['marketplace'], ['market'], ['mp']];
@@ -51,6 +55,10 @@ export class MarketplaceCommand extends Command {
description: 'Output as JSON',
});
quiet = Option.Boolean('--quiet,-q', false, {
description: 'Minimal output',
});
async execute(): Promise<number> {
const marketplace = createMarketplaceAggregator();
@@ -73,11 +81,16 @@ export class MarketplaceCommand extends Command {
}
private async browseMarketplace(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
const spinner = ora('Loading marketplace...').start();
if (!this.quiet && !this.json) {
header('Skill Marketplace');
}
const s = spinner();
s.start('Loading marketplace...');
try {
const index = await marketplace.getIndex();
spinner.stop();
s.stop('Marketplace loaded');
if (this.json) {
console.log(JSON.stringify({
@@ -88,31 +101,31 @@ export class MarketplaceCommand extends Command {
return 0;
}
console.log(chalk.bold('Skill Marketplace\n'));
console.log(`Total skills: ${chalk.cyan(index.totalCount)}`);
console.log(`Sources: ${chalk.cyan(index.sources.length)}`);
console.log(`Last updated: ${chalk.dim(new Date(index.updatedAt).toLocaleString())}\n`);
// Show marketplace info
showMarketplaceInfo({
totalSkills: index.totalCount,
sourceCount: index.sources.length,
lastUpdated: index.updatedAt,
});
// Show featured skills
console.log(colors.bold('Featured Skills:'));
console.log('');
// Show sample skills
console.log(chalk.bold('Featured Skills:\n'));
const featured = index.skills.slice(0, 10);
showSkillList(featured.map(skill => ({
name: skill.name,
description: skill.description,
source: skill.source.name,
})));
for (const skill of featured) {
console.log(` ${chalk.cyan(skill.name)}`);
if (skill.description) {
console.log(` ${chalk.dim(skill.description.slice(0, 60))}${skill.description.length > 60 ? '...' : ''}`);
}
console.log(` ${chalk.dim(`Source: ${skill.source.name}`)}`);
console.log();
}
console.log(chalk.dim('Use "skillkit marketplace search <query>" to search for skills.'));
console.log(chalk.dim('Use "skillkit marketplace tags" to see popular tags.'));
console.log(colors.muted('Use "skillkit marketplace search <query>" to search for skills.'));
console.log(colors.muted('Use "skillkit marketplace tags" to see popular tags.'));
return 0;
} catch (error) {
spinner.fail('Failed to load marketplace');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
} catch (err) {
s.stop(colors.error('Failed to load marketplace'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
@@ -120,12 +133,16 @@ export class MarketplaceCommand extends Command {
private async searchSkills(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
const query = this.query || this.action;
if (!this.quiet && !this.json) {
header('Search Skills');
}
// Validate and parse limit
let limit = 20;
if (this.limit) {
const parsed = parseInt(this.limit, 10);
if (isNaN(parsed) || parsed <= 0) {
console.error(chalk.red('Invalid --limit value. Must be a positive number.'));
console.log(colors.error('Invalid --limit value. Must be a positive number.'));
return 1;
}
limit = parsed;
@@ -137,7 +154,8 @@ export class MarketplaceCommand extends Command {
.map((t) => t.trim())
.filter((t) => t.length > 0);
const spinner = ora(`Searching for "${query}"...`).start();
const s = spinner();
s.start(`Searching for "${query}"...`);
try {
const options: MarketplaceSearchOptions = {
@@ -148,7 +166,7 @@ export class MarketplaceCommand extends Command {
};
const result = await marketplace.search(options);
spinner.stop();
s.stop(`Found ${result.total} skill(s)`);
if (this.json) {
console.log(JSON.stringify(result));
@@ -156,77 +174,94 @@ export class MarketplaceCommand extends Command {
}
if (result.skills.length === 0) {
console.log(chalk.yellow(`No skills found${query ? ` matching "${query}"` : ''}.`));
warn(`No skills found${query ? ` matching "${query}"` : ''}.`);
return 0;
}
console.log(chalk.bold(`Found ${result.total} skill(s):\n`));
console.log('');
console.log(colors.bold(`Found ${result.total} skill(s):`));
console.log('');
for (const skill of result.skills) {
console.log(`${chalk.cyan(skill.name)} ${chalk.dim(`(${skill.source.name})`)}`);
if (skill.description) {
console.log(` ${skill.description}`);
}
if (skill.tags.length > 0) {
console.log(` Tags: ${chalk.dim(skill.tags.join(', '))}`);
}
console.log();
}
showSkillList(result.skills.map(skill => ({
name: skill.name,
description: skill.description,
source: skill.source.name,
})));
if (result.total > result.skills.length) {
console.log(chalk.dim(`Showing ${result.skills.length} of ${result.total} results. Use --limit to see more.`));
console.log(colors.muted(`Showing ${result.skills.length} of ${result.total} results. Use --limit to see more.`));
}
return 0;
} catch (error) {
spinner.fail('Search failed');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
} catch (err) {
s.stop(colors.error('Search failed'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
private async refreshIndex(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
const spinner = ora('Refreshing marketplace index...').start();
if (!this.quiet) {
header('Refresh Marketplace');
}
const s = spinner();
s.start('Refreshing marketplace index...');
try {
const index = await marketplace.refresh();
spinner.succeed(`Marketplace refreshed: ${index.totalCount} skills from ${index.sources.length} sources`);
s.stop(`Refreshed: ${index.totalCount} skills from ${index.sources.length} sources`);
return 0;
} catch (error) {
spinner.fail('Refresh failed');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
} catch (err) {
s.stop(colors.error('Refresh failed'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
private async showTags(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
const spinner = ora('Loading tags...').start();
if (!this.quiet && !this.json) {
header('Popular Tags');
}
const s = spinner();
s.start('Loading tags...');
try {
const tags = await marketplace.getPopularTags(30);
spinner.stop();
s.stop('Tags loaded');
if (this.json) {
console.log(JSON.stringify(tags));
return 0;
}
console.log(chalk.bold('Popular Tags:\n'));
console.log('');
console.log(colors.bold('Popular Tags:'));
console.log('');
const maxCount = Math.max(...tags.map(t => t.count));
for (const { tag, count } of tags) {
const bar = '█'.repeat(Math.min(count, 20));
console.log(` ${tag.padEnd(15)} ${chalk.cyan(bar)} ${count}`);
const bar = progressBar(count, maxCount, 20);
console.log(` ${tag.padEnd(15)} ${colors.dim(bar)} ${colors.muted(String(count))}`);
}
console.log('');
return 0;
} catch (error) {
spinner.fail('Failed to load tags');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
} catch (err) {
s.stop(colors.error('Failed to load tags'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
private async showSources(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
if (!this.quiet && !this.json) {
header('Skill Sources');
}
const sources = marketplace.getSources();
if (this.json) {
@@ -234,15 +269,18 @@ export class MarketplaceCommand extends Command {
return 0;
}
console.log(chalk.bold('Skill Sources:\n'));
console.log('');
console.log(colors.bold('Skill Sources:'));
console.log('');
for (const source of sources) {
console.log(`${chalk.cyan(source.name)} ${source.official ? chalk.green('(official)') : ''}`);
console.log(` ${chalk.dim(`${source.owner}/${source.repo}`)}`);
const officialBadge = source.official ? colors.success(' (official)') : '';
console.log(`${colors.cyan(source.name)}${officialBadge}`);
console.log(` ${colors.muted(`${source.owner}/${source.repo}`)}`);
if (source.description) {
console.log(` ${source.description}`);
}
console.log();
console.log('');
}
return 0;
+297
View File
@@ -0,0 +1,297 @@
import { existsSync, readFileSync } from 'node:fs';
import { join, basename, dirname } from 'node:path';
import { execSync } from 'node:child_process';
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
interface SkillFrontmatter {
name?: string;
description?: string;
tags?: string[];
version?: string;
}
export class PublishCommand extends Command {
static override paths = [['publish']];
static override usage = Command.Usage({
description: 'Publish your skill to the SkillKit marketplace',
examples: [
['Publish skill from current directory', '$0 publish'],
['Publish skill from specific path', '$0 publish ./my-skill'],
['Publish with custom name', '$0 publish --name my-awesome-skill'],
],
});
skillPath = Option.String({ required: false, name: 'path' });
name = Option.String('--name,-n', {
description: 'Custom skill name (default: parsed from SKILL.md)',
});
dryRun = Option.Boolean('--dry-run', false, {
description: 'Show what would be published without actually publishing',
});
async execute(): Promise<number> {
const skillPath = this.skillPath || process.cwd();
const skillMdPath = this.findSkillMd(skillPath);
if (!skillMdPath) {
console.error(chalk.red('No SKILL.md found'));
console.error(chalk.dim('Run this command from a directory containing SKILL.md'));
console.error(chalk.dim('Or specify the path: skillkit publish ./path/to/skill'));
return 1;
}
console.log(chalk.cyan('Publishing skill to SkillKit marketplace...\n'));
// Parse SKILL.md
const content = readFileSync(skillMdPath, 'utf-8');
const frontmatter = this.parseFrontmatter(content);
const skillName = this.name || frontmatter.name || basename(dirname(skillMdPath));
// Get git repo info
const repoInfo = this.getRepoInfo(dirname(skillMdPath));
if (!repoInfo) {
console.error(chalk.red('Not a git repository or no remote configured'));
console.error(chalk.dim('Your skill must be in a git repository with a GitHub remote'));
return 1;
}
// Build skill entry
const skillSlug = this.slugify(skillName);
if (!skillSlug) {
console.error(chalk.red('Skill name produces an empty slug.'));
console.error(chalk.dim('Please pass --name with letters or numbers.'));
return 1;
}
const skillEntry = {
id: `${repoInfo.owner}/${repoInfo.repo}/${skillSlug}`,
name: this.formatName(skillName),
description: frontmatter.description || `Best practices and patterns for ${this.formatName(skillName)}`,
source: `${repoInfo.owner}/${repoInfo.repo}`,
tags: frontmatter.tags || this.inferTags(skillName, frontmatter.description || ''),
};
console.log(chalk.white('Skill details:'));
console.log(chalk.dim(` ID: ${skillEntry.id}`));
console.log(chalk.dim(` Name: ${skillEntry.name}`));
console.log(chalk.dim(` Description: ${skillEntry.description}`));
console.log(chalk.dim(` Source: ${skillEntry.source}`));
console.log(chalk.dim(` Tags: ${skillEntry.tags.join(', ')}`));
console.log();
if (this.dryRun) {
console.log(chalk.yellow('Dry run - not publishing'));
console.log(chalk.dim('JSON entry that would be added:'));
console.log(JSON.stringify(skillEntry, null, 2));
return 0;
}
// Create GitHub issue to add skill
const issueBody = this.createIssueBody(skillEntry);
const issueTitle = encodeURIComponent(`[Publish] ${skillEntry.name}`);
const issueBodyEncoded = encodeURIComponent(issueBody);
const issueUrl = `https://github.com/rohitg00/skillkit/issues/new?title=${issueTitle}&body=${issueBodyEncoded}&labels=skill-submission,publish`;
console.log(chalk.green('Opening GitHub to submit your skill...\n'));
try {
// Try to open the URL
const openCmd =
process.platform === 'darwin'
? `open "${issueUrl}"`
: process.platform === 'win32'
? `cmd /c start "" "${issueUrl}"`
: `xdg-open "${issueUrl}"`;
execSync(openCmd, { stdio: 'ignore' });
console.log(chalk.green('GitHub issue page opened!'));
console.log(chalk.dim('Review and submit the issue to publish your skill.'));
} catch {
console.log(chalk.yellow('Could not open browser automatically.'));
console.log(chalk.dim('Please open this URL manually:\n'));
console.log(chalk.cyan(issueUrl));
}
console.log();
console.log(chalk.cyan('Next steps:'));
console.log(chalk.dim(' 1. Review the skill details in the GitHub issue'));
console.log(chalk.dim(' 2. Submit the issue'));
console.log(chalk.dim(' 3. A maintainer will review and add your skill'));
return 0;
}
private findSkillMd(basePath: string): string | null {
// Check if path is directly to SKILL.md
if (basePath.endsWith('SKILL.md') && existsSync(basePath)) {
return basePath;
}
// Check if SKILL.md exists in the directory
const direct = join(basePath, 'SKILL.md');
if (existsSync(direct)) {
return direct;
}
// Check common skill locations
const locations = [
join(basePath, 'skills', 'SKILL.md'),
join(basePath, '.claude', 'skills', 'SKILL.md'),
join(basePath, '.cursor', 'skills', 'SKILL.md'),
];
for (const loc of locations) {
if (existsSync(loc)) {
return loc;
}
}
return null;
}
private parseFrontmatter(content: string): SkillFrontmatter {
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
if (!match) return {};
const frontmatter: SkillFrontmatter = {};
const lines = match[1].split(/\r?\n/);
let inTagsList = false;
for (const line of lines) {
// Handle multiline tags list
if (inTagsList) {
const tagMatch = line.match(/^\s*-\s*(.+)$/);
if (tagMatch) {
frontmatter.tags ??= [];
frontmatter.tags.push(tagMatch[1].trim().replace(/^["']|["']$/g, ''));
continue;
}
if (line.trim() === '') continue;
inTagsList = false;
}
const colonIdx = line.indexOf(':');
if (colonIdx === -1) continue;
const key = line.slice(0, colonIdx).trim();
const value = line.slice(colonIdx + 1).trim();
switch (key) {
case 'name':
frontmatter.name = value.replace(/^["']|["']$/g, '');
break;
case 'description':
frontmatter.description = value.replace(/^["']|["']$/g, '');
break;
case 'version':
frontmatter.version = value.replace(/^["']|["']$/g, '');
break;
case 'tags':
// Parse YAML array: [tag1, tag2] or multiline list
if (value.startsWith('[')) {
frontmatter.tags = value
.slice(1, -1)
.split(',')
.map(t => t.trim().replace(/^["']|["']$/g, ''))
.filter(t => t.length > 0);
} else if (value === '') {
inTagsList = true;
frontmatter.tags = [];
}
break;
}
}
return frontmatter;
}
private slugify(name: string): string {
return name
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}
private getRepoInfo(dir: string): { owner: string; repo: string } | null {
try {
const remote = execSync('git remote get-url origin', {
cwd: dir,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'ignore'],
}).trim();
// Parse GitHub URL: git@github.com:owner/repo.git or https://github.com/owner/repo.git
const match = remote.match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?$/);
if (match) {
return { owner: match[1], repo: match[2] };
}
} catch {
// Not a git repo or no remote
}
return null;
}
private formatName(name: string): string {
return name
.split(/[-_]/)
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
private inferTags(name: string, description: string): string[] {
const tags: string[] = [];
const text = `${name} ${description}`.toLowerCase();
const tagMap: Record<string, string[]> = {
react: ['react', 'jsx', 'tsx'],
typescript: ['typescript', 'ts'],
nextjs: ['next', 'nextjs'],
testing: ['test', 'jest', 'vitest'],
mobile: ['mobile', 'react-native', 'expo'],
backend: ['backend', 'api', 'server'],
database: ['database', 'postgres', 'mysql', 'supabase'],
frontend: ['frontend', 'ui', 'design'],
devops: ['devops', 'ci', 'cd', 'docker'],
};
for (const [tag, keywords] of Object.entries(tagMap)) {
if (keywords.some(k => text.includes(k))) {
tags.push(tag);
}
}
return tags.length > 0 ? tags : ['general'];
}
private createIssueBody(
skill: { id: string; name: string; description: string; source: string; tags: string[] }
): string {
return `## Publish Skill Request
### Skill Details
- **ID:** \`${skill.id}\`
- **Name:** ${skill.name}
- **Description:** ${skill.description}
- **Source:** [${skill.source}](https://github.com/${skill.source})
- **Tags:** ${skill.tags.map(t => `\`${t}\``).join(', ')}
### JSON Entry
\`\`\`json
${JSON.stringify(skill, null, 2)}
\`\`\`
### Checklist
- [ ] SKILL.md follows the standard format
- [ ] Skill is publicly accessible on GitHub
- [ ] Description accurately describes the skill
- [ ] Tags are appropriate
---
Submitted via \`skillkit publish\``;
}
}
+110 -96
View File
@@ -1,7 +1,5 @@
import { Command, Option } from 'clipanion';
import { resolve } from 'node:path';
import chalk from 'chalk';
import ora from 'ora';
import {
type ProjectProfile,
type ScoredSkill,
@@ -14,10 +12,18 @@ import {
INDEX_PATH,
KNOWN_SKILL_REPOS,
} from '@skillkit/core';
import {
header,
colors,
symbols,
spinner,
warn,
showProjectSummary,
progressBar,
formatQualityBadge,
getQualityGradeFromScore,
} from '../onboarding/index.js';
/**
* Recommend command - get smart skill recommendations based on project analysis
*/
export class RecommendCommand extends Command {
static override paths = [['recommend'], ['rec']];
@@ -97,6 +103,11 @@ export class RecommendCommand extends Command {
description: 'Project path (default: current directory)',
});
// Quiet mode
quiet = Option.Boolean('--quiet,-q', false, {
description: 'Minimal output',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
@@ -105,19 +116,23 @@ export class RecommendCommand extends Command {
return await this.updateIndex();
}
if (!this.quiet && !this.json) {
header('Skill Recommendations');
}
// Load or create project profile
const profile = await this.getProjectProfile(targetPath);
if (!profile) {
console.error(chalk.red('Failed to analyze project'));
console.log(colors.error('Failed to analyze project'));
return 1;
}
// Load skill index
const index = this.loadIndex();
if (!index || index.skills.length === 0) {
console.log(chalk.yellow('No skill index found.'));
console.log(chalk.dim('Run "skillkit recommend --update" to fetch skills from known sources.'));
console.log(chalk.dim('Or install skills manually with "skillkit install <source>"\n'));
warn('No skill index found.');
console.log(colors.muted('Run "skillkit recommend --update" to fetch skills from known sources.'));
console.log(colors.muted('Or install skills manually with "skillkit install <source>"\n'));
// Still show project profile
this.showProjectProfile(profile);
@@ -153,19 +168,20 @@ export class RecommendCommand extends Command {
return 0;
}
/**
* Get project profile from context or by analyzing project
*/
private async getProjectProfile(projectPath: string): Promise<ProjectProfile | null> {
const manager = new ContextManager(projectPath);
let context = manager.get();
if (!context) {
// Auto-analyze project
if (!this.json) {
console.log(chalk.dim('Analyzing project...\n'));
if (!this.json && !this.quiet) {
const s = spinner();
s.start('Analyzing project...');
context = manager.init();
s.stop('Project analyzed');
} else {
context = manager.init();
}
context = manager.init();
}
if (!context) {
@@ -183,33 +199,18 @@ export class RecommendCommand extends Command {
};
}
/**
* Show project profile summary
*/
private showProjectProfile(profile: ProjectProfile): void {
console.log(chalk.cyan('Project Profile:'));
console.log(` Name: ${chalk.bold(profile.name)}`);
if (profile.type) {
console.log(` Type: ${profile.type}`);
}
const languages = profile.stack.languages.map(l => `${l.name}${l.version ? ` ${l.version}` : ''}`);
const frameworks = profile.stack.frameworks.map(f => `${f.name}${f.version ? ` ${f.version}` : ''}`);
const stackItems: string[] = [];
for (const lang of profile.stack.languages) {
stackItems.push(`${lang.name}${lang.version ? ` ${lang.version}` : ''}`);
}
for (const fw of profile.stack.frameworks) {
stackItems.push(`${fw.name}${fw.version ? ` ${fw.version}` : ''}`);
}
if (stackItems.length > 0) {
console.log(` Stack: ${chalk.dim(stackItems.join(', '))}`);
}
console.log();
showProjectSummary({
name: profile.name,
type: profile.type,
languages,
frameworks,
});
}
/**
* Display recommendations
*/
private displayRecommendations(
recommendations: ScoredSkill[],
profile: ProjectProfile,
@@ -219,59 +220,67 @@ export class RecommendCommand extends Command {
this.showProjectProfile(profile);
if (recommendations.length === 0) {
console.log(chalk.yellow('No matching skills found.'));
console.log(chalk.dim('Try lowering the minimum score with --min-score'));
warn('No matching skills found.');
console.log(colors.muted('Try lowering the minimum score with --min-score'));
return;
}
console.log(chalk.cyan(`Recommended Skills (${recommendations.length} of ${totalScanned} scanned):\n`));
console.log(colors.bold(`Recommended Skills (${recommendations.length} of ${totalScanned} scanned):`));
console.log('');
for (const rec of recommendations) {
const scoreColor = rec.score >= 70 ? chalk.green : rec.score >= 50 ? chalk.yellow : chalk.dim;
const scoreBar = this.getScoreBar(rec.score);
let scoreColor: (text: string) => string;
if (rec.score >= 70) {
scoreColor = colors.success;
} else if (rec.score >= 50) {
scoreColor = colors.warning;
} else {
scoreColor = colors.muted;
}
const scoreBar = progressBar(rec.score, 100, 10);
const qualityScore = rec.skill.quality ?? null;
const qualityDisplay = qualityScore !== null && qualityScore !== undefined
? ` ${formatQualityBadge(qualityScore)}`
: '';
console.log(` ${scoreColor(`${rec.score}%`)} ${scoreBar} ${chalk.bold(rec.skill.name)}`);
console.log(` ${scoreColor(`${rec.score}%`)} ${colors.dim(scoreBar)} ${colors.bold(rec.skill.name)}${qualityDisplay}`);
if (rec.skill.description) {
console.log(` ${chalk.dim(truncate(rec.skill.description, 70))}`);
console.log(` ${colors.muted(truncate(rec.skill.description, 70))}`);
}
if (rec.skill.source) {
console.log(` ${chalk.dim('Source:')} ${rec.skill.source}`);
console.log(` ${colors.dim('Source:')} ${rec.skill.source}`);
}
if (this.verbose && rec.reasons.length > 0) {
console.log(chalk.dim(' Reasons:'));
console.log(colors.dim(' Reasons:'));
for (const reason of rec.reasons.filter(r => r.weight > 0)) {
console.log(` ${chalk.dim('•')} ${reason.description} (+${reason.weight})`);
console.log(` ${colors.muted(symbols.stepActive)} ${reason.description} (+${reason.weight})`);
}
if (qualityScore !== null && qualityScore !== undefined) {
const grade = getQualityGradeFromScore(qualityScore);
console.log(` ${colors.muted(symbols.stepActive)} Quality: ${qualityScore}/100 (${grade})`);
}
}
if (rec.warnings.length > 0) {
for (const warning of rec.warnings) {
console.log(` ${chalk.yellow('⚠')} ${warning}`);
console.log(` ${colors.warning(symbols.warning)} ${warning}`);
}
}
console.log();
console.log('');
}
console.log(chalk.dim('Install with: skillkit install <source>'));
console.log(colors.muted('Install with: skillkit install <source>'));
}
/**
* Generate a visual score bar
*/
private getScoreBar(score: number): string {
const filled = Math.round(score / 10);
const empty = 10 - filled;
return chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
}
/**
* Handle search mode
*/
private handleSearch(engine: RecommendationEngine, query: string): number {
if (!this.quiet && !this.json) {
header(`Search: "${query}"`);
}
const results = engine.search({
query,
limit: this.limit ? parseInt(this.limit, 10) : 10,
@@ -287,35 +296,41 @@ export class RecommendCommand extends Command {
}
if (results.length === 0) {
console.log(chalk.yellow(`No skills found matching "${query}"`));
warn(`No skills found matching "${query}"`);
return 0;
}
console.log(chalk.cyan(`Search results for "${query}" (${results.length} found):\n`));
console.log('');
console.log(colors.bold(`Search results for "${query}" (${results.length} found):`));
console.log('');
for (const result of results) {
const relevanceColor =
result.relevance >= 70 ? chalk.green : result.relevance >= 50 ? chalk.yellow : chalk.dim;
let relevanceColor: (text: string) => string;
if (result.relevance >= 70) {
relevanceColor = colors.success;
} else if (result.relevance >= 50) {
relevanceColor = colors.warning;
} else {
relevanceColor = colors.muted;
}
const relevanceBar = progressBar(result.relevance, 100, 10);
console.log(` ${relevanceColor(`${result.relevance}%`)} ${chalk.bold(result.skill.name)}`);
console.log(` ${relevanceColor(`${result.relevance}%`)} ${colors.dim(relevanceBar)} ${colors.bold(result.skill.name)}`);
if (result.snippet) {
console.log(` ${chalk.dim(result.snippet)}`);
console.log(` ${colors.muted(result.snippet)}`);
}
if (result.matchedTerms.length > 0) {
console.log(` ${chalk.dim('Matched:')} ${result.matchedTerms.join(', ')}`);
console.log(` ${colors.dim('Matched:')} ${result.matchedTerms.join(', ')}`);
}
console.log();
console.log('');
}
return 0;
}
/**
* Load skill index from cache
*/
private loadIndex() {
const index = loadIndexFromCache();
@@ -324,63 +339,62 @@ export class RecommendCommand extends Command {
}
// Check if index is stale
if (isIndexStale(index) && !this.json) {
if (isIndexStale(index) && !this.json && !this.quiet) {
const lastUpdated = new Date(index.lastUpdated);
const hoursSinceUpdate = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60);
console.log(
chalk.dim(`Index is ${Math.round(hoursSinceUpdate)} hours old. Run --update to refresh.\n`)
colors.muted(`Index is ${Math.round(hoursSinceUpdate)} hours old. Run --update to refresh.\n`)
);
}
return index;
}
/**
* Update skill index from sources
*/
private async updateIndex(): Promise<number> {
console.log(chalk.cyan('Updating skill index from GitHub repositories...\n'));
console.log(chalk.dim(`Sources: ${KNOWN_SKILL_REPOS.map(r => `${r.owner}/${r.repo}`).join(', ')}\n`));
if (!this.quiet) {
header('Update Skill Index');
}
const spinner = ora('Fetching skills...').start();
console.log(colors.muted(`Sources: ${KNOWN_SKILL_REPOS.map(r => `${r.owner}/${r.repo}`).join(', ')}\n`));
const s = spinner();
s.start('Fetching skills...');
try {
const { index, errors } = await buildSkillIndex(KNOWN_SKILL_REPOS, (message) => {
spinner.text = message;
s.message(message);
});
spinner.stop();
s.stop(`Fetched ${index.skills.length} skills`);
// Report any errors
if (errors.length > 0) {
console.log(chalk.yellow('\nWarnings:'));
console.log('');
console.log(colors.warning('Warnings:'));
for (const error of errors) {
console.log(chalk.dim(` • ${error}`));
console.log(colors.muted(` ${symbols.stepActive} ${error}`));
}
console.log();
}
// Save the index
saveIndex(index);
console.log(chalk.green(`✓ Updated index with ${index.skills.length} skills`));
console.log('');
console.log(colors.success(`${symbols.success} Updated index with ${index.skills.length} skills`));
if (index.sources.length > 0) {
console.log(chalk.dim(` Sources: ${index.sources.map((s) => s.name).join(', ')}`));
console.log(colors.muted(` Sources: ${index.sources.map((s) => s.name).join(', ')}`));
}
console.log(chalk.dim(` Saved to: ${INDEX_PATH}\n`));
console.log(colors.muted(` Saved to: ${INDEX_PATH}\n`));
return 0;
} catch (error) {
spinner.fail('Failed to update index');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
} catch (err) {
s.stop(colors.error('Failed to update index'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
}
/**
* Truncate string to max length
*/
function truncate(str: string, maxLen: number): string {
if (str.length <= maxLen) return str;
return str.slice(0, maxLen - 3) + '...';
+100 -18
View File
@@ -1,11 +1,24 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { loadConfig, findAllSkills } from '@skillkit/core';
import type { AgentType } from '@skillkit/core';
import { getAdapter, detectAgent } from '@skillkit/agents';
import { getAdapter, detectAgent, getAllAdapters } from '@skillkit/agents';
import { getSearchDirs, getAgentConfigPath } from '../helpers.js';
import {
header,
colors,
symbols,
formatAgent,
isCancel,
spinner,
select,
confirm,
outro,
cancel,
warn,
showSyncSummary,
} from '../onboarding/index.js';
export class SyncCommand extends Command {
static override paths = [['sync'], ['s']];
@@ -36,19 +49,54 @@ export class SyncCommand extends Command {
description: 'Skip confirmation prompts',
});
quiet = Option.Boolean('--quiet,-q', false, {
description: 'Minimal output',
});
async execute(): Promise<number> {
const isInteractive = process.stdin.isTTY && !this.yes;
if (!this.quiet) {
header('Sync Skills');
}
try {
let agentType: AgentType;
const s = spinner();
if (this.agent) {
agentType = this.agent as AgentType;
} else if (isInteractive) {
// Let user select agent
s.start('Detecting agent...');
const config = loadConfig();
const detected = config.agent || (await detectAgent());
s.stop(`Detected: ${formatAgent(detected)}`);
const allAgents = getAllAdapters().map(a => a.type);
const agentResult = await select({
message: 'Sync to which agent?',
options: allAgents.map(a => ({
value: a,
label: formatAgent(a),
hint: a === detected ? '(current)' : undefined,
})),
initialValue: detected,
});
if (isCancel(agentResult)) {
cancel('Sync cancelled');
return 0;
}
agentType = agentResult as AgentType;
} else {
const config = loadConfig();
agentType = config.agent || (await detectAgent());
}
const adapter = getAdapter(agentType);
const outputPath = this.output || getAgentConfigPath(agentType);
const searchDirs = getSearchDirs(agentType);
@@ -59,23 +107,47 @@ export class SyncCommand extends Command {
}
if (skills.length === 0) {
console.log(chalk.yellow('No skills found to sync'));
console.log(chalk.dim('Install skills with: skillkit install <source>'));
warn('No skills found to sync');
console.log(colors.muted('Install skills with: skillkit install <source>'));
return 0;
}
console.log(chalk.cyan(`Syncing ${skills.length} skill(s) for ${adapter.name}:`));
skills.forEach(s => {
const status = s.enabled ? chalk.green('✓') : chalk.dim('○');
const location = s.location === 'project' ? chalk.blue('[project]') : chalk.dim('[global]');
console.log(` ${status} ${s.name} ${location}`);
});
console.log();
// Show skills to sync
if (!this.quiet) {
console.log('');
console.log(colors.bold(`Syncing ${skills.length} skill(s) for ${adapter.name}:`));
console.log('');
for (const skill of skills) {
const status = skill.enabled ? colors.success(symbols.success) : colors.muted(symbols.stepPending);
const location = skill.location === 'project'
? colors.cyan('[project]')
: colors.muted('[global]');
console.log(` ${status} ${skill.name} ${location}`);
}
console.log('');
}
// Confirm sync
if (isInteractive && !this.yes) {
const confirmResult = await confirm({
message: `Sync ${skills.length} skill(s) to ${outputPath}?`,
initialValue: true,
});
if (isCancel(confirmResult) || !confirmResult) {
cancel('Sync cancelled');
return 0;
}
}
// Generate and write config
s.start('Generating config...');
const config = adapter.generateConfig(skills);
if (!config) {
console.log(chalk.yellow('No configuration generated'));
s.stop('No configuration generated');
return 0;
}
@@ -93,13 +165,23 @@ export class SyncCommand extends Command {
writeFileSync(outputPath, newContent, 'utf-8');
console.log(chalk.green(`Synced to ${outputPath}`));
console.log(chalk.dim(`Agent: ${adapter.name}`));
s.stop('Config generated');
// Show summary
showSyncSummary({
skillCount: skills.length,
agentType,
configPath: outputPath,
});
if (!this.quiet) {
outro('Sync complete!');
}
return 0;
} catch (error) {
console.error(chalk.red('Sync failed'));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
} catch (err) {
console.log(colors.error('Sync failed'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
+34 -3
View File
@@ -1,10 +1,26 @@
import { Command } from 'clipanion';
/**
* UI Command - Launch the SkillKit TUI
* Uses the unified OpenTUI-based interface
*/
export class UICommand extends Command {
static override paths = [['ui'], ['tui']];
static override usage = Command.Usage({
description: 'Launch the interactive TUI (Terminal User Interface)',
details: `
Launches the SkillKit TUI with a beautiful monochromatic design.
Features:
- Browse and discover skills from the marketplace
- Manage installed skills across 17+ AI coding agents
- Sync skills between agents
- AI-powered recommendations
- Team collaboration
Requires Bun runtime (>=1.2.0) for optimal performance.
`,
examples: [
['Open interactive TUI', '$0 ui'],
['Alias for TUI', '$0 tui'],
@@ -12,8 +28,23 @@ export class UICommand extends Command {
});
async execute(): Promise<number> {
const { startTUI } = await import('@skillkit/tui');
await startTUI();
return 0;
try {
const { startTUI } = await import('@skillkit/tui');
await startTUI();
return 0;
} catch (err) {
if (err instanceof Error) {
console.error('Error launching TUI:', err.message);
console.error('');
console.error('The TUI requires Bun runtime (>=1.2.0). Run with:');
console.error(' bun $(which skillkit) ui');
console.error('');
console.error('Or from source directory:');
console.error(' bun ./apps/skillkit/dist/cli.js ui');
console.error('');
console.error('Install Bun from: https://bun.sh');
}
return 1;
}
}
}
+408 -54
View File
@@ -1,87 +1,441 @@
import { existsSync, readdirSync } from 'node:fs';
import { join, basename } from 'node:path';
import chalk from 'chalk';
import { existsSync, readdirSync, statSync } from 'node:fs';
import { join, basename, resolve, dirname } from 'node:path';
import { Command, Option } from 'clipanion';
import { validateSkill } from '@skillkit/core';
import {
validateSkill,
evaluateSkillFile,
evaluateSkillDirectory,
getQualityGrade,
isHighQuality,
findAllSkills,
benchmarkSkill,
type QualityScore,
type BenchmarkResult,
} from '@skillkit/core';
import { getSearchDirs } from '../helpers.js';
import {
colors,
symbols,
spinner,
success,
warn,
error,
header,
} from '../onboarding/index.js';
function formatScore(score: number): string {
if (score >= 80) return colors.success(`${score}`);
if (score >= 60) return colors.warning(`${score}`);
return colors.error(`${score}`);
}
function formatGrade(grade: string): string {
switch (grade) {
case 'A':
case 'B':
return colors.success(grade);
case 'C':
case 'D':
return colors.warning(grade);
default:
return colors.error(grade);
}
}
function printQualityReport(name: string, quality: QualityScore, verbose: boolean): void {
const grade = getQualityGrade(quality.overall);
const gradeDisplay = formatGrade(grade);
const scoreDisplay = formatScore(quality.overall);
console.log(`\n${colors.primary(name)}`);
console.log(` Grade: ${gradeDisplay} Score: ${scoreDisplay}/100`);
if (verbose) {
console.log('');
console.log(` ${colors.muted('Structure:')} ${formatScore(quality.structure.score)}/100`);
console.log(` ${quality.structure.hasMetadata ? colors.success(symbols.success) : colors.error(symbols.error)} Metadata`);
console.log(` ${quality.structure.hasDescription ? colors.success(symbols.success) : colors.error(symbols.error)} Description`);
console.log(` ${quality.structure.hasTriggers ? colors.success(symbols.success) : colors.error(symbols.error)} Trigger conditions`);
console.log(` ${quality.structure.hasExamples ? colors.success(symbols.success) : colors.error(symbols.error)} Code examples`);
console.log(` ${quality.structure.hasBoundaries ? colors.success(symbols.success) : colors.error(symbols.error)} Boundaries defined`);
console.log('');
console.log(` ${colors.muted('Clarity:')} ${formatScore(quality.clarity.score)}/100`);
console.log(` Lines: ${quality.clarity.lineCount}${quality.clarity.lineCount > 300 ? colors.warning(' (consider splitting)') : ''}`);
console.log(` Tokens: ${quality.clarity.tokenCount}${quality.clarity.tokenCount > 2000 ? colors.warning(' (high)') : ''}`);
console.log(` ${quality.clarity.hasHeaders ? colors.success(symbols.success) : colors.error(symbols.error)} Uses headers`);
console.log('');
console.log(` ${colors.muted('Specificity:')} ${formatScore(quality.specificity.score)}/100`);
console.log(` ${quality.specificity.hasConcreteCommands ? colors.success(symbols.success) : colors.error(symbols.error)} Concrete commands`);
console.log(` ${quality.specificity.hasFilePatterns ? colors.success(symbols.success) : colors.error(symbols.error)} File patterns`);
console.log(` ${quality.specificity.hasCodeExamples ? colors.success(symbols.success) : colors.error(symbols.error)} Multiple code examples`);
if (quality.specificity.vagueTermCount > 0) {
console.log(` ${colors.warning(symbols.warning)} ${quality.specificity.vagueTermCount} vague term(s)`);
}
console.log('');
console.log(` ${colors.muted('Advanced:')} ${formatScore(quality.advanced.score)}/100`);
if (quality.advanced.deprecatedPatterns.length > 0) {
console.log(` ${colors.warning(symbols.warning)} ${quality.advanced.deprecatedPatterns.length} deprecated pattern(s)`);
for (const pattern of quality.advanced.deprecatedPatterns) {
console.log(` ${colors.muted(symbols.bullet)} ${pattern}`);
}
}
if (quality.advanced.securityIssues.length > 0) {
console.log(` ${colors.error(symbols.error)} ${quality.advanced.securityIssues.length} security issue(s)`);
for (const issue of quality.advanced.securityIssues) {
console.log(` ${colors.muted(symbols.bullet)} ${issue}`);
}
}
if (quality.advanced.conflictingInstructions.length > 0) {
console.log(` ${colors.warning(symbols.warning)} ${quality.advanced.conflictingInstructions.length} conflicting instruction(s)`);
}
console.log(` Completeness: ${quality.advanced.completeness.score}/100`);
console.log(` Example coverage: ${quality.advanced.completeness.exampleCoverage}%`);
if (quality.advanced.completeness.hasTodos) {
console.log(` ${colors.warning(symbols.warning)} ${quality.advanced.completeness.todoCount} TODO/FIXME comment(s)`);
}
}
if (quality.warnings.length > 0) {
console.log('');
console.log(` ${colors.warning('Warnings:')}`);
for (const w of quality.warnings) {
console.log(` ${colors.warning(symbols.warning)} ${w}`);
}
}
if (quality.suggestions.length > 0 && verbose) {
console.log('');
console.log(` ${colors.muted('Suggestions:')}`);
for (const s of quality.suggestions) {
console.log(` ${colors.muted(symbols.bullet)} ${s}`);
}
}
}
function printBenchmarkReport(benchmark: BenchmarkResult): void {
console.log('');
console.log(colors.bold('Benchmark Comparison'));
console.log('');
console.log(` ${colors.muted('Your Score:')} ${formatScore(benchmark.score)}/100 ${formatGrade(benchmark.grade)}`);
console.log(` ${colors.muted('Category Average:')} ${benchmark.categoryAvg}/100`);
console.log(` ${colors.muted('Top Skill Score:')} ${benchmark.topSkillScore}/100`);
console.log(` ${colors.muted('Percentile:')} ${benchmark.percentile}${getOrdinal(benchmark.percentile)}`);
if (benchmark.comparisonNotes.length > 0) {
console.log('');
console.log(` ${colors.muted('Comparison:')}`);
for (const note of benchmark.comparisonNotes) {
console.log(` ${colors.muted(symbols.bullet)} ${note}`);
}
}
if (benchmark.recommendations.length > 0) {
console.log('');
console.log(` ${colors.muted('To Improve:')}`);
for (const rec of benchmark.recommendations) {
console.log(` ${colors.info(symbols.info)} ${rec}`);
}
}
}
function getOrdinal(n: number): string {
const s = ['th', 'st', 'nd', 'rd'];
const v = n % 100;
return s[(v - 20) % 10] || s[v] || s[0];
}
export class ValidateCommand extends Command {
static override paths = [['validate'], ['v']];
static override paths = [['validate']];
static override usage = Command.Usage({
description: 'Validate skill(s) against the Agent Skills specification (agentskills.io)',
description: 'Validate skill format and quality',
details: `
Validates skills against the specification and evaluates quality.
Quality scores are based on structure, clarity, and specificity.
`,
examples: [
['Validate a skill directory', '$0 validate ./my-skill'],
['Validate all skills in a directory', '$0 validate ./skills --all'],
['Validate all installed skills', '$0 validate'],
['Validate specific skill', '$0 validate my-skill'],
['Validate skill file', '$0 validate ./path/to/SKILL.md'],
['Detailed quality report', '$0 validate --verbose'],
['Only show issues', '$0 validate --issues'],
['Quality check only', '$0 validate --quality'],
['JSON output', '$0 validate --json'],
],
});
skillPath = Option.String({ required: true });
targets = Option.Rest();
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed quality breakdown',
});
quality = Option.Boolean('--quality,-q', false, {
description: 'Only check quality (skip format validation)',
});
issues = Option.Boolean('--issues,-i', false, {
description: 'Only show skills with issues',
});
minScore = Option.String('--min-score,-m', {
description: 'Minimum acceptable score (default: 60)',
});
json = Option.Boolean('--json', false, {
description: 'Output as JSON',
});
all = Option.Boolean('--all,-a', false, {
description: 'Validate all skills in the directory',
description: 'Validate all skills in directory',
});
benchmark = Option.Boolean('--benchmark,-b', false, {
description: 'Compare skill against category leaders',
});
fix = Option.Boolean('--fix', false, {
description: 'Automatically fix common quality issues (runs fix command)',
});
async execute(): Promise<number> {
const targetPath = this.skillPath;
if (!existsSync(targetPath)) {
console.error(chalk.red(`Path does not exist: ${targetPath}`));
return 1;
if (this.fix) {
if (this.targets.length === 0) {
error('--fix requires at least one target');
console.log(colors.muted('Usage: skillkit validate --fix <skill-name>'));
return 1;
}
const { FixCommand } = await import('./fix.js');
const fixCmd = new FixCommand();
fixCmd.targets = this.targets;
fixCmd.yes = false;
return fixCmd.execute();
}
const skillPaths: string[] = [];
let minScore = 60;
if (this.minScore) {
const parsed = parseInt(this.minScore, 10);
if (Number.isNaN(parsed) || parsed < 0 || parsed > 100) {
if (!this.json) {
warn(`Invalid --min-score value "${this.minScore}", using default: 60`);
}
} else {
minScore = parsed;
}
}
const results: Array<{ name: string; quality: QualityScore | null; formatValid: boolean; formatErrors: string[]; path?: 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 (this.targets.length > 0) {
for (const target of this.targets) {
const resolved = resolve(target);
if (existsSync(resolved)) {
const isDirectory = statSync(resolved).isDirectory();
if (this.all) {
if (!isDirectory) {
if (!this.json) {
warn(`--all requires a directory, but "${target}" is a file`);
}
continue;
}
const entries = readdirSync(resolved, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const skillPath = join(resolved, entry.name);
const hasSkillMd = existsSync(join(skillPath, 'SKILL.md'));
const hasIndexMdc = existsSync(join(skillPath, 'index.mdc'));
const hasNamedMdc = existsSync(join(skillPath, `${entry.name}.mdc`));
if (hasSkillMd || hasIndexMdc || hasNamedMdc) {
const formatResult = this.quality ? { valid: true, errors: [] } : validateSkill(skillPath);
const quality = evaluateSkillDirectory(skillPath);
results.push({
name: entry.name,
quality,
formatValid: formatResult.valid,
formatErrors: formatResult.errors || [],
path: skillPath,
});
}
}
}
} else {
const isFile = resolved.endsWith('.md') || resolved.endsWith('.mdc');
const skillDir = isFile ? dirname(resolved) : resolved;
const formatResult = this.quality ? { valid: true, errors: [] } : validateSkill(skillDir);
const quality = isFile ? evaluateSkillFile(resolved) : evaluateSkillDirectory(resolved);
results.push({
name: basename(target),
quality,
formatValid: formatResult.valid,
formatErrors: formatResult.errors || [],
path: resolved,
});
}
} else {
const searchDirs = getSearchDirs();
const skills = findAllSkills(searchDirs);
const found = skills.find(s => s.name === target);
if (found) {
const formatResult = this.quality ? { valid: true, errors: [] } : validateSkill(found.path);
const quality = evaluateSkillDirectory(found.path);
results.push({
name: found.name,
quality,
formatValid: formatResult.valid,
formatErrors: formatResult.errors || [],
path: found.path,
});
} else {
if (!this.json) {
warn(`Skill not found: ${target}`);
}
}
}
}
if (skillPaths.length === 0) {
console.error(chalk.yellow('No skills found in directory'));
return 1;
}
} else {
skillPaths.push(targetPath);
}
const searchDirs = getSearchDirs();
const skills = findAllSkills(searchDirs);
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}`));
});
if (skills.length === 0) {
if (!this.json) {
warn('No installed skills found');
}
} else {
console.log(chalk.red(`✗ ${skillName}`));
result.errors.forEach(e => {
console.log(chalk.red(` • ${e}`));
return 0;
}
const s = spinner();
if (!this.json) {
s.start(`Evaluating ${skills.length} skill(s)...`);
}
for (const skill of skills) {
const formatResult = this.quality ? { valid: true, errors: [] } : validateSkill(skill.path);
const quality = evaluateSkillDirectory(skill.path);
results.push({
name: skill.name,
quality,
formatValid: formatResult.valid,
formatErrors: formatResult.errors || [],
path: skill.path,
});
hasErrors = true;
}
if (!this.json) {
s.stop(`Evaluated ${results.length} skill(s)`);
}
}
console.log();
if (hasErrors) {
console.log(chalk.red('Validation failed'));
console.log(chalk.dim('See https://agentskills.io/specification for the complete format'));
if (results.length === 0) {
if (!this.json) {
error('No skills to validate');
}
return 1;
}
console.log(chalk.green(`Validated ${skillPaths.length} skill(s) successfully`));
if (this.json) {
const output = results.map(r => {
const result: Record<string, unknown> = {
name: r.name,
path: r.path,
formatValid: r.formatValid,
formatErrors: r.formatErrors,
score: r.quality?.overall ?? null,
grade: r.quality ? getQualityGrade(r.quality.overall) : null,
highQuality: r.quality ? isHighQuality(r.quality) : false,
structure: r.quality?.structure ?? null,
clarity: r.quality?.clarity ?? null,
specificity: r.quality?.specificity ?? null,
advanced: r.quality?.advanced ?? null,
warnings: r.quality?.warnings ?? [],
suggestions: r.quality?.suggestions ?? [],
};
if (this.benchmark && r.quality) {
result.benchmark = benchmarkSkill(r.name, r.quality);
}
return result;
});
console.log(JSON.stringify(output, null, 2));
const hasFormatFailures = results.some(r => !r.formatValid);
const hasBelowThreshold = results.some(r => r.quality && r.quality.overall < minScore);
return hasFormatFailures || hasBelowThreshold ? 1 : 0;
}
header('Skill Validation Report');
let filteredResults = results;
if (this.issues) {
filteredResults = results.filter(r =>
!r.formatValid ||
(r.quality && r.quality.overall < minScore) ||
(r.quality && r.quality.warnings.length > 0)
);
}
filteredResults.sort((a, b) => (b.quality?.overall ?? 0) - (a.quality?.overall ?? 0));
for (const { name, quality, formatValid, formatErrors } of filteredResults) {
if (!formatValid) {
console.log(`\n${colors.error(symbols.error)} ${colors.primary(name)}`);
console.log(` ${colors.error('Format validation failed:')}`);
for (const err of formatErrors) {
console.log(` ${colors.error(symbols.bullet)} ${err}`);
}
}
if (quality) {
printQualityReport(name, quality, this.verbose);
if (this.benchmark) {
const benchmark = benchmarkSkill(name, quality);
printBenchmarkReport(benchmark);
}
}
}
console.log('');
const formatFailed = results.filter(r => !r.formatValid).length;
const withQuality = results.filter(r => r.quality !== null);
const highQuality = withQuality.filter(r => r.quality!.overall >= 80).length;
const passing = withQuality.filter(r => r.quality!.overall >= minScore).length;
const failing = withQuality.filter(r => r.quality!.overall < minScore).length;
console.log(colors.muted('Summary:'));
if (!this.quality) {
console.log(` ${formatFailed === 0 ? colors.success(symbols.success) : colors.error(symbols.error)} Format valid: ${results.length - formatFailed}/${results.length}`);
}
console.log(` ${colors.success(symbols.success)} High quality (80+): ${highQuality}`);
console.log(` ${colors.primary(symbols.bullet)} Passing (${minScore}+): ${passing}`);
if (failing > 0) {
console.log(` ${colors.error(symbols.error)} Below threshold: ${failing}`);
}
if (withQuality.length > 0) {
const avgScore = Math.round(withQuality.reduce((sum, r) => sum + r.quality!.overall, 0) / withQuality.length);
console.log(` ${colors.muted('Average score:')} ${formatScore(avgScore)}/100`);
}
if (formatFailed > 0 || failing > 0) {
console.log('');
if (formatFailed > 0) {
warn(`${formatFailed} skill(s) failed format validation`);
}
if (failing > 0) {
warn(`${failing} skill(s) below quality threshold`);
}
return 1;
}
console.log('');
success('All skills validated successfully');
return 0;
}
}
+239
View File
@@ -0,0 +1,239 @@
export {
AGENT_ICONS,
AGENT_NAMES,
symbols,
SPINNER_FRAMES,
colors,
formatAgent,
getAgentIcon,
formatAgentIconsInline,
progressBar,
formatScore,
formatQualityBadge,
formatQualityBadgeCompact,
getQualityGradeFromScore,
} from './theme.js';
export {
getLogo,
getFullLogo,
getCompactLogo,
getMinimalLogo,
getHeader,
getDivider,
} from './logo.js';
export * as prompts from './prompts.js';
export {
isCancel,
intro,
outro,
cancel,
note,
log,
step,
success,
warn,
error,
spinner,
text,
password,
confirm,
select,
agentMultiselect,
quickAgentSelect,
skillMultiselect,
groupMultiselect,
stepTrail,
selectInstallMethod,
tasks,
summaryBox,
type SkillOption,
} from './prompts.js';
export {
showInstallSummary,
showNextSteps,
showAgentSummary,
showProjectSummary,
showSyncSummary,
showSkillList,
showMarketplaceInfo,
type InstallResult,
type InstallSummary,
} from './summary.js';
export {
loadPreferences,
savePreferences,
isOnboardingComplete,
completeOnboarding,
saveLastAgents,
getLastAgents,
saveInstallMethod,
getInstallMethod,
getPreferencesDir,
getPreferencesPath,
type UserPreferences,
} from './preferences.js';
import { getLogo, getHeader } from './logo.js';
import * as prompts from './prompts.js';
import { colors, formatAgent } from './theme.js';
import { showNextSteps } from './summary.js';
import {
completeOnboarding,
saveLastAgents,
getLastAgents,
} from './preferences.js';
let VERSION = '1.7.6';
let AGENT_COUNT = 17;
export function setVersion(version: string): void {
VERSION = version;
}
export function setAgentCount(count: number): void {
AGENT_COUNT = count;
}
export function welcome(): void {
console.log(getLogo(VERSION, AGENT_COUNT));
}
export function header(title: string): void {
console.log(getHeader(title));
}
export async function runOnboarding(detectedAgents: string[]): Promise<{
selectedAgents: string[];
cancelled: boolean;
}> {
welcome();
if (detectedAgents.length === 0) {
prompts.warn('No agents detected');
completeOnboarding();
return { selectedAgents: [], cancelled: false };
}
prompts.log(`Detected ${detectedAgents.length} agent${detectedAgents.length !== 1 ? 's' : ''}: ${detectedAgents.map(formatAgent).join(', ')}`);
const agentResult = await prompts.agentMultiselect({
message: 'Select agents to configure',
agents: detectedAgents,
initialValues: detectedAgents,
});
if (prompts.isCancel(agentResult)) {
prompts.cancel('Setup cancelled');
return { selectedAgents: [], cancelled: true };
}
saveLastAgents(agentResult as string[]);
completeOnboarding();
prompts.success(`Configured ${agentResult.length} agent${agentResult.length !== 1 ? 's' : ''}`);
return { selectedAgents: agentResult as string[], cancelled: false };
}
export interface InstallFlowOptions {
source: string;
discoveredSkills: Array<{ name: string; path: string }>;
detectedAgents: string[];
showLogo?: boolean;
}
export interface InstallFlowResult {
selectedSkills: string[];
selectedAgents: string[];
installMethod: 'symlink' | 'copy';
cancelled: boolean;
}
export async function runInstallFlow(options: InstallFlowOptions): Promise<InstallFlowResult> {
const { source, discoveredSkills, detectedAgents, showLogo = true } = options;
if (showLogo) {
welcome();
}
prompts.step(`Source: ${colors.cyan(source)}`);
prompts.step(`Found ${discoveredSkills.length} skill${discoveredSkills.length !== 1 ? 's' : ''}`);
const skillNames = discoveredSkills.map(s => s.name);
const skillResult = await prompts.skillMultiselect({
message: 'Select skills to install',
skills: discoveredSkills.map(s => ({ name: s.name })),
initialValues: skillNames,
});
if (prompts.isCancel(skillResult)) {
prompts.cancel('Installation cancelled');
return { selectedSkills: [], selectedAgents: [], installMethod: 'symlink', cancelled: true };
}
if (detectedAgents.length > 1) {
prompts.step(`Detected ${detectedAgents.length} agents`);
}
const lastAgents = getLastAgents();
const initialAgents = lastAgents.length > 0 ? lastAgents : detectedAgents;
const agentResult = await prompts.agentMultiselect({
message: 'Install to which agents?',
agents: detectedAgents,
initialValues: initialAgents.filter(a => detectedAgents.includes(a)),
});
if (prompts.isCancel(agentResult)) {
prompts.cancel('Installation cancelled');
return { selectedSkills: skillResult as string[], selectedAgents: [], installMethod: 'symlink', cancelled: true };
}
saveLastAgents(agentResult as string[]);
const methodResult = await prompts.selectInstallMethod({
message: 'Installation method',
});
if (prompts.isCancel(methodResult)) {
prompts.cancel('Installation cancelled');
return {
selectedSkills: skillResult as string[],
selectedAgents: agentResult as string[],
installMethod: 'symlink',
cancelled: true,
};
}
return {
selectedSkills: skillResult as string[],
selectedAgents: agentResult as string[],
installMethod: methodResult as 'symlink' | 'copy',
cancelled: false,
};
}
export function showCompletion(options: {
skillNames: string[];
agentTypes: string[];
action?: 'install' | 'sync' | 'init';
}): void {
const action = options.action || 'install';
const messages: Record<string, string> = {
install: 'Installation complete!',
sync: 'Sync complete!',
init: 'Initialization complete!',
};
prompts.outro(messages[action] || 'Done!');
showNextSteps(options);
}
export function handleCancel(message?: string): void {
prompts.cancel(message || 'Operation cancelled');
process.exit(0);
}
+86
View File
@@ -0,0 +1,86 @@
import pc from 'picocolors';
import { symbols } from './theme.js';
function getTerminalWidth(): number {
return process.stdout.columns || 80;
}
export function getFullLogo(version?: string, agentCount?: number): string {
const lines = [
'',
pc.dim(' ') + pc.white('███████╗') + pc.gray('██╗ ██╗') + pc.dim('██╗') + pc.gray('██╗ ') + pc.dim('██╗ ') + pc.white('██╗ ██╗') + pc.gray('██╗') + pc.dim('████████╗'),
pc.dim(' ') + pc.white('██╔════╝') + pc.gray('██║ ██╔╝') + pc.dim('██║') + pc.gray('██║ ') + pc.dim('██║ ') + pc.white('██║ ██╔╝') + pc.gray('██║') + pc.dim('╚══██╔══╝'),
pc.dim(' ') + pc.white('███████╗') + pc.gray('█████╔╝ ') + pc.dim('██║') + pc.gray('██║ ') + pc.dim('██║ ') + pc.white('█████╔╝ ') + pc.gray('██║') + pc.dim(' ██║ '),
pc.dim(' ') + pc.white('╚════██║') + pc.gray('██╔═██╗ ') + pc.dim('██║') + pc.gray('██║ ') + pc.dim('██║ ') + pc.white('██╔═██╗ ') + pc.gray('██║') + pc.dim(' ██║ '),
pc.dim(' ') + pc.white('███████║') + pc.gray('██║ ██╗') + pc.dim('██║') + pc.gray('███████╗') + pc.dim('███████╗') + pc.white('██║ ██╗') + pc.gray('██║') + pc.dim(' ██║ '),
pc.dim(' ') + pc.white('╚══════╝') + pc.gray('╚═╝ ╚═╝') + pc.dim('╚═╝') + pc.gray('╚══════╝') + pc.dim('╚══════╝') + pc.white('╚═╝ ╚═╝') + pc.gray('╚═╝') + pc.dim(' ╚═╝ '),
'',
];
if (version || agentCount) {
const info: string[] = [];
if (version) info.push(`v${version}`);
if (agentCount) info.push(`${agentCount} agents`);
lines.push(pc.dim(' ') + pc.dim(info.join(' │ ')));
lines.push('');
}
return lines.join('\n');
}
export function getCompactLogo(version?: string, agentCount?: number): string {
const frame = `${symbols.frameCorner}${symbols.frameLine.repeat(18)}${symbols.frameCorner}`;
const lines = [
'',
pc.dim(` ${frame}`),
pc.dim(' ') + pc.white(' S K I L L K I T '),
pc.dim(` ${frame}`),
];
if (version || agentCount) {
const info: string[] = [];
if (version) info.push(`v${version}`);
if (agentCount) info.push(`${agentCount} agents`);
lines.push(pc.dim(' ') + pc.dim(info.join(' │ ')));
}
lines.push('');
return lines.join('\n');
}
export function getMinimalLogo(version?: string): string {
const lines = [
'',
pc.dim(`${symbols.diamondOpen}───`) + pc.white('SKILLKIT') + pc.dim(`───${symbols.diamondOpen}`),
];
if (version) {
lines.push(pc.dim(` v${version}`));
}
lines.push('');
return lines.join('\n');
}
export function getLogo(version?: string, agentCount?: number): string {
const width = getTerminalWidth();
if (width >= 70) {
return getFullLogo(version, agentCount);
}
if (width >= 50) {
return getCompactLogo(version, agentCount);
}
return getMinimalLogo(version);
}
export function getHeader(title: string): string {
return `\n${pc.dim(symbols.diamondOpen)} ${pc.white(pc.bold('SkillKit'))} ${pc.dim('│')} ${pc.cyan(title)}\n`;
}
export function getDivider(width?: number): string {
const fallback = Math.min(getTerminalWidth() - 4, 60);
const w = Math.max(1, width ?? fallback);
return pc.dim(symbols.horizontalLine.repeat(w));
}
@@ -0,0 +1,97 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
const SKILLKIT_DIR = join(homedir(), '.skillkit');
const PREFERENCES_FILE = join(SKILLKIT_DIR, 'preferences.json');
export interface UserPreferences {
onboardingComplete: boolean;
lastSelectedAgents: string[];
defaultInstallMethod: 'symlink' | 'copy';
outputFormat: 'pretty' | 'json';
lastAccessed: string;
version?: string;
}
const DEFAULT_PREFERENCES: UserPreferences = {
onboardingComplete: false,
lastSelectedAgents: [],
defaultInstallMethod: 'symlink',
outputFormat: 'pretty',
lastAccessed: new Date().toISOString(),
};
function ensureDir(): void {
if (!existsSync(SKILLKIT_DIR)) {
mkdirSync(SKILLKIT_DIR, { recursive: true });
}
}
export function loadPreferences(): UserPreferences {
try {
if (!existsSync(PREFERENCES_FILE)) {
return { ...DEFAULT_PREFERENCES };
}
const content = readFileSync(PREFERENCES_FILE, 'utf-8');
const data = JSON.parse(content);
return {
...DEFAULT_PREFERENCES,
...data,
lastAccessed: new Date().toISOString(),
};
} catch {
return { ...DEFAULT_PREFERENCES };
}
}
export function savePreferences(prefs: Partial<UserPreferences>): void {
try {
ensureDir();
const current = loadPreferences();
const updated: UserPreferences = {
...current,
...prefs,
lastAccessed: new Date().toISOString(),
};
writeFileSync(PREFERENCES_FILE, JSON.stringify(updated, null, 2), 'utf-8');
} catch {
// Silently fail - preferences are not critical
}
}
export function isOnboardingComplete(): boolean {
return loadPreferences().onboardingComplete;
}
export function completeOnboarding(): void {
savePreferences({ onboardingComplete: true });
}
export function saveLastAgents(agents: string[]): void {
savePreferences({ lastSelectedAgents: agents });
}
export function getLastAgents(): string[] {
return loadPreferences().lastSelectedAgents;
}
export function saveInstallMethod(method: 'symlink' | 'copy'): void {
savePreferences({ defaultInstallMethod: method });
}
export function getInstallMethod(): 'symlink' | 'copy' {
return loadPreferences().defaultInstallMethod;
}
export function getPreferencesDir(): string {
return SKILLKIT_DIR;
}
export function getPreferencesPath(): string {
return PREFERENCES_FILE;
}
+309
View File
@@ -0,0 +1,309 @@
import * as clack from '@clack/prompts';
import pc from 'picocolors';
import { symbols, colors, formatAgent, formatScore } from './theme.js';
export function isCancel(value: unknown): value is symbol {
return clack.isCancel(value);
}
export function intro(message?: string): void {
clack.intro(message ? pc.bold(message) : undefined);
}
export function outro(message: string): void {
clack.outro(pc.green(message));
}
export function cancel(message: string = 'Operation cancelled'): void {
clack.cancel(pc.yellow(message));
}
export function note(message: string, title?: string): void {
clack.note(message, title);
}
export function log(message: string): void {
clack.log.info(message);
}
export function step(message: string): void {
clack.log.step(message);
}
export function success(message: string): void {
clack.log.success(pc.green(message));
}
export function warn(message: string): void {
clack.log.warn(pc.yellow(message));
}
export function error(message: string): void {
clack.log.error(pc.red(message));
}
export function spinner(): ReturnType<typeof clack.spinner> {
return clack.spinner();
}
export async function text(options: {
message: string;
placeholder?: string;
defaultValue?: string;
validate?: (value: string) => string | Error | undefined;
}): Promise<string | symbol> {
return clack.text({
message: options.message,
placeholder: options.placeholder,
defaultValue: options.defaultValue,
validate: options.validate,
});
}
export async function password(options: {
message: string;
validate?: (value: string) => string | Error | undefined;
}): Promise<string | symbol> {
return clack.password({
message: options.message,
validate: options.validate,
});
}
export async function confirm(options: {
message: string;
initialValue?: boolean;
}): Promise<boolean | symbol> {
return clack.confirm({
message: options.message,
initialValue: options.initialValue,
});
}
export async function select<T extends string>(options: {
message: string;
options: Array<{ value: T; label: string; hint?: string }>;
initialValue?: T;
}): Promise<T | symbol> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return clack.select({
message: options.message,
options: options.options as any,
initialValue: options.initialValue,
});
}
export async function agentMultiselect(options: {
message: string;
agents: string[];
initialValues?: string[];
required?: boolean;
}): Promise<string[] | symbol> {
const agentOptions = options.agents.map((agent) => ({
value: agent,
label: formatAgent(agent),
hint: undefined as string | undefined,
}));
return clack.multiselect({
message: options.message,
options: agentOptions,
initialValues: options.initialValues,
required: options.required ?? true,
});
}
export async function quickAgentSelect(options: {
message?: string;
agents: string[];
lastSelected?: string[];
}): Promise<{ agents: string[]; method: 'last' | 'all' | 'select' } | symbol> {
const { agents, lastSelected = [] } = options;
const hasLast = lastSelected.length > 0 && lastSelected.some(a => agents.includes(a));
const selectOptions: Array<{ value: string; label: string; hint?: string }> = [];
if (hasLast) {
const validLast = lastSelected.filter(a => agents.includes(a));
const agentList = validLast.slice(0, 3).map(formatAgent).join(', ');
const more = validLast.length > 3 ? ` +${validLast.length - 3}` : '';
selectOptions.push({
value: 'last',
label: `Same as last time (Recommended)`,
hint: `${agentList}${more}`,
});
}
selectOptions.push({
value: 'all',
label: 'All detected agents',
hint: `${agents.length} agent${agents.length !== 1 ? 's' : ''}`,
});
selectOptions.push({
value: 'select',
label: 'Select specific agents',
hint: 'Choose manually',
});
const result = await clack.select({
message: options.message || 'Install to',
options: selectOptions,
});
if (clack.isCancel(result)) {
return result;
}
const method = result as 'last' | 'all' | 'select';
if (method === 'last') {
return { agents: lastSelected.filter(a => agents.includes(a)), method };
}
if (method === 'all') {
return { agents, method };
}
const selected = await agentMultiselect({
message: 'Select agents',
agents,
initialValues: lastSelected.length > 0 ? lastSelected : agents,
});
if (clack.isCancel(selected)) {
return selected;
}
return { agents: selected as string[], method };
}
export interface SkillOption {
name: string;
description?: string;
score?: number;
source?: string;
}
export async function skillMultiselect(options: {
message: string;
skills: SkillOption[];
initialValues?: string[];
required?: boolean;
}): Promise<string[] | symbol> {
const skillOptions = options.skills.map((skill) => {
const label = skill.name;
let hint: string | undefined;
if (skill.score !== undefined) {
hint = formatScore(skill.score);
} else if (skill.source) {
hint = pc.dim(skill.source);
}
return { value: skill.name, label, hint };
});
return clack.multiselect({
message: options.message,
options: skillOptions,
initialValues: options.initialValues,
required: options.required ?? false,
});
}
export async function groupMultiselect<T extends string>(options: {
message: string;
options: Record<string, Array<{ value: T; label: string; hint?: string }>>;
required?: boolean;
}): Promise<T[] | symbol> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return clack.groupMultiselect({
message: options.message,
options: options.options as any,
required: options.required,
});
}
export function stepTrail(steps: Array<{ label: string; status: 'pending' | 'active' | 'complete' }>): string {
const lines: string[] = [];
for (let i = 0; i < steps.length; i++) {
const currentStep = steps[i];
const isLast = i === steps.length - 1;
let icon: string;
let labelColor: (text: string) => string;
switch (currentStep.status) {
case 'complete':
icon = colors.success(symbols.stepComplete);
labelColor = colors.muted;
break;
case 'active':
icon = colors.accent(symbols.stepActive);
labelColor = colors.primary;
break;
case 'pending':
default:
icon = colors.muted(symbols.stepPending);
labelColor = colors.muted;
break;
}
lines.push(`${icon} ${labelColor(currentStep.label)}`);
if (!isLast) {
lines.push(`${colors.muted(symbols.stepLine)}`);
}
}
return lines.join('\n');
}
export async function selectInstallMethod(options: {
message?: string;
}): Promise<'symlink' | 'copy' | symbol> {
return clack.select({
message: options.message || 'Installation method',
options: [
{
value: 'symlink' as const,
label: 'Symlink (Recommended)',
hint: 'Single source, auto-updates',
},
{
value: 'copy' as const,
label: 'Copy to all agents',
hint: 'Independent copies',
},
],
});
}
export async function tasks(
taskList: Array<{
title: string;
task: (message: (msg: string) => void) => Promise<string | void>;
enabled?: boolean;
}>
): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return clack.tasks(taskList.filter((t) => t.enabled !== false) as any);
}
export function summaryBox(options: {
title: string;
items: Array<{ label: string; value: string; icon?: string }>;
}): void {
const lines: string[] = [];
for (const item of options.items) {
const icon = item.icon ? `${item.icon} ` : '';
lines.push(` ${icon}${colors.primary(item.label)}`);
lines.push(` ${colors.muted(item.value)}`);
}
clack.note(lines.join('\n'), options.title);
}
+176
View File
@@ -0,0 +1,176 @@
import * as prompts from './prompts.js';
import { symbols, colors, formatAgent, getAgentIcon, formatAgentIconsInline } from './theme.js';
export interface InstallResult {
skillName: string;
method: 'symlink' | 'copy';
agents: string[];
path: string;
}
export interface InstallSummary {
totalSkills: number;
totalAgents: number;
results: InstallResult[];
source?: string;
}
export function showInstallSummary(summary: InstallSummary): void {
const title = `Installed ${summary.totalSkills} skill${summary.totalSkills !== 1 ? 's' : ''} to ${summary.totalAgents} agent${summary.totalAgents !== 1 ? 's' : ''}`;
const lines: string[] = [];
for (const result of summary.results) {
lines.push(`${colors.success(symbols.success)} ${colors.primary(result.skillName)}`);
const agentDisplay = result.agents.length <= 3
? result.agents.map(formatAgent).join(', ')
: `${formatAgentIconsInline(result.agents.slice(0, 3))} +${result.agents.length - 3} more`;
lines.push(` ${result.method} ${symbols.arrowRight} ${agentDisplay}`);
lines.push('');
}
prompts.note(lines.join('\n').trim(), title);
}
export function showNextSteps(options: {
skillNames: string[];
agentTypes: string[];
syncNeeded?: boolean;
}): void {
const lines: string[] = [];
lines.push(`${colors.muted('1.')} Run ${colors.cyan('skillkit sync')} to update agent configs`);
lines.push(`${colors.muted('2.')} Use ${colors.cyan(`skillkit read ${options.skillNames[0] || '<skill>'}`)} to view skill docs`);
if (options.agentTypes.includes('claude-code')) {
lines.push(`${colors.muted('3.')} Skills are available via ${colors.cyan('/@')} in Claude Code`);
} else if (options.agentTypes.includes('cursor')) {
lines.push(`${colors.muted('3.')} Skills are available in Cursor rules`);
}
console.log('');
console.log(colors.dim('Next steps:'));
console.log(lines.map(l => ` ${l}`).join('\n'));
console.log('');
}
export function showAgentSummary(agents: string[]): void {
console.log('');
console.log(colors.dim('Detected agents:'));
const iconLine = agents.map(a => `${getAgentIcon(a)} ${colors.muted(a)}`).join(' ');
console.log(` ${iconLine}`);
console.log('');
}
export function showProjectSummary(profile: {
name: string;
type?: string;
languages: string[];
frameworks: string[];
}): void {
const lines: string[] = [];
lines.push(`${colors.primary('Project:')} ${profile.name}`);
if (profile.type) {
lines.push(`${colors.primary('Type:')} ${profile.type}`);
}
if (profile.languages.length > 0) {
lines.push(`${colors.primary('Languages:')} ${profile.languages.join(', ')}`);
}
if (profile.frameworks.length > 0) {
lines.push(`${colors.primary('Frameworks:')} ${profile.frameworks.join(', ')}`);
}
prompts.note(lines.join('\n'), 'Project Analysis');
}
export function showSyncSummary(options: {
skillCount: number;
agentType: string;
configPath: string;
}): void {
const lines: string[] = [];
lines.push(`${colors.success(symbols.success)} Synced ${options.skillCount} skill${options.skillCount !== 1 ? 's' : ''}`);
lines.push(` Agent: ${formatAgent(options.agentType)}`);
lines.push(` Config: ${colors.muted(options.configPath)}`);
console.log('');
console.log(lines.join('\n'));
console.log('');
}
export function showSkillList(skills: Array<{
name: string;
description?: string;
score?: number;
source?: string;
installed?: boolean;
}>): void {
console.log('');
for (const skill of skills) {
let line = '';
if (skill.installed) {
line += colors.success(symbols.success) + ' ';
} else {
line += colors.muted(symbols.stepPending) + ' ';
}
line += colors.primary(skill.name);
if (skill.score !== undefined) {
let scoreColor: (text: string) => string;
if (skill.score >= 70) {
scoreColor = colors.success;
} else if (skill.score >= 50) {
scoreColor = colors.warning;
} else {
scoreColor = colors.muted;
}
line += ` ${scoreColor(`${skill.score}%`)}`;
}
console.log(line);
if (skill.description) {
console.log(` ${colors.muted(truncate(skill.description, 60))}`);
}
if (skill.source) {
console.log(` ${colors.dim(`Source: ${skill.source}`)}`);
}
}
console.log('');
}
export function showMarketplaceInfo(options: {
totalSkills: number;
sourceCount: number;
lastUpdated?: string;
}): void {
const lines: string[] = [];
lines.push(`Total skills: ${colors.cyan(String(options.totalSkills))}`);
lines.push(`Sources: ${colors.cyan(String(options.sourceCount))}`);
if (options.lastUpdated) {
const date = new Date(options.lastUpdated).toLocaleDateString();
lines.push(`Updated: ${colors.muted(date)}`);
}
prompts.note(lines.join('\n'), 'Skill Marketplace');
}
function truncate(str: string, maxLen: number): string {
if (str.length <= maxLen) return str;
return str.slice(0, maxLen - 3) + '...';
}
+156
View File
@@ -0,0 +1,156 @@
import pc from 'picocolors';
export const AGENT_ICONS: Record<string, string> = {
'claude-code': '\u27c1',
'cursor': '\u25eb',
'codex': '\u25ce',
'gemini-cli': '\u2726',
'opencode': '\u2b21',
'github-copilot': '\u25c8',
'windsurf': '\u224b',
'droid': '\u25a3',
'goose': '\u25c7',
'amp': '\u25b3',
'kilo': '\u25c9',
'kiro-cli': '\u2b22',
'roo': '\u2299',
'trae': '\u25c6',
'antigravity': '\u229b',
'clawdbot': '\u27d0',
'universal': '\u25cf',
};
export const AGENT_NAMES: Record<string, string> = {
'claude-code': 'Claude Code',
'cursor': 'Cursor',
'codex': 'Codex CLI',
'gemini-cli': 'Gemini CLI',
'opencode': 'OpenCode',
'github-copilot': 'Copilot',
'windsurf': 'Windsurf',
'droid': 'Droid',
'goose': 'Goose',
'amp': 'Amp',
'kilo': 'Kilo Code',
'kiro-cli': 'Kiro',
'roo': 'Roo Code',
'trae': 'Trae',
'antigravity': 'Antigravity',
'clawdbot': 'Clawdbot',
'universal': 'Universal',
};
export const symbols = {
stepPending: '\u25cb',
stepActive: '\u25cf',
stepComplete: '\u25cf',
stepLine: '\u2502',
selected: '\u25cf',
unselected: '\u25cb',
pointer: '\u25b8',
bullet: '\u25cf',
progressFull: '\u2588',
progressEmpty: '\u2591',
success: '\u2713',
error: '\u2717',
warning: '\u26a0',
info: '\u2139',
arrowRight: '\u2192',
arrowLeft: '\u2190',
arrowUp: '\u2191',
arrowDown: '\u2193',
diamondOpen: '\u25c7',
diamondFilled: '\u25c6',
horizontalLine: '\u2500',
verticalLine: '\u2502',
frameCorner: '\u25c7',
frameLine: '\u2500',
};
export const SPINNER_FRAMES = [
'\u280b',
'\u2819',
'\u2839',
'\u2838',
'\u283c',
'\u2834',
'\u2826',
'\u2827',
'\u2807',
'\u280f',
];
export const colors = {
accent: (text: string) => pc.green(text),
accentBright: (text: string) => pc.bold(pc.green(text)),
primary: (text: string) => pc.white(text),
secondary: (text: string) => pc.gray(text),
muted: (text: string) => pc.dim(text),
success: (text: string) => pc.green(text),
error: (text: string) => pc.red(text),
warning: (text: string) => pc.yellow(text),
info: (text: string) => pc.blue(text),
bold: (text: string) => pc.bold(text),
dim: (text: string) => pc.dim(text),
underline: (text: string) => pc.underline(text),
cyan: (text: string) => pc.cyan(text),
magenta: (text: string) => pc.magenta(text),
};
export function formatAgent(agentType: string): string {
const icon = AGENT_ICONS[agentType] || symbols.stepActive;
const name = AGENT_NAMES[agentType] || agentType;
return `${icon} ${name}`;
}
export function getAgentIcon(agentType: string): string {
return AGENT_ICONS[agentType] || symbols.stepActive;
}
export function formatAgentIconsInline(agents: string[]): string {
return agents.map(a => getAgentIcon(a)).join(' ');
}
export function progressBar(value: number, total: number, width: number = 6): string {
if (width <= 0 || total <= 0) return '';
const clampedValue = Math.min(Math.max(value, 0), total);
const filled = Math.round((clampedValue / total) * width);
const safeFilled = Math.min(Math.max(filled, 0), width);
const empty = width - safeFilled;
return symbols.progressFull.repeat(safeFilled) + symbols.progressEmpty.repeat(empty);
}
export function formatScore(score: number): string {
const bar = progressBar(score, 100, 6);
let scoreColor: (text: string) => string;
if (score >= 70) {
scoreColor = colors.success;
} else if (score >= 50) {
scoreColor = colors.warning;
} else {
scoreColor = colors.muted;
}
return `${scoreColor(`${score}%`)} ${colors.dim(bar)}`;
}
export function getQualityGradeFromScore(score: number): string {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
if (score >= 60) return 'D';
return 'F';
}
export function formatQualityBadge(score: number): string {
const grade = getQualityGradeFromScore(score);
if (score >= 80) return colors.success(`[${grade}]`);
if (score >= 60) return colors.warning(`[${grade}]`);
return colors.error(`[${grade}]`);
}
export function formatQualityBadgeCompact(score: number): string {
const grade = getQualityGradeFromScore(score);
if (score >= 80) return colors.success(grade);
if (score >= 60) return colors.warning(grade);
return colors.error(grade);
}
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/core",
"version": "1.6.4",
"version": "1.7.6",
"description": "Core functionality for SkillKit - skill discovery, parsing, and translation",
"type": "module",
"main": "./dist/index.js",
@@ -45,7 +45,6 @@
"test": "vitest run"
},
"dependencies": {
"@types/minimatch": "^6.0.0",
"minimatch": "^10.1.1",
"yaml": "^2.6.1",
"zod": "^3.24.1"
+3 -1
View File
@@ -73,5 +73,7 @@ export * from './audit/index.js';
// Custom Agents Support (Phase 19)
export * from './agents/index.js';
// Skill Translator (Phase 20 - Cross-Agent Skill Translation)
export * from './skill-translator.js';
export * from './manifest/index.js';
export * from './quality/index.js';
+206
View File
@@ -0,0 +1,206 @@
import { readFileSync, writeFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
export interface SkillEntry {
source: string;
skills?: string[];
agents?: string[];
enabled?: boolean;
}
export interface SkillsManifest {
version: number;
skills: SkillEntry[];
agents?: string[];
installMethod?: 'symlink' | 'copy';
updatedAt?: string;
}
const MANIFEST_FILENAMES = ['.skills', '.skills.yaml', '.skills.yml', 'skills.yaml'];
export function findManifestPath(startDir: string = process.cwd()): string | null {
let dir = startDir;
while (dir !== dirname(dir)) {
for (const filename of MANIFEST_FILENAMES) {
const manifestPath = join(dir, filename);
if (existsSync(manifestPath)) {
return manifestPath;
}
}
dir = dirname(dir);
}
return null;
}
export function loadManifest(manifestPath?: string): SkillsManifest | null {
const path = manifestPath || findManifestPath();
if (!path || !existsSync(path)) {
return null;
}
try {
const content = readFileSync(path, 'utf-8');
const parsed = parseYaml(content) as SkillsManifest;
if (!parsed || typeof parsed !== 'object') {
return null;
}
return {
version: parsed.version || 1,
skills: normalizeSkills(parsed.skills || []),
agents: parsed.agents,
installMethod: parsed.installMethod,
updatedAt: parsed.updatedAt,
};
} catch {
return null;
}
}
function normalizeSkills(skills: unknown[]): SkillEntry[] {
return skills.map(skill => {
if (typeof skill === 'string') {
const parts = skill.split('/');
if (parts.length >= 3) {
return {
source: `${parts[0]}/${parts[1]}`,
skills: [parts.slice(2).join('/')],
enabled: true,
};
}
return { source: skill, enabled: true };
}
if (typeof skill === 'object' && skill !== null) {
const entry = skill as Record<string, unknown>;
return {
source: String(entry.source || ''),
skills: entry.skills as string[] | undefined,
agents: entry.agents as string[] | undefined,
enabled: entry.enabled !== false,
};
}
return { source: '', enabled: false };
}).filter(s => s.source);
}
export function saveManifest(manifest: SkillsManifest, manifestPath?: string): void {
const path = manifestPath || join(process.cwd(), '.skills');
const content = stringifyYaml({
version: manifest.version || 1,
skills: manifest.skills.map(s => {
if (!s.skills && !s.agents && s.enabled !== false) {
return s.source;
}
return s;
}),
...(manifest.agents && { agents: manifest.agents }),
...(manifest.installMethod && { installMethod: manifest.installMethod }),
updatedAt: new Date().toISOString(),
});
writeFileSync(path, content, 'utf-8');
}
export function addToManifest(
source: string,
options?: { skills?: string[]; agents?: string[] },
manifestPath?: string
): SkillsManifest {
const existing = loadManifest(manifestPath) || {
version: 1,
skills: [],
};
const existingIndex = existing.skills.findIndex(s => s.source === source);
if (existingIndex >= 0) {
existing.skills[existingIndex] = {
...existing.skills[existingIndex],
...options,
enabled: true,
};
} else {
existing.skills.push({
source,
...options,
enabled: true,
});
}
saveManifest(existing, manifestPath);
return existing;
}
export function removeFromManifest(source: string, manifestPath?: string): SkillsManifest | null {
const existing = loadManifest(manifestPath);
if (!existing) {
return null;
}
existing.skills = existing.skills.filter(s => s.source !== source);
saveManifest(existing, manifestPath);
return existing;
}
export function initManifest(options?: {
agents?: string[];
installMethod?: 'symlink' | 'copy';
}, manifestPath?: string): SkillsManifest {
const manifest: SkillsManifest = {
version: 1,
skills: [],
...options,
updatedAt: new Date().toISOString(),
};
saveManifest(manifest, manifestPath);
return manifest;
}
export function generateManifestFromInstalled(
installedSkills: Array<{ name: string; source: string; agents?: string[] }>
): SkillsManifest {
const skillsBySource = new Map<string, { skills: string[]; agents: Set<string> }>();
for (const skill of installedSkills) {
if (!skill.source) continue;
const existing = skillsBySource.get(skill.source);
if (existing) {
existing.skills.push(skill.name);
if (skill.agents) {
skill.agents.forEach(a => existing.agents.add(a));
}
} else {
skillsBySource.set(skill.source, {
skills: [skill.name],
agents: new Set(skill.agents || []),
});
}
}
const skills: SkillEntry[] = [];
for (const [source, data] of skillsBySource) {
skills.push({
source,
skills: data.skills.length > 0 ? data.skills : undefined,
agents: data.agents.size > 0 ? Array.from(data.agents) : undefined,
enabled: true,
});
}
return {
version: 1,
skills,
updatedAt: new Date().toISOString(),
};
}
@@ -0,0 +1,99 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "SkillKit Marketplace",
"description": "Schema for SkillKit marketplace skills index",
"type": "object",
"required": ["version", "skills"],
"properties": {
"version": {
"type": "integer",
"description": "Schema version number"
},
"updatedAt": {
"type": "string",
"format": "date",
"description": "Last update date (YYYY-MM-DD)"
},
"skills": {
"type": "array",
"description": "List of skills in the marketplace",
"items": {
"$ref": "#/definitions/Skill"
}
}
},
"definitions": {
"Skill": {
"type": "object",
"required": ["id", "name", "source", "tags"],
"properties": {
"id": {
"type": "string",
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+/[a-zA-Z0-9_-]+$",
"description": "Unique identifier: owner/repo/skill-name"
},
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100,
"description": "Human-readable skill name"
},
"description": {
"type": "string",
"maxLength": 500,
"description": "Brief description of the skill"
},
"source": {
"type": "string",
"pattern": "^[a-zA-Z0-9_-]+/[a-zA-Z0-9_.-]+$",
"description": "GitHub repository: owner/repo"
},
"tags": {
"type": "array",
"items": {
"type": "string",
"pattern": "^[a-z0-9-]+$"
},
"minItems": 1,
"maxItems": 10,
"description": "Tags for categorization (lowercase, hyphenated)"
},
"author": {
"type": "string",
"description": "Skill author name or GitHub username"
},
"version": {
"type": "string",
"pattern": "^\\d+\\.\\d+\\.\\d+$",
"description": "Semantic version (e.g., 1.0.0)"
},
"agents": {
"type": "array",
"items": {
"type": "string",
"enum": [
"claude-code",
"cursor",
"codex",
"gemini-cli",
"opencode",
"antigravity",
"amp",
"clawdbot",
"droid",
"github-copilot",
"goose",
"kilo",
"kiro-cli",
"roo",
"trae",
"windsurf",
"universal"
]
},
"description": "Compatible AI agents (omit for universal compatibility)"
}
}
}
}
}
+16 -19
View File
@@ -121,26 +121,23 @@ export interface MarketplaceConfig {
}
/**
* Default skill sources
* Default skill sources - loaded from marketplace/sources.json (single source of truth)
*/
export const DEFAULT_SKILL_SOURCES: SkillSource[] = [
{
owner: 'composioHQ',
repo: 'awesome-claude-code-skills',
name: 'Composio Curated',
description: 'Curated collection of Claude Code skills',
official: false,
branch: 'main',
},
{
owner: 'anthropics',
repo: 'courses',
name: 'Anthropic Official',
description: 'Official Anthropic courses and skills',
official: true,
branch: 'master',
},
];
import sourcesData from '../../../../marketplace/sources.json' with { type: 'json' };
export const DEFAULT_SKILL_SOURCES: SkillSource[] = sourcesData.sources.map(
(s: { source: string; name: string; official?: boolean }) => {
const [owner, repo] = s.source.split('/');
return {
owner,
repo,
name: s.name,
description: `Skills from ${s.name}`,
official: s.official || false,
branch: 'main',
};
}
);
/**
* Cache file name
@@ -0,0 +1,214 @@
import { describe, it, expect } from 'vitest';
import {
evaluateSkillContent,
getQualityGrade,
isHighQuality,
} from '../index.js';
describe('Quality Evaluation', () => {
describe('evaluateSkillContent', () => {
it('should score a well-structured skill highly', () => {
const content = `---
name: test-skill
description: A test skill for validation
globs: ["**/*.ts"]
---
# Test Skill
## When to Use
Use this skill when working with TypeScript files.
## Instructions
Always follow these patterns:
\`\`\`typescript
function example(): void {
console.log('example');
}
\`\`\`
## Commands
Run tests with:
\`\`\`bash
npm test
\`\`\`
## Boundaries
Never commit secrets to the repository.
Always run linting before commits.
`;
const result = evaluateSkillContent(content);
expect(result.overall).toBeGreaterThanOrEqual(70);
expect(result.structure.hasMetadata).toBe(true);
expect(result.structure.hasTriggers).toBe(true);
expect(result.structure.hasExamples).toBe(true);
expect(result.structure.hasBoundaries).toBe(true);
expect(result.clarity.hasHeaders).toBe(true);
expect(result.specificity.hasConcreteCommands).toBe(true);
});
it('should score a minimal skill lower', () => {
const content = `# My Skill
Be helpful and assist the user with various tasks.
Try to do your best.
`;
const result = evaluateSkillContent(content);
expect(result.overall).toBeLessThan(50);
expect(result.structure.hasMetadata).toBe(false);
expect(result.structure.hasTriggers).toBe(false);
expect(result.specificity.vagueTermCount).toBeGreaterThan(0);
expect(result.warnings.length).toBeGreaterThan(0);
});
it('should penalize overly long skills', () => {
const longContent = '# Skill\n' + 'Some content.\n'.repeat(600);
const result = evaluateSkillContent(longContent);
expect(result.clarity.lineCount).toBeGreaterThan(500);
expect(result.clarity.score).toBeLessThan(70);
});
it('should detect vague terms', () => {
const content = `# Skill
Be helpful and assist the user.
Try to do your best when appropriate.
Help with various tasks as needed.
`;
const result = evaluateSkillContent(content);
expect(result.specificity.vagueTermCount).toBeGreaterThan(3);
});
it('should detect code examples', () => {
const content = `# Skill
\`\`\`typescript
const x = 1;
\`\`\`
\`\`\`javascript
const y = 2;
\`\`\`
`;
const result = evaluateSkillContent(content);
expect(result.structure.hasExamples).toBe(true);
expect(result.specificity.hasCodeExamples).toBe(true);
});
it('should detect boundary patterns', () => {
const content = `# Skill
## Boundaries
- Never commit secrets
- Always run tests
- Don't modify node_modules
- Avoid using deprecated APIs
`;
const result = evaluateSkillContent(content);
expect(result.structure.hasBoundaries).toBe(true);
});
it('should detect trigger conditions', () => {
const content = `# Skill
## When to Use
Use this skill when:
- Working with React components
- Building forms
`;
const result = evaluateSkillContent(content);
expect(result.structure.hasTriggers).toBe(true);
expect(result.structure.hasWhenToUse).toBe(true);
});
});
describe('getQualityGrade', () => {
it('should return A for scores >= 90', () => {
expect(getQualityGrade(90)).toBe('A');
expect(getQualityGrade(100)).toBe('A');
});
it('should return B for scores >= 80', () => {
expect(getQualityGrade(80)).toBe('B');
expect(getQualityGrade(89)).toBe('B');
});
it('should return C for scores >= 70', () => {
expect(getQualityGrade(70)).toBe('C');
expect(getQualityGrade(79)).toBe('C');
});
it('should return D for scores >= 60', () => {
expect(getQualityGrade(60)).toBe('D');
expect(getQualityGrade(69)).toBe('D');
});
it('should return F for scores < 60', () => {
expect(getQualityGrade(59)).toBe('F');
expect(getQualityGrade(0)).toBe('F');
});
});
describe('isHighQuality', () => {
const defaultAdvanced = {
score: 100,
deprecatedPatterns: [],
conflictingInstructions: [],
securityIssues: [],
completeness: { score: 100, hasTodos: false, todoCount: 0, emptySections: [], exampleCoverage: 100 },
};
it('should return true for high scoring skills with few warnings', () => {
const score = {
overall: 80,
structure: { score: 80, hasMetadata: true, hasDescription: true, hasTriggers: true, hasExamples: true, hasBoundaries: true, hasWhenToUse: true },
clarity: { score: 80, lineCount: 100, tokenCount: 500, avgSentenceLength: 15, hasHeaders: true },
specificity: { score: 80, hasConcreteCommands: true, hasFilePatterns: true, hasCodeExamples: true, vagueTermCount: 0 },
advanced: defaultAdvanced,
warnings: [],
suggestions: [],
};
expect(isHighQuality(score)).toBe(true);
});
it('should return false for low scoring skills', () => {
const score = {
overall: 50,
structure: { score: 50, hasMetadata: false, hasDescription: false, hasTriggers: false, hasExamples: false, hasBoundaries: false, hasWhenToUse: false },
clarity: { score: 50, lineCount: 100, tokenCount: 500, avgSentenceLength: 15, hasHeaders: true },
specificity: { score: 50, hasConcreteCommands: false, hasFilePatterns: false, hasCodeExamples: false, vagueTermCount: 5 },
advanced: { ...defaultAdvanced, score: 50 },
warnings: ['Missing triggers', 'No examples'],
suggestions: [],
};
expect(isHighQuality(score)).toBe(false);
});
it('should return false for skills with many warnings', () => {
const score = {
overall: 75,
structure: { score: 75, hasMetadata: true, hasDescription: true, hasTriggers: false, hasExamples: false, hasBoundaries: false, hasWhenToUse: false },
clarity: { score: 75, lineCount: 100, tokenCount: 500, avgSentenceLength: 15, hasHeaders: true },
specificity: { score: 75, hasConcreteCommands: true, hasFilePatterns: true, hasCodeExamples: false, vagueTermCount: 0 },
advanced: { ...defaultAdvanced, score: 75 },
warnings: ['Warning 1', 'Warning 2', 'Warning 3'],
suggestions: [],
};
expect(isHighQuality(score)).toBe(false);
});
});
});
+262
View File
@@ -0,0 +1,262 @@
/**
* Benchmark quality scores against category leaders
*/
import type { QualityScore } from './index.js';
export interface BenchmarkResult {
skill: string;
score: number;
grade: string;
categoryAvg: number;
topSkillScore: number;
percentile: number;
comparisonNotes: string[];
recommendations: string[];
}
export interface CategoryStats {
category: string;
avgScore: number;
topScore: number;
topSkills: string[];
count: number;
distribution: {
A: number;
B: number;
C: number;
D: number;
F: number;
};
}
const CATEGORY_BENCHMARKS: Record<string, CategoryStats> = {
react: {
category: 'react',
avgScore: 78,
topScore: 95,
topSkills: ['react-patterns', 'react-hooks-best-practices'],
count: 150,
distribution: { A: 15, B: 35, C: 30, D: 15, F: 5 },
},
typescript: {
category: 'typescript',
avgScore: 75,
topScore: 92,
topSkills: ['typescript-strict', 'type-safety-patterns'],
count: 120,
distribution: { A: 12, B: 30, C: 35, D: 18, F: 5 },
},
testing: {
category: 'testing',
avgScore: 72,
topScore: 90,
topSkills: ['tdd-workflow', 'testing-best-practices'],
count: 80,
distribution: { A: 10, B: 28, C: 38, D: 19, F: 5 },
},
git: {
category: 'git',
avgScore: 80,
topScore: 94,
topSkills: ['git-workflow', 'conventional-commits'],
count: 60,
distribution: { A: 18, B: 40, C: 28, D: 12, F: 2 },
},
security: {
category: 'security',
avgScore: 76,
topScore: 93,
topSkills: ['security-review', 'owasp-patterns'],
count: 45,
distribution: { A: 14, B: 32, C: 34, D: 16, F: 4 },
},
api: {
category: 'api',
avgScore: 74,
topScore: 91,
topSkills: ['api-design', 'rest-best-practices'],
count: 55,
distribution: { A: 11, B: 30, C: 36, D: 18, F: 5 },
},
general: {
category: 'general',
avgScore: 70,
topScore: 88,
topSkills: ['code-review', 'best-practices'],
count: 200,
distribution: { A: 8, B: 25, C: 40, D: 22, F: 5 },
},
};
export function getGrade(score: number): string {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
if (score >= 60) return 'D';
return 'F';
}
export function detectCategory(skillName: string, tags: string[] = []): string {
const lowerName = skillName.toLowerCase();
const lowerTags = tags.map(t => t.toLowerCase());
const searchTerms = [lowerName, ...lowerTags];
const categoryKeywords: Record<string, string[]> = {
react: ['react', 'hooks', 'jsx', 'tsx', 'component', 'nextjs', 'remix'],
typescript: ['typescript', 'type', 'types', 'ts', 'strict'],
testing: ['test', 'testing', 'tdd', 'jest', 'vitest', 'playwright', 'e2e'],
git: ['git', 'commit', 'branch', 'merge', 'workflow', 'conventional'],
security: ['security', 'auth', 'owasp', 'vulnerability', 'safe'],
api: ['api', 'rest', 'graphql', 'endpoint', 'http'],
};
for (const [category, keywords] of Object.entries(categoryKeywords)) {
for (const term of searchTerms) {
if (keywords.some(kw => term.includes(kw))) {
return category;
}
}
}
return 'general';
}
export function calculatePercentile(score: number, categoryStats: CategoryStats): number {
const { distribution } = categoryStats;
const totalSkills = distribution.A + distribution.B + distribution.C + distribution.D + distribution.F;
let percentBelow = 0;
if (score < 60) {
percentBelow = (score / 60) * (distribution.F / totalSkills) * 100;
} else if (score < 70) {
percentBelow = (distribution.F / totalSkills) * 100;
percentBelow += ((score - 60) / 10) * (distribution.D / totalSkills) * 100;
} else if (score < 80) {
percentBelow = ((distribution.F + distribution.D) / totalSkills) * 100;
percentBelow += ((score - 70) / 10) * (distribution.C / totalSkills) * 100;
} else if (score < 90) {
percentBelow = ((distribution.F + distribution.D + distribution.C) / totalSkills) * 100;
percentBelow += ((score - 80) / 10) * (distribution.B / totalSkills) * 100;
} else {
percentBelow = ((distribution.F + distribution.D + distribution.C + distribution.B) / totalSkills) * 100;
percentBelow += ((score - 90) / 10) * (distribution.A / totalSkills) * 100;
}
return Math.round(Math.min(99, Math.max(1, percentBelow)));
}
export function generateComparisonNotes(
quality: QualityScore,
categoryStats: CategoryStats
): string[] {
const notes: string[] = [];
const topScore = categoryStats.topScore;
const avgScore = categoryStats.avgScore;
if (quality.overall >= topScore) {
notes.push('Your skill is among the top performers in this category');
} else if (quality.overall >= avgScore) {
notes.push(`Your skill is above the category average (${avgScore})`);
} else {
notes.push(`Your skill is ${avgScore - quality.overall} points below the category average`);
}
if (!quality.structure.hasExamples) {
notes.push('Missing code examples (present in 95% of top skills)');
}
if (!quality.structure.hasTriggers) {
notes.push('Missing trigger conditions (present in 80% of top skills)');
}
if (!quality.structure.hasBoundaries) {
notes.push('Missing "When Not to Use" section (present in 80% of top skills)');
}
if (quality.specificity.vagueTermCount > 3) {
notes.push('Trigger conditions are less specific than category average');
}
if (quality.clarity.lineCount > 300) {
notes.push('Skill is longer than recommended (top skills average 150-250 lines)');
}
if (quality.advanced.deprecatedPatterns.length > 0) {
notes.push('Contains deprecated patterns not found in top skills');
}
return notes;
}
export function generateRecommendations(
quality: QualityScore,
categoryStats: CategoryStats
): string[] {
const recommendations: string[] = [];
const gap = categoryStats.topScore - quality.overall;
if (gap > 20) {
recommendations.push('Consider studying top skills in this category for patterns');
}
if (!quality.structure.hasExamples) {
recommendations.push(`Add ${quality.specificity.hasCodeExamples ? 'more' : ''} code examples showing input/output`);
}
if (!quality.structure.hasTriggers) {
recommendations.push('Add explicit trigger conditions with patterns like "Triggers when:"');
}
if (!quality.structure.hasBoundaries) {
recommendations.push('Add a "Boundaries" or "Limitations" section');
}
if (quality.clarity.lineCount > 400) {
recommendations.push('Split into multiple focused skills (top skills are 150-250 lines)');
}
if (quality.specificity.vagueTermCount > 0) {
recommendations.push(`Replace ${quality.specificity.vagueTermCount} vague term(s) with specific instructions`);
}
if (quality.advanced.completeness.hasTodos) {
recommendations.push('Complete TODO items before publishing');
}
return recommendations;
}
export function benchmarkSkill(
skillName: string,
quality: QualityScore,
tags: string[] = [],
customCategoryStats?: CategoryStats
): BenchmarkResult {
const category = detectCategory(skillName, tags);
const categoryStats = customCategoryStats || CATEGORY_BENCHMARKS[category] || CATEGORY_BENCHMARKS.general;
const percentile = calculatePercentile(quality.overall, categoryStats);
const comparisonNotes = generateComparisonNotes(quality, categoryStats);
const recommendations = generateRecommendations(quality, categoryStats);
return {
skill: skillName,
score: quality.overall,
grade: getGrade(quality.overall),
categoryAvg: categoryStats.avgScore,
topSkillScore: categoryStats.topScore,
percentile,
comparisonNotes,
recommendations,
};
}
export function getCategoryStats(category: string): CategoryStats | null {
return CATEGORY_BENCHMARKS[category] || null;
}
export function getAllCategories(): string[] {
return Object.keys(CATEGORY_BENCHMARKS);
}
+589
View File
@@ -0,0 +1,589 @@
import { readFileSync, existsSync } from 'node:fs';
import { join, basename } from 'node:path';
export * from './benchmark.js';
export interface QualityScore {
overall: number;
structure: StructureScore;
clarity: ClarityScore;
specificity: SpecificityScore;
advanced: AdvancedScore;
warnings: string[];
suggestions: string[];
}
export interface AdvancedScore {
score: number;
deprecatedPatterns: string[];
conflictingInstructions: string[];
securityIssues: string[];
completeness: CompletenessResult;
}
export interface CompletenessResult {
score: number;
hasTodos: boolean;
todoCount: number;
emptySections: string[];
exampleCoverage: number;
}
export interface StructureScore {
score: number;
hasMetadata: boolean;
hasDescription: boolean;
hasTriggers: boolean;
hasExamples: boolean;
hasBoundaries: boolean;
hasWhenToUse: boolean;
}
export interface ClarityScore {
score: number;
lineCount: number;
tokenCount: number;
avgSentenceLength: number;
hasHeaders: boolean;
}
export interface SpecificityScore {
score: number;
hasConcreteCommands: boolean;
hasFilePatterns: boolean;
hasCodeExamples: boolean;
vagueTermCount: number;
}
const VAGUE_TERMS = [
'be helpful',
'assist the user',
'help with',
'try to',
'attempt to',
'do your best',
'as needed',
'when appropriate',
'if necessary',
'general purpose',
'various tasks',
'many things',
'etc.',
'and so on',
'stuff like that',
];
const BOUNDARY_PATTERNS = [
/never\s+(?:do|use|commit|push|delete|remove)/i,
/always\s+(?:do|use|check|verify|ensure)/i,
/don'?t\s+(?:do|use|commit|push|delete)/i,
/avoid\s+(?:using|doing|committing)/i,
/must\s+(?:not|always|never)/i,
/forbidden/i,
/prohibited/i,
/required/i,
];
const TRIGGER_PATTERNS = [
/when\s+to\s+use/i,
/use\s+this\s+(?:skill|when)/i,
/triggers?\s*(?:when|:)/i,
/activated?\s+(?:when|by)/i,
/applies?\s+(?:when|to)/i,
/invoke\s+(?:when|this)/i,
];
const COMMAND_PATTERNS = [
/```(?:bash|sh|shell|zsh)[\s\S]*?```/g,
/`(?:npm|pnpm|yarn|bun|npx|git|docker|kubectl)\s+[^`]+`/g,
/\$\s*\w+/g,
];
const CODE_EXAMPLE_PATTERNS = [
/```(?:typescript|javascript|tsx|jsx|python|go|rust|java)[\s\S]*?```/g,
/```[\s\S]{50,}?```/g,
];
const FILE_PATTERN_PATTERNS = [
/\*\*\/\*\.\w+/,
/\.\w+$/m,
/glob[s]?\s*[:=]/i,
/include[s]?\s*[:=]/i,
/pattern[s]?\s*[:=]/i,
];
const DEPRECATED_PATTERNS = [
{ pattern: /require\s*\(['"][^'"]+['"]\)/g, message: 'Uses CommonJS require() instead of ES modules' },
{ pattern: /React\.Component/g, message: 'Uses class components instead of functional' },
{ pattern: /componentDidMount|componentWillUnmount|componentDidUpdate/g, message: 'Uses lifecycle methods instead of hooks' },
{ pattern: /\bvar\s+\w+\s*=/g, message: 'Uses var instead of const/let' },
{ pattern: /\.then\s*\([^)]*\)\.catch/g, message: 'Uses .then().catch() instead of async/await' },
{ pattern: /new\s+Promise\s*\(/g, message: 'Consider using async/await instead of new Promise()' },
];
const SECURITY_PATTERNS = [
{ pattern: /password\s*[:=]\s*['"][^'"]+['"]/gi, message: 'Potential hardcoded password' },
{ pattern: /api[_-]?key\s*[:=]\s*['"][^'"]+['"]/gi, message: 'Potential hardcoded API key' },
{ pattern: /secret\s*[:=]\s*['"][^'"]+['"]/gi, message: 'Potential hardcoded secret' },
{ pattern: /token\s*[:=]\s*['"][A-Za-z0-9_-]{20,}['"]/gi, message: 'Potential hardcoded token' },
{ pattern: /\$\{[^}]*\}/g, message: 'Template literal - ensure proper sanitization in shell commands' },
{ pattern: /eval\s*\(/g, message: 'Uses eval() - potential code injection risk' },
{ pattern: /innerHTML\s*=/g, message: 'Uses innerHTML - potential XSS risk' },
{ pattern: /dangerouslySetInnerHTML/g, message: 'Uses dangerouslySetInnerHTML - potential XSS risk' },
];
function extractFrontmatter(content: string): Record<string, unknown> | null {
const normalizedContent = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
const match = normalizedContent.match(/^---\s*\n([\s\S]*?)\n---/);
if (!match) return null;
const frontmatter: Record<string, unknown> = {};
const lines = match[1].split('\n');
for (const line of lines) {
const colonIndex = line.indexOf(':');
if (colonIndex > 0) {
const key = line.slice(0, colonIndex).trim();
const value = line.slice(colonIndex + 1).trim();
frontmatter[key] = value;
}
}
return Object.keys(frontmatter).length > 0 ? frontmatter : null;
}
function countTokens(text: string): number {
return Math.ceil(text.length / 4);
}
function countVagueTerms(content: string): number {
const lowerContent = content.toLowerCase();
let count = 0;
for (const term of VAGUE_TERMS) {
const regex = new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
const matches = lowerContent.match(regex);
if (matches) count += matches.length;
}
return count;
}
function hasPattern(content: string, patterns: RegExp[]): boolean {
return patterns.some(p => p.test(content));
}
function countMatches(content: string, patterns: RegExp[]): number {
let count = 0;
for (const pattern of patterns) {
const matches = content.match(pattern);
if (matches) count += matches.length;
}
return count;
}
function calculateAvgSentenceLength(content: string): number {
const contentWithoutCode = content.replace(/```[\s\S]*?```/g, '');
const sentences = contentWithoutCode.split(/[.!?]+/).filter(s => s.trim().length > 0);
if (sentences.length === 0) return 0;
const totalWords = sentences.reduce((sum, s) => sum + s.trim().split(/\s+/).length, 0);
return Math.round(totalWords / sentences.length);
}
function evaluateStructure(content: string): StructureScore {
const frontmatter = extractFrontmatter(content);
const hasMetadata = frontmatter !== null && Object.keys(frontmatter).length > 0;
const hasDescription = !!(frontmatter?.description) || /^#+\s*description/im.test(content);
const hasTriggers = hasPattern(content, TRIGGER_PATTERNS);
const hasExamples = countMatches(content, CODE_EXAMPLE_PATTERNS) > 0;
const hasBoundaries = hasPattern(content, BOUNDARY_PATTERNS);
const hasWhenToUse = /when\s+to\s+use|use\s+case|scenario/i.test(content);
let score = 0;
if (hasMetadata) score += 15;
if (hasDescription) score += 10;
if (hasTriggers) score += 20;
if (hasExamples) score += 20;
if (hasBoundaries) score += 20;
if (hasWhenToUse) score += 15;
return {
score: Math.min(100, score),
hasMetadata,
hasDescription,
hasTriggers,
hasExamples,
hasBoundaries,
hasWhenToUse,
};
}
function evaluateClarity(content: string): ClarityScore {
const lines = content.split('\n');
const lineCount = lines.length;
const tokenCount = countTokens(content);
const avgSentenceLength = calculateAvgSentenceLength(content);
const hasHeaders = /^#+\s+/m.test(content);
let score = 100;
if (lineCount > 500) score -= 30;
else if (lineCount > 300) score -= 15;
else if (lineCount > 150) score -= 5;
if (tokenCount > 4000) score -= 30;
else if (tokenCount > 2000) score -= 15;
else if (tokenCount > 1000) score -= 5;
if (avgSentenceLength > 30) score -= 20;
else if (avgSentenceLength > 20) score -= 10;
if (!hasHeaders) score -= 15;
return {
score: Math.max(0, score),
lineCount,
tokenCount,
avgSentenceLength,
hasHeaders,
};
}
function countCodeBlocks(content: string): number {
const fencedBlocks = content.match(/```[\s\S]*?```/g) || [];
return fencedBlocks.length;
}
function detectDeprecatedPatterns(content: string): string[] {
const codeBlocks = content.match(/```[\s\S]*?```/g) || [];
const codeContent = codeBlocks.join('\n');
const issues: string[] = [];
for (const { pattern, message } of DEPRECATED_PATTERNS) {
const regex = new RegExp(pattern.source, pattern.flags);
if (regex.test(codeContent)) {
issues.push(message);
}
}
return [...new Set(issues)];
}
function detectSecurityPatterns(content: string): string[] {
const issues: string[] = [];
for (const { pattern, message } of SECURITY_PATTERNS) {
const regex = new RegExp(pattern.source, pattern.flags);
if (regex.test(content)) {
if (!message.includes('Template literal') || content.includes('bash') || content.includes('shell')) {
issues.push(message);
}
}
}
return [...new Set(issues)];
}
function detectConflictingInstructions(content: string): string[] {
const issues: string[] = [];
const lowerContent = content.toLowerCase();
const alwaysMatches = lowerContent.match(/always\s+(?:use|do|include|add)\s+(\w+)/gi) || [];
const neverMatches = lowerContent.match(/never\s+(?:use|do|include|add)\s+(\w+)/gi) || [];
for (const always of alwaysMatches) {
const term = always.replace(/always\s+(?:use|do|include|add)\s+/i, '').toLowerCase();
for (const never of neverMatches) {
const neverTerm = never.replace(/never\s+(?:use|do|include|add)\s+/i, '').toLowerCase();
if (term === neverTerm) {
issues.push(`Conflicting instructions: "always" and "never" used with "${term}"`);
}
}
}
const mustMatches = lowerContent.match(/must\s+(\w+)/gi) || [];
const mustNotMatches = lowerContent.match(/must\s+not\s+(\w+)/gi) || [];
for (const must of mustMatches) {
const term = must.replace(/must\s+/i, '').toLowerCase();
for (const mustNot of mustNotMatches) {
const notTerm = mustNot.replace(/must\s+not\s+/i, '').toLowerCase();
if (term === notTerm) {
issues.push(`Conflicting instructions: "must" and "must not" used with "${term}"`);
}
}
}
return [...new Set(issues)];
}
function assessCompleteness(content: string): CompletenessResult {
const todoMatches = content.match(/TODO|FIXME|XXX|HACK/gi) || [];
const todoCount = todoMatches.length;
const headerPositions: Array<{ header: string; index: number }> = [];
const lines = content.split('\n');
let inFence = false;
let offset = 0;
for (const line of lines) {
if (/^```|^~~~/.test(line)) {
inFence = !inFence;
} else if (!inFence && /^#+\s+.+$/.test(line)) {
headerPositions.push({ header: line, index: offset });
}
offset += line.length + 1;
}
const emptySections: string[] = [];
for (let i = 0; i < headerPositions.length - 1; i++) {
const current = headerPositions[i];
const next = headerPositions[i + 1];
const sectionContent = content.slice(current.index + current.header.length, next.index).trim();
if (sectionContent.length < 20) {
const sectionName = current.header.replace(/^#+\s+/, '');
emptySections.push(sectionName);
}
}
if (headerPositions.length > 0) {
const last = headerPositions[headerPositions.length - 1];
const tailContent = content.slice(last.index + last.header.length).trim();
if (tailContent.length < 20) {
const sectionName = last.header.replace(/^#+\s+/, '');
emptySections.push(sectionName);
}
}
const codeBlocks = countCodeBlocks(content);
const exampleCoverage = Math.min(100, codeBlocks * 25);
let score = 100;
if (todoCount > 0) score -= Math.min(30, todoCount * 10);
if (emptySections.length > 0) score -= Math.min(30, emptySections.length * 10);
if (codeBlocks < 2) score -= 20;
else if (codeBlocks < 4) score -= 10;
return {
score: Math.max(0, score),
hasTodos: todoCount > 0,
todoCount,
emptySections,
exampleCoverage,
};
}
function evaluateAdvanced(content: string): AdvancedScore {
const deprecatedPatterns = detectDeprecatedPatterns(content);
const conflictingInstructions = detectConflictingInstructions(content);
const securityIssues = detectSecurityPatterns(content);
const completeness = assessCompleteness(content);
let score = 100;
score -= Math.min(30, deprecatedPatterns.length * 10);
score -= Math.min(30, conflictingInstructions.length * 15);
score -= Math.min(25, securityIssues.length * 10);
score -= Math.round((100 - completeness.score) * 0.15);
return {
score: Math.max(0, score),
deprecatedPatterns,
conflictingInstructions,
securityIssues,
completeness,
};
}
function evaluateSpecificity(content: string): SpecificityScore {
const hasConcreteCommands = countMatches(content, COMMAND_PATTERNS) > 0;
const hasFilePatterns = hasPattern(content, FILE_PATTERN_PATTERNS);
const codeBlockCount = countCodeBlocks(content);
const hasCodeExamples = codeBlockCount >= 2;
const vagueTermCount = countVagueTerms(content);
let score = 0;
if (hasConcreteCommands) score += 30;
if (hasFilePatterns) score += 25;
if (hasCodeExamples) score += 30;
if (vagueTermCount === 0) score += 15;
else if (vagueTermCount <= 2) score += 10;
else if (vagueTermCount <= 5) score += 5;
return {
score: Math.min(100, score),
hasConcreteCommands,
hasFilePatterns,
hasCodeExamples,
vagueTermCount,
};
}
function generateWarnings(
structure: StructureScore,
clarity: ClarityScore,
specificity: SpecificityScore,
advanced: AdvancedScore
): string[] {
const warnings: string[] = [];
if (!structure.hasMetadata) {
warnings.push('Missing frontmatter metadata');
}
if (!structure.hasTriggers) {
warnings.push('No trigger conditions defined');
}
if (!structure.hasBoundaries) {
warnings.push('No boundaries or constraints specified');
}
if (clarity.lineCount > 500) {
warnings.push(`Skill is too long (${clarity.lineCount} lines)`);
}
if (clarity.tokenCount > 4000) {
warnings.push(`High token usage (${clarity.tokenCount} tokens)`);
}
if (specificity.vagueTermCount > 5) {
warnings.push(`Contains ${specificity.vagueTermCount} vague terms`);
}
if (!structure.hasExamples) {
warnings.push('No code examples provided');
} else if (!specificity.hasCodeExamples) {
warnings.push('Only one code example provided');
}
for (const issue of advanced.securityIssues) {
warnings.push(`Security: ${issue}`);
}
for (const conflict of advanced.conflictingInstructions) {
warnings.push(conflict);
}
if (advanced.completeness.hasTodos) {
warnings.push(`Contains ${advanced.completeness.todoCount} TODO/FIXME comment(s)`);
}
if (advanced.completeness.emptySections.length > 0) {
warnings.push(`Empty sections: ${advanced.completeness.emptySections.join(', ')}`);
}
return warnings;
}
function generateSuggestions(
structure: StructureScore,
clarity: ClarityScore,
specificity: SpecificityScore,
advanced: AdvancedScore
): string[] {
const suggestions: string[] = [];
if (!structure.hasMetadata) {
suggestions.push('Add YAML frontmatter with name, description, and globs');
}
if (!structure.hasTriggers) {
suggestions.push('Add a "When to Use" section with specific trigger conditions');
}
if (!structure.hasExamples) {
suggestions.push('Include code examples showing expected output');
}
if (!structure.hasBoundaries) {
suggestions.push('Define boundaries: what the agent should never do');
}
if (clarity.lineCount > 300) {
suggestions.push('Consider splitting into multiple focused skills');
}
if (!clarity.hasHeaders) {
suggestions.push('Use markdown headers to organize content');
}
if (specificity.vagueTermCount > 0) {
suggestions.push('Replace vague terms with specific instructions');
}
if (!specificity.hasConcreteCommands) {
suggestions.push('Add concrete executable commands with flags');
}
if (advanced.deprecatedPatterns.length > 0) {
suggestions.push('Update code examples to use modern patterns (ES modules, hooks, async/await)');
}
if (advanced.securityIssues.length > 0) {
suggestions.push('Review and remove potential security risks from examples');
}
if (advanced.completeness.hasTodos) {
suggestions.push('Complete or remove TODO/FIXME comments');
}
if (advanced.completeness.emptySections.length > 0) {
suggestions.push('Add content to empty sections or remove them');
}
if (advanced.completeness.exampleCoverage < 50) {
suggestions.push('Add more code examples to improve coverage');
}
return suggestions;
}
export function evaluateSkillContent(content: string): QualityScore {
const structure = evaluateStructure(content);
const clarity = evaluateClarity(content);
const specificity = evaluateSpecificity(content);
const advanced = evaluateAdvanced(content);
const overall = Math.round(
structure.score * 0.35 +
clarity.score * 0.25 +
specificity.score * 0.25 +
advanced.score * 0.15
);
const warnings = generateWarnings(structure, clarity, specificity, advanced);
const suggestions = generateSuggestions(structure, clarity, specificity, advanced);
return {
overall,
structure,
clarity,
specificity,
advanced,
warnings,
suggestions,
};
}
export function evaluateSkillFile(filePath: string): QualityScore | null {
if (!existsSync(filePath)) return null;
try {
const content = readFileSync(filePath, 'utf-8');
return evaluateSkillContent(content);
} catch {
return null;
}
}
export function evaluateSkillDirectory(dirPath: string): QualityScore | null {
const skillMdPath = join(dirPath, 'SKILL.md');
if (existsSync(skillMdPath)) {
return evaluateSkillFile(skillMdPath);
}
const mdcFiles = ['index.mdc', `${basename(dirPath)}.mdc`];
for (const file of mdcFiles) {
const mdcPath = join(dirPath, file);
if (existsSync(mdcPath)) {
return evaluateSkillFile(mdcPath);
}
}
return null;
}
export function getQualityGrade(score: number): string {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
if (score >= 70) return 'C';
if (score >= 60) return 'D';
return 'F';
}
export function isHighQuality(score: QualityScore): boolean {
return score.overall >= 80 && score.warnings.length <= 2;
}
+78 -163
View File
@@ -5,216 +5,131 @@
**Interactive terminal UI for SkillKit** - browse, install, translate, and manage skills visually in your terminal.
## Requirements
- **Bun runtime** (>=1.2.0) - Required for OpenTUI rendering
- Terminal with 80x24 minimum (120x40 recommended)
Install Bun: https://bun.sh
## Installation
```bash
npm install @skillkit/tui
# or
npm install -g skillkit # includes TUI
npm install -g skillkit
```
## Quick Start
```bash
skillkit ui
# or just
skillkit
# Launch TUI with Bun
bun skillkit ui
# Or via pnpm in monorepo
pnpm ui
```
## Features
- **Browse Skills**: Explore 33+ skill repositories with search and filtering
- **Smart Recommendations**: See project-aware skill suggestions with match scores
- **Cross-Agent Translation**: Convert skills between any of 17 agent formats
- **Context Management**: View detected stack and sync to all agents
- **Multi-Agent Install**: Install skills to multiple agents at once
- **Responsive Design**: Adapts to any terminal size
## Screens
### Home (h)
Overview of your project and quick actions. Shows detected agents, installed skills count, and navigation hints.
### Marketplace (m)
Browse curated skill marketplace:
- Search across 33+ repositories
- Filter by tags and categories
- View popularity metrics
- Install with one key
### Browse (b)
Explore available skills from curated repositories:
- Search skills with `/`
- Filter by tags
- View skill details
- One-key installation
### Workflow (w)
Manage and execute workflows:
- List available workflows
- View workflow steps
- Execute workflows
- Monitor progress
### Execute (x)
Execute skills with checkpoints:
- Task-based execution
- Decision and review checkpoints
- Dry-run mode
- Git integration
### Team (a)
Team collaboration management:
- Create and share skill bundles
- Import team bundles
- Sync with remote registry
- Manage team members
### Plugins (p)
Plugin system management:
- List installed plugins
- Install new plugins
- Enable/disable plugins
- View plugin details
### Methodology (o)
Development methodologies:
- Browse 5 methodologies (Agile, TDD, DevOps, Design Thinking, Feature Flags)
- View methodology skills
- Apply to project
- Track adoption
### Plan (n)
Structured plan system:
- Parse plan files
- Validate plan structure
- Execute plans step-by-step
- Track progress
### Recommend (r)
AI-powered skill suggestions based on your project:
- Analyzes your package.json, configs, and file structure
- Shows match percentage for each skill
- Explains why skills are recommended
- Filter by minimum score
### Translate (t)
Convert skills between agent formats:
- Select source skill
- Choose target agent(s)
- Preview translation
- Apply with confirmation
### Context (c)
View and manage project context:
- Detected languages and frameworks
- Found testing tools and databases
- Installed agents
- Sync context to all agents
### Memory (e)
Session memory system:
- View learnings
- Search past sessions
- Compress observations
- Export as skills
### Installed (i)
Manage your installed skills:
- View all installed skills
- Enable/disable skills
- Remove skills
- Update from source
### Sync (s)
Sync skills across agents:
- Select target agents
- Preview changes
- Apply sync
### Settings (,)
Configure SkillKit:
- Default agent
- Auto-sync settings
- Skill directories
- **Monochromatic Design** - Clean B&W theme with colored accents
- **Animated UI** - Smooth entrance animations and transitions
- **Browse Skills** - Explore skill repositories with search and filtering
- **Smart Recommendations** - AI-powered skill suggestions with match scores
- **Cross-Agent Translation** - Convert skills between 17+ agent formats
- **Team Collaboration** - Share and sync skills across teams
- **Responsive Design** - Adapts to any terminal size
## Keyboard Shortcuts
| Key | Action |
### Navigation
| Key | Screen |
|-----|--------|
| `h` | Home screen |
| `m` | Marketplace |
| `h` | Home |
| `b` | Browse skills |
| `m` | Marketplace |
| `r` | Recommendations |
| `i` | Installed skills |
| `s` | Sync settings |
### Actions
| Key | Screen |
|-----|--------|
| `t` | Translate skills |
| `w` | Workflows |
| `x` | Execute |
| `a` | Team collaboration |
| `n` | Plan |
| `y` | History |
### Team & Config
| Key | Screen |
|-----|--------|
| `a` | Team |
| `c` | Context |
| `e` | Memory |
| `p` | Plugins |
| `o` | Methodology |
| `n` | Plan system |
| `r` | Recommendations |
| `t` | Translate skills |
| `c` | Context management |
| `e` | Memory/Learnings |
| `i` | Installed skills |
| `s` | Sync skills |
| `,` | Settings |
| `↑/↓` | Navigate lists |
| `Enter` | Select / Confirm |
| `/` | Search |
| `Tab` | Switch focus |
| `Esc` | Go back |
| `?` | Help |
### Global
| Key | Action |
|-----|--------|
| `/` | Help screen |
| `esc` | Go back / Home |
| `q` | Quit |
| `j/k` | Navigate lists |
| `enter` | Select item |
## Screens Overview
- **Home** - Dashboard with stats, detected agents, and features
- **Browse** - Search and explore skill repositories
- **Marketplace** - Curated skill marketplace with popularity metrics
- **Recommend** - AI-powered suggestions based on your project
- **Installed** - Manage installed skills (enable/disable/remove)
- **Sync** - Sync skills across multiple agents
- **Translate** - Convert skills between agent formats
- **Workflow** - Manage and execute automation workflows
- **Execute** - Run skills with checkpoints
- **Plan** - Structured plan creation and execution
- **Team** - Share skills and bundles with team members
- **Context** - View detected stack and project context
- **Memory** - Session memory and learnings
- **Plugins** - Plugin management
- **Methodology** - Development methodology frameworks
- **Settings** - Configure SkillKit preferences
## Programmatic Usage
```typescript
import { startTUI, TUIOptions } from '@skillkit/tui';
import { startTUI } from '@skillkit/tui';
// Launch with defaults
await startTUI();
// Launch with options
await startTUI({
projectPath: './my-project',
initialScreen: 'browse',
theme: 'dark',
});
```
## Architecture
Built with:
- **Ink** - React for CLIs
- **OpenTUI** - High-performance terminal UI framework
- **React** - Component architecture
- **@skillkit/core** - Core functionality
```
src/
├── app.tsx # Main app component
├── index.tsx # Entry point and startTUI
├── App.tsx # Main app component
├── screens/ # Screen components
│ ├── Home.tsx
│ ├── Browse.tsx
│ ├── Recommend.tsx
│ ├── Translate.tsx
│ ├── Context.tsx
│ ├── Help.tsx
│ └── ...
├── components/ # Reusable UI components
│ ├── SkillCard.tsx
│ ├── AgentSelector.tsx
│ ├── Sidebar.tsx
│ ├── Splash.tsx
│ └── ...
└── hooks/ # React hooks
├── useSkills.ts
├── useContext.ts
└── ...
├── state/ # State types and navigation
├── theme/ # Colors and symbols
└── utils/ # Helper functions
```
## Terminal Requirements
- Minimum: 80x24 characters
- Recommended: 120x40 characters
- Supports: True Color, 256 colors, basic ANSI
## Documentation
Full documentation: https://github.com/rohitg00/skillkit
+7 -10
View File
@@ -1,7 +1,7 @@
{
"name": "@skillkit/tui",
"version": "1.6.4",
"description": "Terminal UI for SkillKit",
"version": "2.0.0",
"description": "Unified Terminal UI for SkillKit - Built on OpenTUI",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -23,22 +23,19 @@
"dependencies": {
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"chalk": "^5.3.0",
"ink": "^5.0.1",
"ink-select-input": "^6.0.0",
"ink-spinner": "^5.0.0",
"ink-text-input": "^6.0.0",
"react": "^18.3.1"
"@opentui/core": "^0.1.75",
"@opentui/react": "^0.1.75",
"react": "^19.0.0"
},
"devDependencies": {
"@types/node": "^22.10.5",
"@types/react": "^18.3.18",
"@types/react": "^19.0.0",
"tsup": "^8.3.5",
"typescript": "^5.7.2",
"vitest": "^2.1.8"
},
"engines": {
"node": ">=18.0.0"
"bun": ">=1.2.0"
},
"license": "Apache-2.0"
}
+87 -81
View File
@@ -1,105 +1,111 @@
import { useState } from 'react';
import { Box, Text, useInput, useApp, useStdout } from 'ink';
import { useState, useCallback, useEffect } from 'react';
import { useKeyboard } from '@opentui/react';
import { type Screen, NAV_KEYS } from './state/types.js';
import { Sidebar } from './components/Sidebar.js';
import { Home } from './screens/Home.js';
import { Browse } from './screens/Browse.js';
import { Installed } from './screens/Installed.js';
import { Sync } from './screens/Sync.js';
import { Settings } from './screens/Settings.js';
import { Recommend } from './screens/Recommend.js';
import { Translate } from './screens/Translate.js';
import { Context } from './screens/Context.js';
import { Workflow } from './screens/Workflow.js';
import { Execute } from './screens/Execute.js';
import { History } from './screens/History.js';
import { Marketplace } from './screens/Marketplace.js';
import { Memory } from './screens/Memory.js';
import { Team } from './screens/Team.js';
import { Plugins } from './screens/Plugins.js';
import { Methodology } from './screens/Methodology.js';
import { Plan } from './screens/Plan.js';
import { Splash } from './components/Splash.js';
import {
Home, Browse, Installed, Marketplace, Settings, Recommend,
Translate, Context, Memory, Team, Plugins, Methodology,
Plan, Workflow, Execute, History, Sync, Help,
} from './screens/index.js';
export type Screen = 'home' | 'browse' | 'installed' | 'sync' | 'settings' | 'recommend' | 'translate' | 'context' | 'workflow' | 'execute' | 'history' | 'marketplace' | 'memory' | 'team' | 'plugins' | 'methodology' | 'plan';
interface AppProps {
onExit?: (code?: number) => void;
}
export function App() {
export function App({ onExit }: AppProps = {}) {
const [showSplash, setShowSplash] = useState(true);
const [screen, setScreen] = useState<Screen>('home');
const { exit } = useApp();
const { stdout } = useStdout();
const [dimensions, setDimensions] = useState({
cols: process.stdout.columns || 80,
rows: process.stdout.rows || 24,
});
const cols = stdout?.columns || 80;
const rows = stdout?.rows || 24;
const showSidebar = cols >= 70;
useEffect(() => {
const handleResize = () => {
setDimensions({
cols: process.stdout.columns || 80,
rows: process.stdout.rows || 24,
});
};
process.stdout.on('resize', handleResize);
return () => { process.stdout.off('resize', handleResize); };
}, []);
const NAV_KEYS: Record<string, Screen> = {
h: 'home',
m: 'marketplace',
b: 'browse',
w: 'workflow',
x: 'execute',
y: 'history',
r: 'recommend',
t: 'translate',
c: 'context',
e: 'memory',
i: 'installed',
s: 'sync',
a: 'team',
p: 'plugins',
o: 'methodology',
n: 'plan',
',': 'settings',
};
const { cols, rows } = dimensions;
const showSidebar = cols >= 60;
useInput((input, key) => {
if (input === 'q') {
exit();
const handleNavigate = useCallback((newScreen: Screen) => {
setScreen(newScreen);
}, []);
const handleSplashComplete = useCallback(() => {
setShowSplash(false);
}, []);
useKeyboard((key: { name?: string; ctrl?: boolean }) => {
if (showSplash) {
setShowSplash(false);
return;
}
if (key.escape) {
setScreen('home');
if (key.name === 'q' || (key.ctrl && key.name === 'c')) {
onExit ? onExit(0) : process.exit(0);
return;
}
const targetScreen = NAV_KEYS[input];
const targetScreen = NAV_KEYS[key.name || ''];
if (targetScreen) {
setScreen(targetScreen);
}
if (key.name === 'escape' && screen !== 'home') {
setScreen('home');
}
});
if (showSplash) {
return <Splash onComplete={handleSplashComplete} duration={3000} />;
}
const screenProps = {
onNavigate: handleNavigate,
cols: cols - (showSidebar ? 20 : 0),
rows,
};
const renderScreen = () => {
switch (screen) {
case 'home': return <Home onNavigate={setScreen} cols={cols} rows={rows} />;
case 'browse': return <Browse cols={cols} rows={rows} />;
case 'installed': return <Installed cols={cols} rows={rows} />;
case 'sync': return <Sync cols={cols} rows={rows} />;
case 'settings': return <Settings cols={cols} rows={rows} />;
case 'recommend': return <Recommend cols={cols} rows={rows} />;
case 'translate': return <Translate cols={cols} rows={rows} />;
case 'context': return <Context cols={cols} rows={rows} />;
case 'workflow': return <Workflow cols={cols} rows={rows} />;
case 'execute': return <Execute cols={cols} rows={rows} />;
case 'history': return <History cols={cols} rows={rows} />;
case 'marketplace': return <Marketplace cols={cols} rows={rows} />;
case 'memory': return <Memory cols={cols} rows={rows} />;
case 'team': return <Team cols={cols} rows={rows} />;
case 'plugins': return <Plugins cols={cols} rows={rows} />;
case 'methodology': return <Methodology cols={cols} rows={rows} />;
case 'plan': return <Plan cols={cols} rows={rows} />;
case 'home': return <Home {...screenProps} />;
case 'browse': return <Browse {...screenProps} />;
case 'installed': return <Installed {...screenProps} />;
case 'marketplace': return <Marketplace {...screenProps} />;
case 'settings': return <Settings {...screenProps} />;
case 'recommend': return <Recommend {...screenProps} />;
case 'translate': return <Translate {...screenProps} />;
case 'context': return <Context {...screenProps} />;
case 'memory': return <Memory {...screenProps} />;
case 'team': return <Team {...screenProps} />;
case 'plugins': return <Plugins {...screenProps} />;
case 'methodology': return <Methodology {...screenProps} />;
case 'plan': return <Plan {...screenProps} />;
case 'workflow': return <Workflow {...screenProps} />;
case 'execute': return <Execute {...screenProps} />;
case 'history': return <History {...screenProps} />;
case 'sync': return <Sync {...screenProps} />;
case 'help': return <Help {...screenProps} />;
default: return <Home {...screenProps} />;
}
};
const contentHeight = rows - 2;
return (
<Box flexDirection="column" height={rows}>
<Box flexDirection="row" height={contentHeight}>
{showSidebar && <Sidebar screen={screen} onNavigate={setScreen} />}
<Box flexDirection="column" flexGrow={1} marginLeft={1}>
{renderScreen()}
</Box>
</Box>
<Box>
<Text dimColor>h Home m Market b Browse w Wflow x Exec a Team p Plug o Meth n Plan r Rec t Trans c Ctx e Mem i Inst s Sync q Quit</Text>
</Box>
</Box>
<box flexDirection="row" height={rows}>
{showSidebar && <Sidebar screen={screen} onNavigate={handleNavigate} />}
<box flexDirection="column" flexGrow={1} marginLeft={showSidebar ? 1 : 0} paddingRight={1}>
{renderScreen()}
</box>
</box>
);
}
export { type Screen };
@@ -1,35 +0,0 @@
import { describe, it, expect } from 'vitest';
describe('TUI Components', () => {
describe('exports', () => {
it('should export App component', async () => {
const { App } = await import('../App.js');
expect(App).toBeDefined();
expect(typeof App).toBe('function');
});
it('should export theme configuration', async () => {
const { colors, symbols } = await import('../theme.js');
expect(colors).toBeDefined();
expect(symbols).toBeDefined();
});
it('should export all screens', async () => {
const screens = await import('../screens/index.js');
expect(screens.Home).toBeDefined();
expect(screens.Browse).toBeDefined();
expect(screens.Installed).toBeDefined();
expect(screens.Sync).toBeDefined();
expect(screens.Settings).toBeDefined();
expect(screens.Recommend).toBeDefined();
});
it('should export all hooks', async () => {
const hooks = await import('../hooks/index.js');
expect(hooks.useSkills).toBeDefined();
expect(hooks.useMarketplace).toBeDefined();
expect(hooks.useKeyboard).toBeDefined();
expect(hooks.useRecommend).toBeDefined();
});
});
});
+84
View File
@@ -0,0 +1,84 @@
import { describe, it, expect } from 'vitest';
import {
NAV_KEYS,
SIDEBAR_NAV,
STATUS_BAR_SHORTCUTS,
type Screen,
type SkillItem,
} from '../state/types.js';
import { terminalColors } from '../theme/colors.js';
import { symbols, AGENT_LOGOS } from '../theme/symbols.js';
import { getVersion, getSearchDirs, getInstallDir } from '../utils/helpers.js';
describe('@skillkit/tui', () => {
describe('state/types', () => {
it('should export NAV_KEYS with all screens', () => {
expect(NAV_KEYS).toBeDefined();
expect(NAV_KEYS.h).toBe('home');
expect(NAV_KEYS.b).toBe('browse');
expect(NAV_KEYS.m).toBe('marketplace');
expect(NAV_KEYS['/']).toBe('help');
expect(NAV_KEYS.q).toBeUndefined(); // q is quit, not a screen
});
it('should export SIDEBAR_NAV with sections', () => {
expect(SIDEBAR_NAV).toBeDefined();
expect(Array.isArray(SIDEBAR_NAV)).toBe(true);
expect(SIDEBAR_NAV.length).toBeGreaterThan(0);
const sections = SIDEBAR_NAV.map(s => s.section);
expect(sections).toContain('Discover');
expect(sections).toContain('Manage');
expect(sections).toContain('Execute');
});
it('should export STATUS_BAR_SHORTCUTS', () => {
expect(STATUS_BAR_SHORTCUTS).toBeDefined();
expect(STATUS_BAR_SHORTCUTS).toContain('browse');
expect(STATUS_BAR_SHORTCUTS).toContain('help');
expect(STATUS_BAR_SHORTCUTS).toContain('quit');
});
});
describe('theme/colors', () => {
it('should export terminalColors', () => {
expect(terminalColors).toBeDefined();
expect(terminalColors.text).toBeDefined();
expect(terminalColors.textMuted).toBeDefined();
expect(terminalColors.accent).toBeDefined();
});
});
describe('theme/symbols', () => {
it('should export symbols', () => {
expect(symbols).toBeDefined();
expect(symbols.brandIcon).toBeDefined();
expect(symbols.pointer).toBeDefined();
expect(symbols.horizontalLine).toBeDefined();
});
it('should export AGENT_LOGOS', () => {
expect(AGENT_LOGOS).toBeDefined();
expect(AGENT_LOGOS['claude-code']).toBeDefined();
expect(AGENT_LOGOS['claude-code'].name).toBe('Claude Code');
});
});
describe('utils/helpers', () => {
it('should return version string', () => {
const version = getVersion();
expect(typeof version).toBe('string');
expect(version.length).toBeGreaterThan(0);
});
it('should return search directories', () => {
const dirs = getSearchDirs();
expect(Array.isArray(dirs)).toBe(true);
});
it('should return install directory', () => {
const dir = getInstallDir();
expect(typeof dir).toBe('string');
});
});
});
+68
View File
@@ -0,0 +1,68 @@
/**
* AgentGrid Component
* Displays monochromatic agent logos in a grid layout
*/
import { AGENT_LOGOS, type AgentLogo } from '../theme/symbols.js';
import { terminalColors } from '../theme/colors.js';
interface AgentGridProps {
/** Maximum number of agents to display */
maxVisible?: number;
/** Show status indicators for detected agents */
showStatus?: boolean;
/** Agent types that are detected/active */
detectedAgents?: string[];
/** Number of columns in the grid */
columns?: number;
}
export function AgentGrid({
maxVisible = 12,
showStatus = true,
detectedAgents = [],
columns = 4,
}: AgentGridProps) {
const safeColumns = Math.max(1, columns);
const allAgents = Object.entries(AGENT_LOGOS);
const visibleAgents = allAgents.slice(0, maxVisible);
const hiddenCount = allAgents.length - maxVisible;
const rows: [string, AgentLogo][][] = [];
for (let i = 0; i < visibleAgents.length; i += safeColumns) {
rows.push(visibleAgents.slice(i, i + safeColumns));
}
return (
<box flexDirection="column">
<text fg={terminalColors.text}>
<b>Works with</b>
</text>
<text> </text>
{rows.map((row, rowIndex) => (
<box key={`row-${rowIndex}`} flexDirection="row">
{row.map(([agentType, agent]) => {
const isDetected = detectedAgents.includes(agentType);
const statusIcon = showStatus ? (isDetected ? '●' : '○') : '';
const fg = isDetected ? terminalColors.accent : terminalColors.text;
return (
<box key={agentType} width={18}>
<text fg={fg}>
{agent.icon} {agent.name}
{showStatus && (
<span fg={isDetected ? terminalColors.success : terminalColors.textMuted}>
{' '}{statusIcon}
</span>
)}
</text>
</box>
);
})}
</box>
))}
{hiddenCount > 0 && (
<text fg={terminalColors.textMuted}>+{hiddenCount} more agents</text>
)}
</box>
);
}
@@ -0,0 +1,44 @@
/**
* FeatureList Component
* Colored feature keywords with descriptions
*/
import { terminalColors } from '../theme/colors.js';
interface Feature {
key: string;
label: string;
description: string;
color: keyof typeof terminalColors;
}
const FEATURES: Feature[] = [
{ key: 'sync', label: 'Sync', color: 'sync', description: 'share skills across all your coding agents' },
{ key: 'browse', label: 'Browse', color: 'browse', description: 'discover skills from the marketplace' },
{ key: 'recommend', label: 'Recommend', color: 'recommend', description: 'AI-powered skill suggestions for your project' },
{ key: 'translate', label: 'Translate', color: 'translate', description: 'convert skills between agent formats' },
{ key: 'workflow', label: 'Workflow', color: 'workflow', description: 'automate skill execution chains' },
{ key: 'team', label: 'Team', color: 'team', description: 'collaborate with your development team' },
];
interface FeatureListProps {
features?: Feature[];
}
export function FeatureList({ features = FEATURES }: FeatureListProps) {
return (
<box flexDirection="column">
<text fg={terminalColors.text}><b>Features</b></text>
<text> </text>
{features.map((feat) => (
<box key={feat.key} flexDirection="row">
<text fg={terminalColors[feat.color]}>
<b>{' '}{feat.label.padEnd(12)}</b>
</text>
<text fg={terminalColors.textMuted}>{feat.description}</text>
</box>
))}
</box>
);
}
export { FEATURES, type Feature };
+21 -16
View File
@@ -1,30 +1,35 @@
import { Box, Text } from 'ink';
import { colors, symbols } from '../theme.js';
/**
* Header Component
* Screen header with title and optional badge/count
*/
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
interface HeaderProps {
title: string;
subtitle?: string;
count?: number;
badge?: string;
icon?: string;
}
export function Header({ title, subtitle, count }: HeaderProps) {
export function Header({ title, subtitle, count, badge, icon }: HeaderProps) {
return (
<Box flexDirection="column" marginBottom={1}>
<Box justifyContent="space-between">
<Text color={colors.primary} bold>
{title.toUpperCase()}
</Text>
<box flexDirection="column" marginBottom={1}>
<box flexDirection="row" gap={2}>
<text fg={terminalColors.text}>
<b>{icon && `${icon} `}{title}</b>
</text>
{count !== undefined && (
<Text color={colors.secondaryDim}>
{symbols.star} {count}
</Text>
<text fg={terminalColors.textMuted}>({count})</text>
)}
</Box>
{badge && (
<text fg={terminalColors.accent}>[{badge}]</text>
)}
</box>
{subtitle && (
<Text color={colors.secondaryDim} dimColor>
{subtitle}
</Text>
<text fg={terminalColors.textSecondary}>{subtitle}</text>
)}
</Box>
</box>
);
}
@@ -0,0 +1,41 @@
/**
* ProgressBar Component
* Animated progress bar display
*/
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
interface ProgressBarProps {
progress: number; // 0-100
width?: number;
showPercentage?: boolean;
color?: keyof typeof terminalColors;
}
export function ProgressBar({
progress,
width = 20,
showPercentage = true,
color = 'accent',
}: ProgressBarProps) {
const clampedProgress = Math.max(0, Math.min(100, progress));
const filledWidth = Math.round((clampedProgress / 100) * width);
const emptyWidth = width - filledWidth;
const filled = symbols.progressFilled.repeat(filledWidth);
const empty = symbols.progressEmpty.repeat(emptyWidth);
return (
<box flexDirection="row" gap={1}>
<text>
<span fg={terminalColors[color]}>{filled}</span>
<span fg={terminalColors.textMuted}>{empty}</span>
</text>
{showPercentage && (
<text fg={terminalColors.textSecondary}>
{Math.round(clampedProgress)}%
</text>
)}
</box>
);
}
+17 -28
View File
@@ -1,40 +1,29 @@
import { Box, Text } from 'ink';
import TextInput from 'ink-text-input';
import { colors } from '../theme.js';
/**
* SearchInput Component
* Rounded search input with icon
*/
import { terminalColors } from '../theme/colors.js';
interface SearchInputProps {
value: string;
onChange: (value: string) => void;
placeholder?: string;
isFocused?: boolean;
focused?: boolean;
onChange?: (value: string) => void;
}
export function SearchInput({
value,
onChange,
placeholder = 'Search skills...',
isFocused = false,
placeholder = 'Search...',
focused = false,
}: SearchInputProps) {
const display = value || placeholder;
const textColor = value ? terminalColors.text : terminalColors.textMuted;
return (
<Box
borderStyle="single"
borderColor={isFocused ? colors.primary : colors.borderDim}
paddingX={1}
>
<Text color={colors.secondaryDim}>/ </Text>
{isFocused ? (
<TextInput
value={value}
onChange={onChange}
placeholder={placeholder}
/>
) : (
<Text color={value ? colors.secondary : colors.secondaryDim}>
{value || placeholder}
</Text>
)}
<Box flexGrow={1} />
<Text color={colors.secondaryDim}>/</Text>
</Box>
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted}>&#x2315; </text>
<text fg={textColor}>{display}</text>
{focused && <text fg={terminalColors.accent}>&#x258F;</text>}
</box>
);
}
+31 -87
View File
@@ -1,100 +1,44 @@
import { Box, Text } from 'ink';
import { colors, symbols } from '../theme.js';
import type { Screen } from '../App.js';
import { type Screen, SIDEBAR_NAV } from '../state/types.js';
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
import { getVersion } from '../utils/helpers.js';
interface SidebarProps {
screen: Screen;
onNavigate: (screen: Screen) => void;
isCompact?: boolean;
}
const NAV: { id: Screen; label: string; key: string }[] = [
// Discovery
{ id: 'home', label: 'Home', key: 'h' },
{ id: 'marketplace', label: 'Marketplace', key: 'm' },
{ id: 'browse', label: 'Browse', key: 'b' },
// Execution
{ id: 'workflow', label: 'Workflows', key: 'w' },
{ id: 'execute', label: 'Execute', key: 'x' },
{ id: 'history', label: 'History', key: 'y' },
// Collaboration
{ id: 'team', label: 'Team', key: 'a' },
{ id: 'plugins', label: 'Plugins', key: 'p' },
// Methodology
{ id: 'methodology', label: 'Methodology', key: 'o' },
{ id: 'plan', label: 'Plans', key: 'n' },
// Tools
{ id: 'recommend', label: 'Recommend', key: 'r' },
{ id: 'translate', label: 'Translate', key: 't' },
{ id: 'context', label: 'Context', key: 'c' },
{ id: 'memory', label: 'Memory', key: 'e' },
// Management
{ id: 'installed', label: 'Installed', key: 'i' },
{ id: 'sync', label: 'Sync', key: 's' },
{ id: 'settings', label: 'Config', key: ',' },
];
export function Sidebar({ screen }: SidebarProps) {
const version = getVersion();
return (
<Box flexDirection="column" width={14} borderStyle="single" paddingX={1}>
<Text bold color={colors.primary}>SkillKit</Text>
<box flexDirection="column" width={18} paddingRight={1}>
<text fg={terminalColors.accent}>
<b>{symbols.brandIcon} skillkit</b>
</text>
<text fg={terminalColors.textMuted}>v{version}</text>
<text> </text>
{/* Discovery (0-2) */}
{NAV.slice(0, 3).map((item) => (
<Text key={item.id} inverse={screen === item.id}>
{screen === item.id ? symbols.bullet : ' '}{item.label}
</Text>
{SIDEBAR_NAV.map(({ section, items }, idx) => (
<box key={section} flexDirection="column">
{idx > 0 && <text> </text>}
<text fg={terminalColors.textMuted}>
<i>{section}</i>
</text>
{items.map((item) => {
const active = screen === item.screen;
return (
<text key={item.key} fg={active ? terminalColors.accent : terminalColors.text}>
{active ? <b>{symbols.pointer} {item.label}</b> : <>{symbols.pointerInactive} {item.label}</>}
</text>
);
})}
</box>
))}
<Text> </Text>
{/* Execution (3-5) */}
{NAV.slice(3, 6).map((item) => (
<Text key={item.id} inverse={screen === item.id}>
{screen === item.id ? symbols.bullet : ' '}{item.label}
</Text>
))}
<Text> </Text>
{/* Collaboration (6-7) */}
{NAV.slice(6, 8).map((item) => (
<Text key={item.id} inverse={screen === item.id}>
{screen === item.id ? symbols.bullet : ' '}{item.label}
</Text>
))}
<Text> </Text>
{/* Methodology (8-9) */}
{NAV.slice(8, 10).map((item) => (
<Text key={item.id} inverse={screen === item.id}>
{screen === item.id ? symbols.bullet : ' '}{item.label}
</Text>
))}
<Text> </Text>
{/* Tools (10-13) */}
{NAV.slice(10, 14).map((item) => (
<Text key={item.id} inverse={screen === item.id}>
{screen === item.id ? symbols.bullet : ' '}{item.label}
</Text>
))}
<Text> </Text>
{/* Management (14-16) */}
{NAV.slice(14).map((item) => (
<Text key={item.id} inverse={screen === item.id}>
{screen === item.id ? symbols.bullet : ' '}{item.label}
</Text>
))}
<Box flexGrow={1} />
<Text dimColor>? Help</Text>
<Text dimColor>q Quit</Text>
</Box>
<box flexGrow={1} />
<text fg={terminalColors.textMuted}>{symbols.horizontalLine.repeat(14)}</text>
<text fg={terminalColors.textMuted}>/ help q quit</text>
</box>
);
}
+39 -73
View File
@@ -1,103 +1,69 @@
import { Box, Text } from 'ink';
import { colors, symbols } from '../theme.js';
export interface SkillItem {
name: string;
description?: string;
source?: string;
installs?: number;
enabled?: boolean;
}
/**
* SkillList Component
* Paginated list of skills with selection
*/
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
import { calculatePagination, type PaginationResult } from '../utils/list.js';
import type { SkillItem } from '../state/types.js';
interface SkillListProps {
skills: SkillItem[];
selectedIndex: number;
showInstalls?: boolean;
showRank?: boolean;
showSource?: boolean;
maxVisible?: number;
}
function formatInstalls(count: number): string {
if (count >= 1000) {
return `${(count / 1000).toFixed(1)}K`;
}
return String(count);
onSelect?: (skill: SkillItem) => void;
}
export function SkillList({
skills,
selectedIndex,
showInstalls = false,
showRank = false,
showSource = true,
maxVisible = 10,
onSelect,
}: SkillListProps) {
if (skills.length === 0) {
return (
<Box>
<Text color={colors.secondaryDim} dimColor>
No skills found
</Text>
</Box>
<text fg={terminalColors.textMuted}>No skills found</text>
);
}
const startIndex = Math.max(0, selectedIndex - Math.floor(maxVisible / 2));
const visibleSkills = skills.slice(startIndex, startIndex + maxVisible);
const actualStartIndex = startIndex;
const pagination = calculatePagination(skills.length, selectedIndex, maxVisible);
const visibleSkills = skills.slice(pagination.start, pagination.end);
return (
<Box flexDirection="column">
{showRank && (
<Box marginBottom={1}>
<Text color={colors.secondaryDim}>
{' # SKILL'}
{showSource && ' SOURCE'}
{showInstalls && ' INSTALLS'}
</Text>
</Box>
<box flexDirection="column">
{/* Items above indicator */}
{pagination.itemsAbove > 0 && (
<text fg={terminalColors.textMuted}>
{symbols.arrowUp} {pagination.itemsAbove} more above
</text>
)}
{/* Skill list */}
{visibleSkills.map((skill, idx) => {
const realIndex = actualStartIndex + idx;
const isSelected = realIndex === selectedIndex;
const skillName = skill.name.padEnd(28).slice(0, 28);
const sourceName = skill.source ? skill.source.slice(0, 25) : '';
const actualIndex = pagination.start + idx;
const isSelected = actualIndex === selectedIndex;
const pointer = isSelected ? symbols.pointer : symbols.pointerInactive;
const fg = isSelected ? terminalColors.accent : terminalColors.text;
const statusIcon = skill.enabled ? symbols.active : symbols.pending;
const descPart = skill.description
? ` - ${skill.description.slice(0, 40)}${skill.description.length > 40 ? '...' : ''}`
: '';
// Use single text element to avoid rendering overlap
const line = `${pointer} ${skill.name} ${statusIcon}${descPart}`;
return (
<Box key={`${skill.source}-${skill.name}`}>
<Text
color={isSelected ? colors.primary : colors.secondary}
bold={isSelected}
inverse={isSelected}
>
{isSelected ? symbols.pointer : ' '}
{showRank ? String(realIndex + 1).padStart(2, ' ') : ''}
{' '}
{skillName}
</Text>
{showSource && (
<Text color={colors.secondaryDim} dimColor={!isSelected}>
{' '}{sourceName}
</Text>
)}
{showInstalls && skill.installs !== undefined && (
<Text color={colors.secondaryDim}>
{formatInstalls(skill.installs).padStart(8)}
</Text>
)}
</Box>
<text key={skill.name} fg={fg}>
{isSelected ? <b>{line}</b> : line}
</text>
);
})}
{skills.length > maxVisible && (
<Box marginTop={1}>
<Text color={colors.secondaryDim} dimColor>
Showing {startIndex + 1}-{Math.min(startIndex + maxVisible, skills.length)} of {skills.length}
</Text>
</Box>
{/* Items below indicator */}
{pagination.itemsBelow > 0 && (
<text fg={terminalColors.textMuted}>
{symbols.arrowDown} {pagination.itemsBelow} more below
</text>
)}
</Box>
</box>
);
}
+30
View File
@@ -0,0 +1,30 @@
/**
* Spinner Component
* Loading indicator with animated frames
*/
import { useState, useEffect } from 'react';
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
interface SpinnerProps {
label?: string;
color?: keyof typeof terminalColors;
}
export function Spinner({ label, color = 'accent' }: SpinnerProps) {
const [frame, setFrame] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setFrame((f) => (f + 1) % symbols.spinner.length);
}, 80);
return () => clearInterval(interval);
}, []);
return (
<box flexDirection="row" gap={1}>
<text fg={terminalColors[color]}>{symbols.spinner[frame]}</text>
{label && <text fg={terminalColors.text}>{label}</text>}
</box>
);
}
+262
View File
@@ -0,0 +1,262 @@
/**
* Splash Component
* Cinematic ASCII art intro with elegant animations
* Premium terminal experience
*/
import { useState, useEffect, useMemo, useCallback } from 'react';
import { terminalColors } from '../theme/colors.js';
import { getVersion } from '../utils/helpers.js';
// Premium ASCII art logo - clean geometric design
const LOGO_FRAMES = [
// Frame 1 - Dots appear
[
' ',
' · · · · · · · · · · · · · · · ',
' ',
],
// Frame 2 - Lines form
[
' ',
' ━━━ ━ ━ ━ ━ ━ ━ ━ ━━━ ',
' ',
],
// Frame 3 - Structure emerges
[
' ┌──┐ ┬ ┌─ ┬ ┬ ┬ ┬ ┌─ ┬ ┌─┐ ',
' └──┐ │ │ │ │ │ │ │ │ │ ',
' └──┘ ┴ └─ ┴ ┴─┘ ┴─┘ ┴ └─ ┴ ┴ ',
],
// Frame 4 - Bold letters
[
' ╔═╗ ╦╔═ ╦ ╦ ╦ ╦╔═ ╦╔╦╗ ',
' ╚═╗ ╠╩╗ ║ ║ ║ ╠╩╗ ║ ║ ',
' ╚═╝ ╩ ╩ ╩ ╩═╝ ╩═╝ ╩ ╩ ╩ ╩ ',
],
// Frame 5 - Final premium logo
[
' ███████╗██╗ ██╗██╗██╗ ██╗ ██╗ ██╗██╗████████╗',
' ██╔════╝██║ ██╔╝██║██║ ██║ ██║ ██╔╝██║╚══██╔══╝',
' ███████╗█████╔╝ ██║██║ ██║ █████╔╝ ██║ ██║ ',
' ╚════██║██╔═██╗ ██║██║ ██║ ██╔═██╗ ██║ ██║ ',
' ███████║██║ ██╗██║███████╗███████╗██║ ██╗██║ ██║ ',
' ╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ',
],
];
// Compact logo for smaller terminals
const LOGO_SMALL = [
' ╔═╗╦╔═╦╦ ╦ ╦╔═╦╔╦╗ ',
' ╚═╗╠╩╗║║ ║ ╠╩╗║ ║ ',
' ╚═╝╩ ╩╩╩═╝╩═╝╩ ╩╩ ╩ ',
];
// Elegant spinner frames
const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
// Progress bar characters
const PROGRESS = {
empty: '░',
filled: '█',
head: '▓',
};
// Loading phases with elegant messaging
const PHASES = [
{ message: 'Initializing', detail: 'skill engine' },
{ message: 'Connecting', detail: 'agent network' },
{ message: 'Loading', detail: 'skill manifests' },
{ message: 'Syncing', detail: 'configurations' },
{ message: 'Ready', detail: '' },
];
interface SplashProps {
onComplete: () => void;
duration?: number;
}
export function Splash({ onComplete, duration = 3500 }: SplashProps) {
const [frame, setFrame] = useState(0);
const [progress, setProgress] = useState(0);
const [spinnerFrame, setSpinnerFrame] = useState(0);
const [phase, setPhase] = useState(0);
const [fadeIn, setFadeIn] = useState(0);
const [particles, setParticles] = useState<string[]>([]);
// Cache version to avoid repeated sync file I/O on every render
const version = useMemo(() => getVersion(), []);
const cols = process.stdout.columns || 80;
const rows = process.stdout.rows || 24;
const useSmallLogo = cols < 70;
const currentLogo = useSmallLogo ? LOGO_SMALL : (LOGO_FRAMES[Math.min(frame, 4)] || LOGO_FRAMES[4]);
const maxWidth = Math.max(...currentLogo.map(l => l.length));
// Generate ambient particles - returns fresh randomized string each call
const generateParticles = useCallback(() => {
const chars = ['·', '∙', '•', '○', '◦', '◌', '◍', '◎'];
return Array(cols).fill(0).map(() =>
Math.random() > 0.97 ? chars[Math.floor(Math.random() * chars.length)] : ' '
).join('');
}, [cols]);
// Logo reveal animation
useEffect(() => {
if (frame >= 4) return;
const timer = setTimeout(() => setFrame(f => f + 1), 200);
return () => clearTimeout(timer);
}, [frame]);
// Fade in effect
useEffect(() => {
if (fadeIn >= 10) return;
const timer = setTimeout(() => setFadeIn(f => f + 1), 50);
return () => clearTimeout(timer);
}, [fadeIn]);
// Progress animation
useEffect(() => {
const interval = setInterval(() => {
setProgress(p => {
const newProgress = p + (Math.random() * 3 + 1);
if (newProgress >= 100) {
clearInterval(interval);
return 100;
}
return newProgress;
});
}, 50);
return () => clearInterval(interval);
}, []);
// Phase progression
useEffect(() => {
const phaseProgress = progress / 20;
setPhase(Math.min(Math.floor(phaseProgress), PHASES.length - 1));
}, [progress]);
// Spinner animation
useEffect(() => {
const interval = setInterval(() => {
setSpinnerFrame(f => (f + 1) % SPINNER.length);
}, 80);
return () => clearInterval(interval);
}, []);
// Particle animation
useEffect(() => {
const interval = setInterval(() => {
setParticles(prev => {
const newParticles = [...prev];
if (newParticles.length > 3) newParticles.shift();
newParticles.push(generateParticles());
return newParticles;
});
}, 150);
return () => clearInterval(interval);
}, [generateParticles]);
// Auto-complete
useEffect(() => {
const timer = setTimeout(onComplete, duration);
return () => clearTimeout(timer);
}, [onComplete, duration]);
const pad = ' '.repeat(Math.max(0, Math.floor((cols - maxWidth) / 2)));
const progressWidth = Math.max(1, Math.min(40, cols - 20));
const progressPad = ' '.repeat(Math.max(0, Math.floor((cols - progressWidth) / 2)));
const filledWidth = Math.min(Math.floor((progress / 100) * progressWidth), progressWidth);
const emptyWidth = Math.max(0, progressWidth - filledWidth - 1);
const progressBar = PROGRESS.filled.repeat(filledWidth) +
(filledWidth < progressWidth ? PROGRESS.head : '') +
PROGRESS.empty.repeat(emptyWidth);
const currentPhase = PHASES[phase];
return (
<box flexDirection="column" height={rows}>
{/* Top ambient particles */}
<text fg={terminalColors.textMuted}>
{particles[0] || ''}
</text>
{/* Spacer */}
<box flexGrow={1} />
{/* Logo */}
<box flexDirection="column" alignItems="center">
{currentLogo.map((line, idx) => (
<text key={idx} fg={frame >= 4 ? terminalColors.accent : terminalColors.textMuted}>
{frame >= 4 ? <b>{pad}{line}</b> : <>{pad}{line}</>}
</text>
))}
</box>
{/* Tagline with fade-in */}
<text> </text>
{fadeIn > 3 && (
<text fg={terminalColors.textSecondary}>
{pad}{' '}universal skills for ai coding agents
</text>
)}
{/* Version badge */}
{fadeIn > 5 && (
<>
<text> </text>
<text fg={terminalColors.textMuted}>
{pad}{' '}v{version}
</text>
</>
)}
{/* Spacer */}
<text> </text>
<text> </text>
{/* Progress section */}
{fadeIn > 7 && (
<box flexDirection="column" alignItems="center">
{/* Status line */}
<box flexDirection="row">
<text fg={terminalColors.accent}>
{progressPad}{SPINNER[spinnerFrame]}{' '}
</text>
<text fg={terminalColors.text}>
<b>{currentPhase.message}</b>
</text>
{currentPhase.detail && (
<text fg={terminalColors.textMuted}>
{' '}{currentPhase.detail}
</text>
)}
</box>
{/* Progress bar */}
<text> </text>
<box flexDirection="row">
<text fg={terminalColors.textMuted}>{progressPad}[</text>
<text fg={terminalColors.accent}>{progressBar}</text>
<text fg={terminalColors.textMuted}>]</text>
<text fg={terminalColors.textSecondary}>{' '}{Math.floor(progress)}%</text>
</box>
</box>
)}
{/* Spacer */}
<box flexGrow={1} />
{/* Bottom hint */}
<box flexDirection="column" alignItems="center">
<text fg={terminalColors.textMuted}>
{progressPad}{' '}press any key to skip
</text>
<text> </text>
{/* Bottom particles */}
<text fg={terminalColors.textMuted}>
{particles[1] || ''}
</text>
</box>
</box>
);
}
+88
View File
@@ -0,0 +1,88 @@
/**
* StatsCard Component
* OpenSync-style stats display with optional animations
*/
import { useState, useEffect } from 'react';
import { terminalColors } from '../theme/colors.js';
import { animations } from '../theme/animations.js';
interface StatItem {
label: string;
value: number;
color?: keyof typeof terminalColors;
}
interface StatsCardProps {
items: StatItem[];
animated?: boolean;
}
export function StatsCard({ items, animated = true }: StatsCardProps) {
const [displayValues, setDisplayValues] = useState<number[]>(() =>
animated ? items.map(() => 0) : items.map((item) => item.value)
);
const [animComplete, setAnimComplete] = useState(!animated);
const [prevItemsLength, setPrevItemsLength] = useState(items.length);
useEffect(() => {
if (items.length !== prevItemsLength) {
setPrevItemsLength(items.length);
setDisplayValues(animated ? items.map(() => 0) : items.map((item) => item.value));
setAnimComplete(!animated);
}
}, [items, prevItemsLength, animated]);
useEffect(() => {
if (!animated || animComplete) return;
const duration = animations.countUp.duration;
const startTime = Date.now();
const targetValues = items.map((item) => item.value);
const frameInterval = 16;
const intervalId = setInterval(() => {
const elapsed = Date.now() - startTime;
const progress = Math.min(elapsed / duration, 1);
const eased = 1 - Math.pow(1 - progress, 4);
const newValues = targetValues.map((target) =>
Math.round(target * eased)
);
setDisplayValues(newValues);
if (progress >= 1) {
clearInterval(intervalId);
setAnimComplete(true);
}
}, frameInterval);
return () => clearInterval(intervalId);
}, [animated, animComplete, items]);
return (
<box flexDirection="row" gap={2}>
{items.map((item, index) => {
const fg = item.color
? terminalColors[item.color]
: terminalColors.text;
return (
<box
key={item.label}
flexDirection="column"
alignItems="center"
padding={2}
borderStyle="single"
borderColor={terminalColors.border}
>
<text fg={fg}>
<b>{String(displayValues[index])}</b>
</text>
<text fg={terminalColors.textMuted}>{item.label}</text>
</box>
);
})}
</box>
);
}
+29 -35
View File
@@ -1,44 +1,38 @@
import { Box, Text } from 'ink';
import { colors, symbols } from '../theme.js';
interface Shortcut {
key: string;
label: string;
}
/**
* StatusBar Component
* Bottom status bar with keyboard shortcuts
*/
import { terminalColors } from '../theme/colors.js';
import { STATUS_BAR_SHORTCUTS } from '../state/types.js';
interface StatusBarProps {
shortcuts: Shortcut[];
message?: string;
messageType?: 'info' | 'success' | 'error' | 'warning';
shortcuts?: string;
}
export function StatusBar({ shortcuts, message }: StatusBarProps) {
return (
<Box
borderStyle="single"
borderColor={colors.borderDim}
borderTop
borderBottom={false}
borderLeft={false}
borderRight={false}
paddingX={1}
justifyContent="space-between"
>
<Box gap={2}>
{shortcuts.map((shortcut, idx) => (
<Box key={idx} gap={1}>
<Text color={colors.primary} bold>
{shortcut.key}
</Text>
<Text color={colors.secondaryDim}>{shortcut.label}</Text>
</Box>
))}
</Box>
export function StatusBar({
message,
messageType = 'info',
shortcuts = STATUS_BAR_SHORTCUTS,
}: StatusBarProps) {
const messageColors = {
info: terminalColors.info,
success: terminalColors.success,
error: terminalColors.error,
warning: terminalColors.warning,
};
{message && (
<Text color={colors.success}>
{symbols.check} {message}
</Text>
return (
<box flexDirection="column">
<text fg={terminalColors.textMuted}>
{'\u2500'.repeat(70)}
</text>
{message ? (
<text fg={messageColors[messageType]}>{message}</text>
) : (
<text fg={terminalColors.textMuted}>{shortcuts}</text>
)}
</Box>
</box>
);
}
+12 -2
View File
@@ -1,5 +1,15 @@
export { Sidebar } from './Sidebar.js';
/**
* Components module for SkillKit TUI
*/
export { AgentGrid } from './AgentGrid.js';
export { StatsCard } from './StatsCard.js';
export { Header } from './Header.js';
export { SkillList, type SkillItem } from './SkillList.js';
export { Sidebar } from './Sidebar.js';
export { StatusBar } from './StatusBar.js';
export { SkillList } from './SkillList.js';
export { SearchInput } from './SearchInput.js';
export { Spinner } from './Spinner.js';
export { ProgressBar } from './ProgressBar.js';
export { FeatureList, FEATURES, type Feature } from './FeatureList.js';
export { Splash } from './Splash.js';
-36
View File
@@ -1,36 +0,0 @@
// Re-export commonly used functions with proper adapters
import {
loadConfig,
getSearchDirs as coreGetSearchDirs,
getInstallDir as coreGetInstallDir,
saveSkillMetadata as coreSaveSkillMetadata,
} from '@skillkit/core';
import { getAdapter } from '@skillkit/agents';
import type { AgentType, AgentAdapterInfo } from '@skillkit/core';
// Re-export for direct use
export { coreSaveSkillMetadata as saveSkillMetadata };
export function getSearchDirs(agentType?: AgentType): string[] {
const type = agentType || loadConfig().agent;
const adapter = getAdapter(type);
const adapterInfo: AgentAdapterInfo = {
type: adapter.type,
name: adapter.name,
skillsDir: adapter.skillsDir,
configFile: adapter.configFile,
};
return coreGetSearchDirs(adapterInfo);
}
export function getInstallDir(global = false, agentType?: AgentType): string {
const type = agentType || loadConfig().agent;
const adapter = getAdapter(type);
const adapterInfo: AgentAdapterInfo = {
type: adapter.type,
name: adapter.name,
skillsDir: adapter.skillsDir,
configFile: adapter.configFile,
};
return coreGetInstallDir(adapterInfo, global);
}
-5
View File
@@ -1,5 +0,0 @@
export { useSkills } from './useSkills.js';
export { useMarketplace } from './useMarketplace.js';
export { useKeyboard, useListNavigation } from './useKeyboard.js';
export { useRecommend } from './useRecommend.js';
export { useMemory } from './useMemory.js';
-93
View File
@@ -1,93 +0,0 @@
import { useState, useCallback, useEffect } from 'react';
import { useInput, useApp } from 'ink';
import type { Screen } from '../App.js';
interface UseKeyboardOptions {
onNavigate?: (screen: Screen) => void;
onSelect?: () => void;
onSearch?: () => void;
onInstall?: () => void;
onBack?: () => void;
onUp?: () => void;
onDown?: () => void;
disabled?: boolean;
}
export function useKeyboard(options: UseKeyboardOptions = {}) {
const { exit } = useApp();
useInput((input, key) => {
if (options.disabled) return;
if (input === 'q' || (key.ctrl && input === 'c')) {
exit();
return;
}
if (key.escape && options.onBack) {
options.onBack();
return;
}
if (key.return && options.onSelect) {
options.onSelect();
return;
}
if (key.upArrow && options.onUp) {
options.onUp();
return;
}
if (key.downArrow && options.onDown) {
options.onDown();
return;
}
if (input === '/' && options.onSearch) {
options.onSearch();
return;
}
if (input === 'i' && options.onInstall) {
options.onInstall();
return;
}
if (input === 'h' && options.onNavigate) {
options.onNavigate('home');
} else if (input === 'b' && options.onNavigate) {
options.onNavigate('browse');
} else if (input === 'l' && options.onNavigate) {
options.onNavigate('installed');
} else if (input === 's' && options.onNavigate) {
options.onNavigate('sync');
} else if (input === ',' && options.onNavigate) {
options.onNavigate('settings');
}
});
}
export function useListNavigation(listLength: number, initialIndex = 0) {
const [selectedIndex, setSelectedIndex] = useState(initialIndex);
useEffect(() => {
if (selectedIndex >= listLength && listLength > 0) {
setSelectedIndex(listLength - 1);
}
}, [listLength, selectedIndex]);
const moveUp = useCallback(() => {
setSelectedIndex((prev) => Math.max(0, prev - 1));
}, []);
const moveDown = useCallback(() => {
setSelectedIndex((prev) => Math.min(listLength - 1, prev + 1));
}, [listLength]);
const reset = useCallback(() => {
setSelectedIndex(0);
}, []);
return { selectedIndex, setSelectedIndex, moveUp, moveDown, reset };
}
-251
View File
@@ -1,251 +0,0 @@
import { useState, useCallback, useEffect } from 'react';
import { detectProvider, loadConfig, extractFrontmatter } from '@skillkit/core';
import { readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import type { SkillItem } from '../components/SkillList.js';
export interface RepoInfo {
source: string;
name: string;
}
// Default popular repos - can be extended via config.marketplaceSources
const DEFAULT_REPOS: RepoInfo[] = [
{ source: 'anthropics/skills', name: 'Anthropic Official' },
{ source: 'vercel-labs/agent-skills', name: 'Vercel Labs' },
{ source: 'expo/skills', name: 'Expo / React Native' },
{ source: 'remotion-dev/skills', name: 'Remotion Video' },
{ source: 'ComposioHQ/awesome-claude-skills', name: 'Composio Awesome' },
{ source: 'travisvn/awesome-claude-skills', name: 'Travis Awesome' },
{ source: 'mhattingpete/claude-skills-marketplace', name: 'Skills Marketplace' },
{ source: 'coreyhaines31/marketingskills', name: 'Marketing Skills' },
{ source: 'obra/superpowers', name: 'Superpowers TDD' },
{ source: 'softaworks/agent-toolkit', name: 'Softaworks Toolkit' },
{ source: 'wshobson/agents', name: 'Dev Patterns' },
{ source: 'langgenius/dify', name: 'Dify Frontend' },
{ source: 'trailofbits/skills', name: 'Trail of Bits Security' },
{ source: 'better-auth/skills', name: 'Better Auth' },
{ source: 'onmax/nuxt-skills', name: 'Nuxt / Vue' },
{ source: 'hyf0/vue-skills', name: 'Vue Best Practices' },
{ source: 'jezweb/claude-skills', name: 'Cloudflare / TanStack' },
{ source: 'elysiajs/skills', name: 'ElysiaJS / Bun' },
{ source: 'kadajett/agent-nestjs-skills', name: 'NestJS' },
{ source: 'callstackincubator/agent-skills', name: 'React Native' },
{ source: 'cloudai-x/threejs-skills', name: 'Three.js' },
{ source: 'emalorenzo/three-agent-skills', name: 'Three.js Advanced' },
{ source: 'dimillian/skills', name: 'SwiftUI iOS' },
{ source: 'stripe/ai', name: 'Stripe Payments' },
{ source: 'waynesutton/convexskills', name: 'Convex Backend' },
{ source: 'kepano/obsidian-skills', name: 'Obsidian Notes' },
{ source: 'jimliu/baoyu-skills', name: 'Baoyu Tools' },
{ source: 'giuseppe-trisciuoglio/developer-kit', name: 'Shadcn / Radix' },
{ source: 'openrouterteam/agent-skills', name: 'OpenRouter SDK' },
{ source: 'intellectronica/agent-skills', name: 'Context7' },
];
/**
* Get marketplace repos from config or use defaults
*/
function getMarketplaceRepos(): RepoInfo[] {
try {
const config = loadConfig();
if (config.marketplaceSources?.length) {
// Merge config sources with defaults, config takes priority
const configRepos: RepoInfo[] = config.marketplaceSources.map(source => ({
source,
name: source.split('/').pop() || source,
}));
// Add defaults that aren't in config
const existingSources = new Set(configRepos.map(r => r.source));
for (const repo of DEFAULT_REPOS) {
if (!existingSources.has(repo.source)) {
configRepos.push(repo);
}
}
return configRepos;
}
} catch {
// Config load failed, use defaults
}
return DEFAULT_REPOS;
}
/**
* Try to read skill description from frontmatter
*/
function readSkillDescription(skillPath: string): string | undefined {
const skillMdPath = join(skillPath, 'SKILL.md');
if (!existsSync(skillMdPath)) {
return undefined;
}
try {
const content = readFileSync(skillMdPath, 'utf-8');
const frontmatter = extractFrontmatter(content);
if (frontmatter && typeof frontmatter.description === 'string') {
return frontmatter.description;
}
} catch {
// Failed to read, return undefined
}
return undefined;
}
interface FetchedSkill {
name: string;
source: string;
repoName: string;
description?: string;
}
interface UseMarketplaceResult {
skills: SkillItem[];
loading: boolean;
error: string | null;
totalCount: number;
repos: RepoInfo[];
currentRepo: string | null;
failedRepos: string[];
refresh: () => void;
search: (query: string) => void;
fetchRepo: (source: string) => Promise<void>;
fetchAllRepos: () => Promise<void>;
}
export function useMarketplace(): UseMarketplaceResult {
const [allSkills, setAllSkills] = useState<FetchedSkill[]>([]);
const [filteredSkills, setFilteredSkills] = useState<FetchedSkill[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [currentRepo, setCurrentRepo] = useState<string | null>(null);
const [fetchedRepos, setFetchedRepos] = useState<Set<string>>(new Set());
const [failedRepos, setFailedRepos] = useState<string[]>([]);
const [repos] = useState<RepoInfo[]>(() => getMarketplaceRepos());
const fetchRepo = useCallback(async (source: string) => {
if (fetchedRepos.has(source)) return;
setLoading(true);
setError(null);
setCurrentRepo(source);
try {
const provider = detectProvider(source);
if (!provider) {
throw new Error(`Could not detect provider for: ${source}`);
}
const result = await provider.clone(source, '', { depth: 1 });
if (!result.success || !result.discoveredSkills) {
throw new Error(result.error || 'Failed to fetch skills');
}
const repoName = repos.find(r => r.source === source)?.name || source;
const newSkills: FetchedSkill[] = result.discoveredSkills.map(skill => ({
name: skill.name,
source: source,
repoName: repoName,
// Try to read description from skill frontmatter
description: readSkillDescription(skill.path),
}));
setAllSkills(prev => {
const updated = [...prev, ...newSkills];
return updated.sort((a, b) => a.name.localeCompare(b.name));
});
setFetchedRepos(prev => new Set([...prev, source]));
if (result.tempRoot) {
const { rmSync } = await import('node:fs');
rmSync(result.tempRoot, { recursive: true, force: true });
}
} catch (err) {
const errorMsg = err instanceof Error ? err.message : 'Failed to fetch repository';
setError(errorMsg);
// Track failed repos for display
setFailedRepos(prev => prev.includes(source) ? prev : [...prev, source]);
} finally {
setLoading(false);
setCurrentRepo(null);
}
}, [fetchedRepos, repos]);
const fetchAllRepos = useCallback(async () => {
setLoading(true);
setError(null);
const failures: string[] = [];
for (const repo of repos) {
if (!fetchedRepos.has(repo.source)) {
setCurrentRepo(repo.source);
try {
await fetchRepo(repo.source);
} catch (err) {
// Track which repos failed
failures.push(repo.source);
}
}
}
// Update failed repos list
if (failures.length > 0) {
setFailedRepos(prev => {
const combined = [...prev, ...failures];
return [...new Set(combined)]; // deduplicate
});
}
setLoading(false);
setCurrentRepo(null);
}, [fetchRepo, fetchedRepos, repos]);
const search = useCallback((query: string) => {
if (!query.trim()) {
setFilteredSkills(allSkills);
} else {
const lowerQuery = query.toLowerCase();
setFilteredSkills(
allSkills.filter(
(s) =>
s.name.toLowerCase().includes(lowerQuery) ||
s.source.toLowerCase().includes(lowerQuery) ||
s.repoName.toLowerCase().includes(lowerQuery) ||
s.description?.toLowerCase().includes(lowerQuery)
)
);
}
}, [allSkills]);
const refresh = useCallback(() => {
setFetchedRepos(new Set());
setAllSkills([]);
setFilteredSkills([]);
setFailedRepos([]);
setError(null);
}, []);
useEffect(() => {
setFilteredSkills(allSkills);
}, [allSkills]);
const skills: SkillItem[] = filteredSkills.map((s) => ({
name: s.name,
description: s.description || s.repoName,
source: s.source,
}));
return {
skills,
loading,
error,
totalCount: allSkills.length,
repos,
currentRepo,
failedRepos,
refresh,
search,
fetchRepo,
fetchAllRepos,
};
}

Some files were not shown because too many files have changed in this diff Show More