Compare commits

...
Author SHA1 Message Date
Rohit Ghumare de4425f440 chore: release v1.9.0 (#38)
Features:
- Hierarchical skill tree with 12 categories (skillkit tree)
- LLM-based reasoning engine for skill discovery
- Explainable recommendations (--explain, --reasoning flags)
- Connector placeholders for tool-agnostic skills (~~CRM, ~~chat, etc.)
- Execution flow tracking with metrics
- Standalone vs Enhanced mode detection

CLI:
- New `tree` command for taxonomy navigation
- Enhanced `recommend` with explanation support
- Fixed --skill alias and agent detection

Documentation:
- Added tree.mdx for Skill Tree documentation
- Updated recommendations.mdx with reasoning features
- Updated TUI docs with tree view mode
- Updated README with new features
- Updated website Features and Commands
2026-02-02 16:48:43 +00:00
Rohit Ghumare 8121c2bbac feat(core): add PageIndex-inspired patterns for skill discovery (#37)
* feat(core): add PageIndex-inspired patterns for skill discovery

Implements patterns from anthropics/knowledge-work-plugins:

Tree Module (packages/core/src/tree/):
- Hierarchical skill taxonomy with 12 categories
- Tree generator from skill tags and metadata
- Tree serializer for JSON/Markdown export
- Related skills graph with 4 relation types

Reasoning Engine (packages/core/src/reasoning/):
- LLM-based tree traversal for skill discovery
- Explainable recommendations with reasoning chains
- Search planning with category relevance scoring
- Result caching with 5-minute TTL

Connectors (packages/core/src/connectors/):
- Tool-agnostic ~~ placeholder system
- 13 connector categories (crm, chat, email, etc.)
- Auto-suggest mappings from MCP config
- Placeholder detection and replacement utilities

Execution Flow (packages/core/src/execution/):
- Step-by-step execution tracking with metrics
- Automatic retry with exponential backoff
- Standalone vs Enhanced mode detection
- Capability-based feature gating

CLI Integration:
- New `skillkit tree` command with --generate, --stats flags
- Enhanced `skillkit recommend` with --explain, --reasoning flags

TUI Integration:
- Tree view mode in Marketplace (toggle with 'v')
- Arrow key navigation for tree hierarchy

* fix: address CodeRabbit and Devin review feedback

- Use os.homedir() instead of process.env.HOME || '~' fallback
  (tree.ts, tree.service.ts, mode.ts)
- Add guard for division by zero in tree stats percentage
- Validate parseInt result for --depth flag
- Fix average stats calculation to use cacheMisses count
- Extract category from data in validateCategoryScore
- Remove unused skillMap field from TreeGenerator
- Make reasoning provider configurable instead of hardcoded
- Add try/catch for tree loading errors in Marketplace
- Handle missing tree nodes during traversal

* fix(execution): clear timeout timer to prevent resource leak

Store setTimeout ID and clear it in finally block when step
completes successfully before timeout. This prevents orphaned
timers from accumulating during long-running applications.
2026-02-02 16:18:13 +00:00
Rohit Ghumare 3565daa7f1 fix(cli): add --skill alias and fix agent detection
- Add --skill as alias for --skills option (install command)
- Fix sync command to always detect agent instead of using default 'universal'
- Auto-install npm dependencies for skills with package.json
2026-02-02 12:07:41 +00:00
Rohit Ghumare 8496e3c63c feat(publish): add RFC 8615 well-known skills support (#36)
* feat(agents): add skill-to-subagent converter command

Add `skillkit agent from-skill` command to convert SkillKit skills into
Claude Code native subagent format (.md files in .claude/agents/).

Features:
- Reference mode (default): generates subagent with `skills: [skill-name]`
- Inline mode (--inline): embeds full skill content in system prompt
- Options: --model, --permission, --global, --output, --dry-run

New files:
- packages/core/src/agents/skill-converter.ts
- packages/core/src/agents/__tests__/skill-converter.test.ts (23 tests)

Closes #22

* feat(publish): add RFC 8615 well-known skills support

Redesign publish workflow to align with industry standard:

- Add WellKnownProvider for auto-discovery from any domain
- skillkit add https://example.com discovers skills via /.well-known/skills/
- skillkit publish generates well-known hosting structure
- skillkit publish submit opens GitHub issue (legacy workflow)

Provider discovers skills from:
- /.well-known/skills/index.json (manifest)
- /.well-known/skills/{skill-name}/SKILL.md (skill files)

Includes 16 tests for WellKnownProvider and structure generation.

* fix(wellknown): correct baseSkillsUrl calculation for skills.json fallback

When using the /.well-known/skills.json fallback URL, the previous
logic produced a malformed URL with duplicated .well-known path segment:
- Before: https://example.com/.well-known/.well-known/skills
- After: https://example.com/.well-known/skills

Extract calculateBaseSkillsUrl helper function for better testability
and add 4 new unit tests covering both URL formats.

* docs: update publish command documentation for well-known skills

- README.md: Add self-hosting section with well-known URI structure
- commands.mdx: Add Publishing Commands section
- marketplace.mdx: Expand publish section with self-hosting instructions
- skills.mdx: Add self-hosting workflow documentation

Documents the new `skillkit publish` workflow that generates RFC 8615
well-known URI structures for decentralized skill hosting.

* fix(security): address path traversal and CRLF vulnerabilities

- agent.ts: Sanitize skill.name when building default filename
- publish.ts: Add sanitizeSkillName() to validate skill names before
  using in file paths, verify resolved paths stay within target dir
- skill-converter.ts: Normalize CRLF to LF before extracting body
  content to handle Windows-style line endings
- wellknown.ts: Add sanitizeSkillName() to validate remote skill names,
  verify resolved paths stay within temp dir, encode URL components

* fix(agents): improve YAML string escaping logic

Only escape strings that actually need it for valid YAML parsing:
- Strings containing newlines or colons
- Strings starting with special YAML characters (-, *, &, !, {, [, >, |, @, `)
- Strings starting with quotes

This fixes unnecessary escaping of strings like "code-quality" where
hyphens in the middle don't need escaping.

* fix(wellknown): address security review feedback

- Use path.sep instead of hardcoded '/' for cross-platform compatibility
- Add sanitization and path containment check in generateWellKnownStructure
- Remove unused 'vi' import in wellknown.test.ts
2026-02-01 21:38:42 +00:00
Rohit Ghumare 847af0f7ab feat(agents): add skill-to-subagent converter command (#34)
* feat(agents): add skill-to-subagent converter command

Add `skillkit agent from-skill` command to convert SkillKit skills into
Claude Code native subagent format (.md files in .claude/agents/).

Features:
- Reference mode (default): generates subagent with `skills: [skill-name]`
- Inline mode (--inline): embeds full skill content in system prompt
- Options: --model, --permission, --global, --output, --dry-run

New files:
- packages/core/src/agents/skill-converter.ts
- packages/core/src/agents/__tests__/skill-converter.test.ts (23 tests)

Closes #22

* fix(agents): address code review feedback

- Update CLI option descriptions to list all valid values (model: inherit, permission: bypassPermissions)
- Add filename sanitization to prevent path traversal attacks via --output
- Fix parseAllowedTools to handle both string and YAML array formats
- Support space-separated tool lists in allowed-tools
- Add tests for array and space-separated formats
2026-02-01 20:00:11 +00:00
Rohit Ghumare 34e8cd0b61 docs(tui): update documentation for Solid.js migration (#33)
Update TUI documentation to reflect the v1.8.0 migration from React to
Solid.js:

- Change @opentui/react to @opentui/solid
- Change React 19.0.0 to Solid.js 1.9.0
- Add note about migration rationale (performance, bundle size)
- Update performance optimizations section with Solid.js primitives
  (createMemo, createSignal, createEffect)
- Add windowed list rendering mention
- Update Integration section with Solid.js code example
- Update graceful exit to reference onCleanup instead of React unmount
2026-02-01 17:55:45 +00:00
Rohit Ghumare cbd9fcd679 chore: fix version mismatch in root and docs packages 2026-02-01 17:34:40 +00:00
Rohit Ghumare f9e31fedc8 chore: bump version to 1.8.1 2026-02-01 17:33:24 +00:00
Rohit Ghumare 12ed10d170 refactor(tui): migrate to OpenTUI/Solid.js framework (#32)
* refactor(tui): migrate to OpenTUI/Solid.js framework

Complete TUI rewrite from Ink/React to OpenTUI/Solid.js:

- Replace React with Solid.js for reactive state management
- Migrate all 20 screens to OpenTUI component primitives
- Add monochromatic design with 14 color themes
- Implement cinematic splash screen with ASCII animation
- Add vi-key navigation (j/k/h/l) throughout
- Create 32 reusable components with consistent styling
- Add service layer for @skillkit/core API integration
- Remove deprecated react-opentui.d.ts type definitions
- Update build config for Solid.js JSX transform

Features covered:
- Browse, Marketplace, Recommend (discovery)
- Installed, Sync, Translate (management)
- Workflow, Execute, Plan, History (execution)
- Team, Context, Memory, Mesh, Message (collaboration)
- Plugins, Methodology, Settings (configuration)
- Help screen with 25+ keyboard shortcuts

* fix(tui): address CodeRabbit review feedback

Critical fixes:
- Remove non-existent module exports from index.tsx (context, themes, ui, hooks, services)
- Simplify App.tsx to remove missing context provider imports

Major fixes:
- ProgressBar: Add defensive guards for width/progress (NaN, Infinity, negative)
- Browse: Fix filtered index loading wrong repository
- Context: Add section navigation (h/l keys) and async error handling
- Methodology: Add error handling with try/catch/finally for all async ops
- Plan: Fix division by zero when plan has no tasks, add error handling
- Team: Add error handling for loadTeamConfig and handleInitialize
- Translate: Guard against missing skill.path before read operations

* fix(tui): address remaining CodeRabbit feedback

- Memory: Add error handling for loadData, handleDelete, handleClearAll, handleInitialize
- Team: Fix key conflict by blocking global keys when detail pane is open
- animations: Fix springCurve to return 0 at progress=0 and 1 at progress=1

* fix(tui): add Solid.js OpenTUI type definitions

Required for TypeScript to recognize OpenTUI JSX elements (box, text, span)
with their custom props (fg, bg, flexDirection, etc.)

* fix(tui): add stub services and fix type errors for CI

- Add minimal stub service implementations for all TUI screens:
  - context.service.ts - project context loading
  - executor.service.ts - skill execution
  - memory.service.ts - memory management
  - methodology.service.ts - methodology packs
  - plan.service.ts - plan management
  - plugin.service.ts - plugin management
  - recommend.service.ts - skill recommendations
  - team.service.ts - team collaboration
  - translator.service.ts - skill translation
  - workflow.service.ts - workflow orchestration

- Fix type errors in screens:
  - Plan.tsx: Add non-null assertions for optional issues array
  - Plugins.tsx: Cast getPluginInfo result to Plugin type

These stubs provide the expected interfaces for screens while
the full integration with @skillkit/core is completed later.

* fix(tui): add missing component files for CI

Add the component files that screens depend on:
- StatusIndicator - loading/success/error status display
- DetailPane - side panel for detailed view
- EmptyState/ErrorState - empty and error state components
- SelectList - selection list component
- SplitPane - split view layout
- AnimatedText - text animations
- Breadcrumb - navigation breadcrumb
- Button/Clickable - interactive elements
- CodeBlock - code display
- FormField - form input wrapper
- HoverHighlight - hover effect wrapper
- RightSidebar/BottomStatusBar - layout components
- TabBar - tab navigation
- ErrorBoundary - error handling wrapper

These components are required by the screen files and were
missing from the previous commit.

* fix(tui): resolve context import and duplicate export issues

- RightSidebar: inline sidebar state instead of importing from context
- services/index.ts: fix duplicate AgentType export by using explicit
  exports for executor and translator services

* fix(tui): use export type for type-only re-exports

* refactor(tui): simplify components and remove redundant exports

* refactor(tui): remove unused imports and variables

Code simplification pass:
- Remove unused onCleanup import from Workflow, Recommend, Sync screens
- Remove unused contentWidth from Browse, Recommend, Marketplace, Sync
- Remove unused cols from Browse, Recommend
- Remove unused JSX import from EmptyState component
- Remove unused translate import from Sync screen
- Remove unused SelectList import and listItems function from Memory screen

* fix(tui): wire up interactive handlers and fix type definitions

- AnimatedText: fix reactive dependency tracking in createEffect
- BottomStatusBar: remove unused width prop
- Breadcrumb: wire onNavigate handlers, fix off-by-one in getPathAtIndex
- Button: wire onClick with disabled check, apply paddingX, fix ButtonGroup spacing
- Clickable: wire click/double-click/right-click handlers, fix InteractiveArea
- DetailPane: make close button interactive
- ErrorBoundary: use terminal keyboard handler, prevent duplicate onError calls
- FormField: fix placeholder show condition for empty string
- SelectList: add onSelect/onHover interactive behavior
- SplitPane: preserve string sizes like "50%" in width/height helpers
- TabBar: wire onSelect callbacks for both horizontal and vertical variants
- solid-opentui.d.ts: add missing event handler types to BoxProps/TextProps

* fix(tui): address Devin review issues

- App: restore process.exit(0) fallback when onExit is undefined
- Execute: pass skill path instead of content to executeSkillWithAgent
- Memory: add useKeyboard handler for j/k/Enter/d/c/i/Esc shortcuts

* fix(tui): address Devin and CodeRabbit review issues

Security & Robustness:
- App: use execFile instead of exec to prevent command injection in openUrl
- App: clamp cols/rows to minimum 1 to prevent negative dimensions
- index: await render() and handle failures with exitTUI(1)

Execute screen:
- Add error state for load failures
- Prevent re-entrant execution with executing() guard
- Use try/finally to always clear executing state

Memory screen:
- Add missing 'r' shortcut for retry/refresh

Workflow screen:
- Use try/finally to always clear executing state even on rejection

Sync screen:
- Capture selectedIndex and agent values before await to prevent drift

* fix(tui): implement list windowing to keep selection visible

Execute, Marketplace, Recommend screens now use windowed list rendering
that follows the selection, preventing the selected item from being
off-screen when navigating through long lists.

- Add createMemo for computing visible window based on selectedIndex
- Show ▲/▼ indicators when items are above/below the visible window
- Navigate through full list instead of clamping to visible window size

* fix(tui): add error handling and index clamping

Marketplace.tsx:
- Set error signal when all repos fail or no skills loaded
- Add reactive effect to clamp selectedIndex when filteredSkills changes

Recommend.tsx:
- Wrap loadData in try/catch to surface errors in UI
- Clamp selectedIndex after recommendations update

* fix(tui): add error handling to Plugins and Workflow screens

Plugins.tsx:
- Wrap loadData in try/catch to prevent stuck loading state
- Wrap handleToggle in try/catch/finally to always reset toggling flag
- Wrap handleShowDetail in try/catch to surface errors gracefully

Workflow.tsx:
- Wrap loadData in try/catch to prevent stuck loading state
- Add catch block to handleExecute to show execution errors in UI
2026-02-01 17:29:25 +00:00
Rohit Ghumare eebaa710f7 feat(website): add demo video and fix Twitter preview (#31)
* feat(website): add demo video to Hero section

- Add skillkit.mp4 video player below hero content
- Auto-plays muted with loop for seamless demo experience
- Styled with terminal-like window frame

* fix(website): fix Twitter/OG preview card

- Update og:url from skillkit.dev to agenstskills.com
- Use absolute URLs for og:image and twitter:image
- Add og:image dimensions (1200x630)
- Add og:site_name and twitter:url
- Update description to "32 agents"
2026-01-30 22:48:25 +00:00
133 changed files with 15155 additions and 2108 deletions
+77 -5
View File
@@ -142,8 +142,25 @@ Filter by task, category, or minimum score:
skillkit recommend --search "auth" # Task-based search
skillkit recommend --category security # Category filter
skillkit recommend --min-score 80 # Quality threshold
skillkit recommend --explain # Show WHY skills match
skillkit recommend --reasoning # Use LLM-based search
```
### Hierarchical Skill Tree
Browse skills organized in a navigable taxonomy:
```bash
skillkit tree # Show full tree
skillkit tree Frontend # Show Frontend subtree
skillkit tree "Frontend > React" # Navigate to subcategory
skillkit tree --generate # Generate tree from index
skillkit tree --stats # Show tree statistics
skillkit tree --depth 2 # Limit display depth
```
**Categories:** Development, Frontend, Backend, Mobile, DevOps, Testing, Security, AI/ML, Database, Tooling, Documentation, Performance
### Session Memory System
Your AI agents learn, but that knowledge dies with the session. SkillKit captures learnings and makes them persistent:
@@ -190,7 +207,7 @@ skillkit ui
skillkit
```
**Navigation:** `h` Home | `b` Browse | `r` Recommend | `t` Translate | `c` Context | `l` List | `s` Sync | `q` Quit
**Navigation:** `h` Home | `m` Marketplace | `b` Browse | `v` Tree View | `r` Recommend | `t` Translate | `c` Context | `l` List | `s` Sync | `q` Quit
### Skill Testing Framework
@@ -298,6 +315,10 @@ skillkit status # Show skill and agent status
```bash
skillkit recommend # Get smart recommendations
skillkit recommend --explain # Show reasoning for matches
skillkit recommend --reasoning # Use LLM-based discovery
skillkit tree # Browse hierarchical taxonomy
skillkit tree --generate # Generate tree from index
skillkit marketplace # Browse skill marketplace
skillkit marketplace search # Search marketplace
skillkit find <query> # Quick skill search
@@ -428,11 +449,31 @@ skillkit methodology load # Load a methodology
### Publishing & Sharing
```bash
skillkit publish # Publish skill to marketplace
skillkit publish # Generate well-known hosting structure
skillkit publish submit # Submit to SkillKit marketplace
skillkit create # Create new skill
skillkit init # Initialize in project
```
#### Self-Hosting Skills (RFC 8615)
Generate a well-known URI structure to host skills on your own domain:
```bash
# Generate hosting structure
skillkit publish ./my-skills --output ./public
# Users install from your domain
skillkit add https://your-domain.com
```
This creates:
```
.well-known/skills/
index.json # Skill manifest
my-skill/SKILL.md # Skill files
```
### Configuration
```bash
@@ -491,8 +532,29 @@ import {
// Recommendations
RecommendationEngine,
ReasoningRecommendationEngine,
analyzeProject,
// Tree & Taxonomy
TreeGenerator,
generateSkillTree,
loadTree,
buildSkillGraph,
getRelatedSkills,
// Reasoning Engine
ReasoningEngine,
createReasoningEngine,
// Connectors (Tool-Agnostic Placeholders)
detectPlaceholders,
replacePlaceholders,
suggestMappingsFromMcp,
// Execution Flow
ExecutionManager,
detectExecutionMode,
// Context
ContextManager,
syncToAllAgents,
@@ -516,10 +578,20 @@ import {
const skill = await translateSkill(skillContent, 'cursor');
console.log(skill.content);
// Example: Get recommendations
const engine = new RecommendationEngine();
// Example: Get recommendations with reasoning
const engine = new ReasoningRecommendationEngine();
await engine.initReasoning();
const profile = await analyzeProject('./my-project');
const recs = engine.recommend(profile);
const recs = await engine.recommendWithReasoning(profile, { reasoning: true });
// Example: Browse skill tree
const tree = generateSkillTree(skills);
console.log(tree.rootNode.children); // Categories
// Example: Detect execution mode
const mode = detectExecutionMode();
console.log(mode.mode); // 'standalone' or 'enhanced'
console.log(mode.capabilities); // Available MCP capabilities
```
## Skill Sources & Attribution
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "skillkit",
"version": "1.8.0",
"version": "1.9.0",
"description": "Supercharge AI coding agents with portable skills. Install, translate, and share skills across Claude Code, Cursor, Codex, Copilot & 13 more",
"type": "module",
"bin": {
+7
View File
@@ -48,10 +48,12 @@ import {
AICommand,
AuditCommand,
PublishCommand,
PublishSubmitCommand,
AgentCommand,
AgentListCommand,
AgentShowCommand,
AgentCreateCommand,
AgentFromSkillCommand,
AgentTranslateCommand,
AgentSyncCommand,
AgentValidateCommand,
@@ -95,6 +97,7 @@ import {
GuidelineDisableCommand,
GuidelineCreateCommand,
GuidelineRemoveCommand,
TreeCommand,
} from '@skillkit/cli';
const __filename = fileURLToPath(import.meta.url);
@@ -149,10 +152,12 @@ cli.register(CommandCmd);
cli.register(AICommand);
cli.register(AuditCommand);
cli.register(PublishCommand);
cli.register(PublishSubmitCommand);
cli.register(AgentCommand);
cli.register(AgentListCommand);
cli.register(AgentShowCommand);
cli.register(AgentCreateCommand);
cli.register(AgentFromSkillCommand);
cli.register(AgentTranslateCommand);
cli.register(AgentSyncCommand);
cli.register(AgentValidateCommand);
@@ -213,4 +218,6 @@ cli.register(GuidelineDisableCommand);
cli.register(GuidelineCreateCommand);
cli.register(GuidelineRemoveCommand);
cli.register(TreeCommand);
cli.runExit(process.argv.slice(2));
+9 -1
View File
@@ -233,10 +233,18 @@ skillkit init # Initialize project
skillkit create <name> # Create new skill
skillkit validate [path] # Validate skill format
skillkit read <skills> # Read skill content
skillkit publish # Publish to marketplace
skillkit settings --set key=value # Configure settings
```
## Publishing Commands
```bash
skillkit publish [path] # Generate well-known hosting structure
skillkit publish --output dir # Output to specific directory
skillkit publish --dry-run # Preview without writing
skillkit publish submit # Submit to SkillKit marketplace
```
## Interactive TUI
```bash
+32 -1
View File
@@ -48,8 +48,39 @@ skillkit install anthropics/skills --agent claude-code,cursor
## Publish Skills
### Self-Host on Your Domain (Recommended)
Generate a well-known URI structure (RFC 8615) to host skills on your own domain:
```bash
# Create and validate your skill
skillkit create my-skill
skillkit validate my-skill
skillkit publish
# Generate hosting structure
skillkit publish ./my-skill --output ./public
```
This creates:
```
.well-known/skills/
index.json # Skill manifest for auto-discovery
my-skill/
SKILL.md # Your skill content
```
Deploy the `.well-known` folder to your web server. Users can then install via:
```bash
skillkit add https://your-domain.com
```
### Submit to SkillKit Marketplace
To submit your skill for inclusion in the central marketplace:
```bash
skillkit publish submit
```
This opens a GitHub issue for review by maintainers.
+1
View File
@@ -9,6 +9,7 @@
"agents",
"translation",
"marketplace",
"tree",
"recommendations",
"primer",
"memory",
+41 -1
View File
@@ -32,6 +32,33 @@ skillkit recommend --category security
skillkit recommend --min-score 80
```
## Explainable Recommendations
See WHY skills match your project:
```bash
skillkit recommend --explain
```
Output:
```
vercel-react-best-practices (Score: 92)
├── Matched: React, TypeScript, Next.js
├── Your stack: Next.js 14, React 18
└── Path: Frontend > React > Best Practices
```
## LLM-Based Reasoning
Use reasoning-based discovery for complex queries:
```bash
skillkit recommend --reasoning
```
This uses an LLM to traverse the skill taxonomy and find the most relevant skills based on semantic understanding.
## How It Works
The engine analyzes:
@@ -50,9 +77,22 @@ Scores based on:
## Programmatic API
```typescript
import { RecommendationEngine, analyzeProject } from '@skillkit/core'
import {
RecommendationEngine,
ReasoningRecommendationEngine,
analyzeProject
} from '@skillkit/core'
// Basic recommendations
const engine = new RecommendationEngine()
const profile = await analyzeProject('./my-project')
const recs = engine.recommend(profile)
// With reasoning and explanations
const reasoningEngine = new ReasoningRecommendationEngine()
await reasoningEngine.initReasoning()
const explained = await reasoningEngine.recommendWithReasoning(profile, {
reasoning: true,
explain: true
})
```
+18 -2
View File
@@ -94,6 +94,22 @@ Or manually create a `SKILL.md` file following the format above.
# Test locally
skillkit validate ./my-skill
# Publish to marketplace
skillkit publish
# Generate well-known hosting structure for self-hosting
skillkit publish ./my-skill --output ./public
# Or submit to SkillKit marketplace
skillkit publish submit
```
### Self-Hosting
The `skillkit publish` command generates an RFC 8615 well-known URI structure:
```
.well-known/skills/
index.json # Manifest for auto-discovery
my-skill/
SKILL.md # Skill content
```
Deploy to your domain and users can install via `skillkit add https://your-domain.com`.
+144
View File
@@ -0,0 +1,144 @@
---
title: Skill Tree
description: Browse skills in a hierarchical taxonomy
---
# Skill Tree
Browse and navigate skills organized in a hierarchical taxonomy structure.
## Quick Start
```bash
# Show full skill tree
skillkit tree
# Navigate to a category
skillkit tree Frontend
# Navigate to subcategory
skillkit tree "Frontend > React"
```
## Commands
### Display Tree
```bash
skillkit tree # Full tree
skillkit tree Development # Specific category
skillkit tree --depth 2 # Limit display depth
```
### Generate Tree
```bash
skillkit tree --generate # Generate from skill index
```
This builds a hierarchical tree from the skill index based on tags and metadata.
### Export Formats
```bash
skillkit tree --json # JSON output
skillkit tree --markdown # Markdown output
```
### Statistics
```bash
skillkit tree --stats
```
Output:
```
Overview:
Total Skills: 15,064
Categories: 156
Max Depth: 4
Top-Level Categories:
Development 4,521 skills (30.0%)
Frontend (1,245), Backend (1,102), Mobile (456)
DevOps 2,340 skills (15.5%)
CI/CD (890), Kubernetes (567), Docker (445)
AI/ML 1,890 skills (12.5%)
LLM Integration (756), Agents (445), RAG (312)
```
## Categories
The tree organizes skills into 12 top-level categories:
| Category | Description |
|----------|-------------|
| Development | General coding, programming patterns |
| Frontend | React, Vue, Angular, Svelte, UI/UX |
| Backend | Node.js, Python, Go, APIs, servers |
| Mobile | React Native, Flutter, iOS, Android |
| DevOps | CI/CD, Kubernetes, Docker, cloud |
| Testing | Unit, E2E, integration, TDD |
| Security | Auth, encryption, vulnerabilities |
| AI/ML | LLM, agents, RAG, embeddings |
| Database | SQL, NoSQL, ORM, migrations |
| Tooling | Linting, formatting, bundling |
| Documentation | API docs, guides, READMEs |
| Performance | Optimization, caching, profiling |
## TUI Tree View
In the TUI, press `v` to toggle tree view in the Marketplace:
- **Arrow keys** - Navigate tree
- **Enter** - Expand category / select skill
- **←** - Go back / collapse
- **v** - Toggle list/tree view
## Related Skills Graph
Find skills related to each other:
```typescript
import { buildSkillGraph, getRelatedSkills } from '@skillkit/core'
const graph = buildSkillGraph(skills)
const related = getRelatedSkills('react-patterns', graph, skills, {
limit: 5,
types: ['similar', 'complementary']
})
```
### Relation Types
- **similar** - Shares tags and functionality
- **complementary** - Works well together
- **dependency** - Required by other skills
- **alternative** - Different approach to same problem
## Programmatic API
```typescript
import {
TreeGenerator,
generateSkillTree,
loadTree,
saveTree,
treeToMarkdown
} from '@skillkit/core'
// Generate tree from skills
const generator = new TreeGenerator({ maxDepth: 3 })
const tree = generator.generateTree(skills)
// Or use the helper function
const tree = generateSkillTree(skills)
// Save and load
saveTree(tree, './skill-tree.json')
const loaded = loadTree('./skill-tree.json')
// Export to markdown
const markdown = treeToMarkdown(tree)
```
+41 -9
View File
@@ -18,10 +18,12 @@ skillkit
## Framework
Built on modern technologies:
- **@opentui/react** - Terminal rendering
- **React 19.0.0** - Component architecture
- **@opentui/solid** - Terminal rendering with Solid.js
- **Solid.js 1.9.0** - Reactive component architecture
- **Bun 1.2.0+** - Runtime requirement
The TUI was migrated from React to Solid.js in v1.8.0 for improved performance and smaller bundle size.
## Screens
| Screen | Key | Purpose |
@@ -103,6 +105,20 @@ Browse 15,000+ skills:
- Featured skills
- 3-phase animation loading
- Quality scoring
- **Tree View** - Press `v` to toggle hierarchical navigation
#### Tree View Mode
Navigate skills in a hierarchical taxonomy:
| Key | Action |
|-----|--------|
| `v` | Toggle tree/list view |
| `→` or `Enter` | Expand category |
| `←` | Collapse / go back |
| `↑`/`↓` | Navigate |
Categories include: Development, Frontend, Backend, Mobile, DevOps, Testing, Security, AI/ML, Database, Tooling, Documentation, Performance
### Recommend Screen
@@ -159,8 +175,10 @@ loadSkills()
### Performance Optimizations
- `useMemo` for filtered lists
- `useCallback` for event handlers
- `createMemo` for filtered lists and computed values
- `createSignal` for reactive state management
- `createEffect` for side effects and subscriptions
- Windowed list rendering for large datasets
- Pagination limits rendered items
- Progressive animation with phases
@@ -174,18 +192,32 @@ loadSkills()
## Integration
The TUI integrates with @skillkit/core:
The TUI integrates with @skillkit/core using Solid.js reactive patterns:
```typescript
findAllSkills(searchDirs) // Returns skill metadata
evaluateSkillDirectory(path) // Quality metrics
getQualityGrade(score) // 0-100 to A-F
import { createSignal, createMemo, createEffect } from 'solid-js';
const [skills, setSkills] = createSignal([]);
createEffect(async () => {
const result = await findAllSkills(searchDirs);
setSkills(result);
});
const filteredSkills = createMemo(() =>
skills().filter(s => s.name.includes(searchTerm()))
);
```
Core functions:
- `findAllSkills(searchDirs)` - Returns skill metadata
- `evaluateSkillDirectory(path)` - Quality metrics
- `getQualityGrade(score)` - 0-100 to A-F
## Graceful Exit
The TUI handles shutdown gracefully:
1. Unmounts React components
1. Runs Solid.js cleanup functions (`onCleanup`)
2. Restores terminal state
3. Cleans up signal handlers
4. Exits process cleanly
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "skillkit-docs",
"version": "1.8.0",
"version": "1.9.0",
"private": true,
"scripts": {
"build": "next build",
+1 -1
View File
@@ -13,7 +13,7 @@ const COMMAND_GROUPS: CommandGroup[] = [
{ cmd: 'install <repo>', desc: 'Install from GitHub' },
{ cmd: 'add <repo>', desc: 'Alias for install' },
{ cmd: 'recommend', desc: 'Smart suggestions' },
{ cmd: 'find <query>', desc: 'Search 15K+ skills' },
{ cmd: 'tree', desc: 'Browse skill taxonomy' },
{ cmd: 'marketplace', desc: 'Browse skills' },
],
},
+9
View File
@@ -43,6 +43,15 @@ const FEATURES: Feature[] = [
</svg>
)
},
{
title: 'Skill Tree',
description: 'Browse 15K+ skills in a hierarchical taxonomy with 12 categories.',
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="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
</svg>
)
},
{
title: 'Workflows',
description: 'Compose multi-step automated skill sequences.',
+26
View File
@@ -206,6 +206,32 @@ export function Hero(): React.ReactElement {
</div>
</div>
</div>
{/* Video Demo */}
<div className="mt-8 sm:mt-10 animate-fade-in-delay">
<div className="relative mx-auto max-w-3xl">
<div className="absolute -inset-1 bg-gradient-to-r from-zinc-800 via-zinc-600 to-zinc-800 rounded-lg opacity-30 blur-xl"></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-red-500/80"></div>
<div className="w-2.5 h-2.5 rounded-full bg-yellow-500/80"></div>
<div className="w-2.5 h-2.5 rounded-full bg-green-500/80"></div>
<span className="ml-2 text-zinc-500 text-xs font-mono">skillkit demo</span>
</div>
<video
className="w-full"
autoPlay
loop
muted
playsInline
poster="/og-image.png"
>
<source src="/skillkit.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
</div>
</div>
</div>
</div>
<style>{FADE_ANIMATION_STYLES}</style>
+10 -6
View File
@@ -4,20 +4,24 @@
<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.">
<meta name="description" content="Write once, deploy to 32 AI coding agents. Skills for Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and more.">
<!-- Open Graph -->
<meta property="og:type" content="website">
<meta property="og:url" content="https://skillkit.dev/">
<meta property="og:url" content="https://agenstskills.com/">
<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">
<meta property="og:description" content="Write once, deploy to 32 AI coding agents. Skills for Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and more.">
<meta property="og:image" content="https://agenstskills.com/og-image.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:site_name" content="SkillKit">
<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:url" content="https://agenstskills.com/">
<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">
<meta name="twitter:description" content="Write once, deploy to 32 AI coding agents. Skills for Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and more.">
<meta name="twitter:image" content="https://agenstskills.com/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" />
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "skillkit",
"private": true,
"version": "1.8.0",
"version": "1.9.0",
"type": "module",
"scripts": {
"dev": "vite",
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "skillkit-monorepo",
"version": "1.8.0",
"version": "1.9.0",
"private": true,
"description": "Universal skills loader for AI coding agents - Monorepo",
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/agents",
"version": "1.8.0",
"version": "1.9.0",
"description": "Agent adapters for SkillKit - supports 32 AI coding agents",
"type": "module",
"main": "./dist/index.js",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/cli",
"version": "1.8.0",
"version": "1.9.0",
"description": "CLI commands for SkillKit",
"type": "module",
"main": "./dist/index.js",
+187 -22
View File
@@ -7,7 +7,7 @@
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { join, basename } from 'node:path';
import { homedir } from 'node:os';
import {
findAllAgents,
@@ -17,8 +17,14 @@ import {
validateAgent,
translateAgent,
getAgentTargetDirectory,
discoverSkills,
readSkillContent,
generateSubagentFromSkill,
type CustomAgent,
type AgentType,
type Skill,
type AgentPermissionMode,
type SkillToSubagentOptions,
} from '@skillkit/core';
import {
getBundledAgents,
@@ -28,7 +34,6 @@ import {
isAgentInstalled,
type BundledAgent,
} from '@skillkit/resources';
// Agent discovery uses root directories, not skill directories
export class AgentCommand extends Command {
static override paths = [['agent']];
@@ -43,17 +48,19 @@ export class AgentCommand extends Command {
that can be invoked with @mentions or the --agent flag.
Sub-commands:
agent list - List all installed agents
agent show - Show agent details
agent create - Create a new agent
agent translate - Translate agents between formats
agent sync - Sync agents to target AI agent
agent validate - Validate agent definitions
agent list - List all installed agents
agent show - Show agent details
agent create - Create a new agent
agent from-skill - Convert a skill to a subagent
agent translate - Translate agents between formats
agent sync - Sync agents to target AI agent
agent validate - Validate agent definitions
`,
examples: [
['List all agents', '$0 agent list'],
['Show agent details', '$0 agent show architect'],
['Create new agent', '$0 agent create security-reviewer'],
['Convert skill to subagent', '$0 agent from-skill code-simplifier'],
['Translate to Cursor format', '$0 agent translate --to cursor'],
['Sync agents', '$0 agent sync --agent claude-code'],
],
@@ -64,6 +71,7 @@ export class AgentCommand extends Command {
console.log(' agent list List all installed agents');
console.log(' agent show <name> Show agent details');
console.log(' agent create <name> Create a new agent');
console.log(' agent from-skill <name> Convert a skill to a subagent');
console.log(' agent translate Translate agents between formats');
console.log(' agent sync Sync agents to target AI agent');
console.log(' agent validate [path] Validate agent definitions');
@@ -254,7 +262,6 @@ export class AgentCreateCommand extends Command {
});
async execute(): Promise<number> {
// Validate agent name format
const namePattern = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (!namePattern.test(this.name)) {
console.log(chalk.red('Invalid agent name: must be lowercase alphanumeric with hyphens'));
@@ -262,7 +269,6 @@ export class AgentCreateCommand extends Command {
return 1;
}
// Determine target directory
let targetDir: string;
if (this.global) {
targetDir = join(homedir(), '.claude', 'agents');
@@ -270,23 +276,19 @@ export class AgentCreateCommand extends Command {
targetDir = join(process.cwd(), '.claude', 'agents');
}
// Create directory if needed
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
// Check if agent already exists
const agentPath = join(targetDir, `${this.name}.md`);
if (existsSync(agentPath)) {
console.log(chalk.red(`Agent already exists: ${agentPath}`));
return 1;
}
// Generate content
const description = this.description || `${this.name} agent`;
const content = generateAgentTemplate(this.name, description, this.model);
// Write file
writeFileSync(agentPath, content);
console.log(chalk.green(`Created agent: ${agentPath}`));
@@ -350,11 +352,9 @@ export class AgentTranslateCommand extends Command {
const searchDirs = [process.cwd()];
const targetAgent = this.to as AgentType;
// Get agents to translate
let agents: CustomAgent[];
if (this.source) {
// Translate from custom source path
const sourcePath = this.source.startsWith('/')
? this.source
: join(process.cwd(), this.source);
@@ -391,7 +391,6 @@ export class AgentTranslateCommand extends Command {
return 0;
}
// Determine output directory
const outputDir = this.output || getAgentTargetDirectory(process.cwd(), targetAgent);
console.log(chalk.cyan(`Translating ${agents.length} agent(s) to ${targetAgent} format...\n`));
@@ -424,7 +423,6 @@ export class AgentTranslateCommand extends Command {
}
}
} else {
// Create directory if needed
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
@@ -529,12 +527,10 @@ export class AgentValidateCommand extends Command {
let hasErrors = false;
if (this.agentPath) {
// Validate specific path
const result = validateAgent(this.agentPath);
printValidationResult(this.agentPath, result);
hasErrors = !result.valid;
} else if (this.all) {
// Validate all agents
const searchDirs = [process.cwd()];
const agents = findAllAgents(searchDirs);
@@ -559,8 +555,6 @@ export class AgentValidateCommand extends Command {
}
}
// Helper functions
function printAgent(agent: CustomAgent): void {
const status = agent.enabled ? chalk.green('✓') : chalk.red('○');
const name = agent.enabled ? agent.name : chalk.dim(agent.name);
@@ -831,9 +825,180 @@ export class AgentAvailableCommand extends Command {
}
}
export class AgentFromSkillCommand extends Command {
static override paths = [['agent', 'from-skill']];
static override usage = Command.Usage({
description: 'Convert a skill into a Claude Code subagent',
details: `
Converts a SkillKit skill into a Claude Code native subagent format.
The generated .md file can be used with @mentions in Claude Code.
By default, the subagent references the skill (skills: [skill-name]).
Use --inline to embed the full skill content in the system prompt.
`,
examples: [
['Convert skill to subagent', '$0 agent from-skill code-simplifier'],
['Create global subagent', '$0 agent from-skill code-simplifier --global'],
['Embed skill content inline', '$0 agent from-skill code-simplifier --inline'],
['Set model for subagent', '$0 agent from-skill code-simplifier --model opus'],
['Preview without writing', '$0 agent from-skill code-simplifier --dry-run'],
],
});
skillName = Option.String({ required: true });
inline = Option.Boolean('--inline,-i', false, {
description: 'Embed full skill content in system prompt',
});
model = Option.String('--model,-m', {
description: 'Model to use (sonnet, opus, haiku, inherit)',
});
permission = Option.String('--permission,-p', {
description: 'Permission mode (default, plan, auto-edit, full-auto, bypassPermissions)',
});
global = Option.Boolean('--global,-g', false, {
description: 'Create in ~/.claude/agents/ instead of .claude/agents/',
});
output = Option.String('--output,-o', {
description: 'Custom output filename (without .md)',
});
dryRun = Option.Boolean('--dry-run,-n', false, {
description: 'Preview without writing files',
});
async execute(): Promise<number> {
const skills = discoverSkills(process.cwd());
const skill = skills.find((s: Skill) => s.name === this.skillName);
if (!skill) {
console.log(chalk.red(`Skill not found: ${this.skillName}`));
console.log(chalk.dim('Available skills:'));
for (const s of skills.slice(0, 10)) {
console.log(chalk.dim(` - ${s.name}`));
}
if (skills.length > 10) {
console.log(chalk.dim(` ... and ${skills.length - 10} more`));
}
return 1;
}
const skillContent = readSkillContent(skill.path);
if (!skillContent) {
console.log(chalk.red(`Could not read skill content: ${skill.path}`));
return 1;
}
const options: SkillToSubagentOptions = {
inline: this.inline,
};
if (this.model) {
const validModels = ['sonnet', 'opus', 'haiku', 'inherit'];
if (!validModels.includes(this.model)) {
console.log(chalk.red(`Invalid model: ${this.model}`));
console.log(chalk.dim(`Valid options: ${validModels.join(', ')}`));
return 1;
}
options.model = this.model as 'sonnet' | 'opus' | 'haiku' | 'inherit';
}
if (this.permission) {
const validModes = ['default', 'plan', 'auto-edit', 'full-auto', 'bypassPermissions'];
if (!validModes.includes(this.permission)) {
console.log(chalk.red(`Invalid permission mode: ${this.permission}`));
console.log(chalk.dim(`Valid options: ${validModes.join(', ')}`));
return 1;
}
options.permissionMode = this.permission as AgentPermissionMode;
}
const content = generateSubagentFromSkill(skill, skillContent, options);
const targetDir = this.global
? join(homedir(), '.claude', 'agents')
: join(process.cwd(), '.claude', 'agents');
let filename: string;
if (this.output) {
const sanitized = sanitizeFilename(this.output);
if (!sanitized) {
console.log(chalk.red(`Invalid output filename: ${this.output}`));
console.log(chalk.dim('Filename must contain only alphanumeric characters, hyphens, and underscores'));
return 1;
}
filename = `${sanitized}.md`;
} else {
const sanitized = sanitizeFilename(skill.name);
if (!sanitized) {
console.log(chalk.red(`Invalid skill name for filename: ${skill.name}`));
console.log(chalk.dim('Skill name must contain only alphanumeric characters, hyphens, and underscores'));
return 1;
}
filename = `${sanitized}.md`;
}
const outputPath = join(targetDir, filename);
if (this.dryRun) {
console.log(chalk.cyan('Preview (dry run):\n'));
console.log(chalk.dim(`Would write to: ${outputPath}`));
console.log(chalk.dim('─'.repeat(50)));
console.log(content);
console.log(chalk.dim('─'.repeat(50)));
return 0;
}
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
if (existsSync(outputPath)) {
console.log(chalk.yellow(`Overwriting existing file: ${outputPath}`));
}
writeFileSync(outputPath, content);
console.log(chalk.green(`Created subagent: ${outputPath}`));
console.log();
console.log(chalk.dim(`Invoke with: @${skill.name}`));
if (!this.inline) {
console.log(chalk.dim(`Skills referenced: ${skill.name}`));
} else {
console.log(chalk.dim('Skill content embedded inline'));
}
return 0;
}
}
function formatCategoryName(category: string): string {
return category
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
function sanitizeFilename(input: string): string | null {
const base = basename(input);
const stem = base.replace(/\.md$/i, '');
if (!stem || stem.startsWith('.') || stem.startsWith('-')) {
return null;
}
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(stem)) {
return null;
}
if (stem.length > 64) {
return null;
}
return stem;
}
+5 -1
View File
@@ -43,12 +43,13 @@ export { PlanCommand } from './plan.js';
export { CommandCmd, CommandAvailableCommand, CommandInstallCommand } from './command.js';
export { AICommand } from './ai.js';
export { AuditCommand } from './audit.js';
export { PublishCommand } from './publish.js';
export { PublishCommand, PublishSubmitCommand } from './publish.js';
export {
AgentCommand,
AgentListCommand,
AgentShowCommand,
AgentCreateCommand,
AgentFromSkillCommand,
AgentTranslateCommand,
AgentSyncCommand,
AgentValidateCommand,
@@ -104,3 +105,6 @@ export {
GuidelineCreateCommand,
GuidelineRemoveCommand,
} from './guideline.js';
// Tree command for hierarchical skill browsing (Phase 21)
export { TreeCommand } from './tree.js';
+23 -3
View File
@@ -1,5 +1,9 @@
import { existsSync, mkdirSync, cpSync, rmSync, symlinkSync } from 'node:fs';
import { join } from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
import { Command, Option } from 'clipanion';
import { detectProvider, isLocalPath, getProvider, evaluateSkillDirectory } from '@skillkit/core';
import type { SkillMetadata, GitProvider, AgentType } from '@skillkit/core';
@@ -42,7 +46,8 @@ export class InstallCommand extends Command {
['Install from GitHub', '$0 install owner/repo'],
['Install from GitLab', '$0 install gitlab:owner/repo'],
['Install from Bitbucket', '$0 install bitbucket:owner/repo'],
['Install specific skills (CI/CD)', '$0 install owner/repo --skills=pdf,xlsx'],
['Install specific skill', '$0 install owner/repo --skill=pdf'],
['Install multiple skills (CI/CD)', '$0 install owner/repo --skills=pdf,xlsx'],
['Install all skills non-interactively', '$0 install owner/repo --all'],
['Install from local path', '$0 install ./my-skills'],
['Install globally', '$0 install owner/repo --global'],
@@ -53,7 +58,7 @@ export class InstallCommand extends Command {
source = Option.String({ required: true });
skills = Option.String('--skills,-s', {
skills = Option.String('--skills,--skill,-s', {
description: 'Comma-separated list of skills to install (non-interactive)',
});
@@ -143,7 +148,7 @@ export class InstallCommand extends Command {
}
console.log('');
console.log(colors.muted(`Total: ${discoveredSkills.length} skill(s)`));
console.log(colors.muted('To install: skillkit install <source> --skills=skill1,skill2'));
console.log(colors.muted('To install: skillkit install <source> --skill=name'));
}
const cleanupPath = result.tempRoot || result.path;
@@ -334,6 +339,21 @@ export class InstallCommand extends Command {
if (isSymlinkMode && primaryPath === null) {
primaryPath = targetPath;
}
// Auto-install npm dependencies if package.json exists
const packageJsonPath = join(targetPath, 'package.json');
if (existsSync(packageJsonPath)) {
s.stop(`Installed ${skillName} to ${adapter.name}`);
s.start(`Installing npm dependencies for ${skillName}...`);
try {
await execFileAsync('npm', ['install', '--production'], { cwd: targetPath });
s.stop(`Installed dependencies for ${skillName}`);
} catch (npmErr) {
s.stop(colors.warning(`Dependencies failed for ${skillName}`));
console.log(colors.muted('Run manually: npm install in ' + targetPath));
}
s.start(`Finishing ${skillName} installation...`);
}
}
const metadata: SkillMetadata = {
+336 -126
View File
@@ -1,8 +1,20 @@
import { existsSync, readFileSync } from 'node:fs';
import { join, basename, dirname } from 'node:path';
import { execSync } from 'node:child_process';
import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, statSync } from 'node:fs';
import { join, basename, dirname, resolve } from 'node:path';
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { generateWellKnownIndex, type WellKnownSkill } from '@skillkit/core';
function sanitizeSkillName(name: string): string | null {
if (!name || typeof name !== 'string') return null;
const base = basename(name);
if (base !== name || name.includes('..') || name.includes('/') || name.includes('\\')) {
return null;
}
if (!/^[a-zA-Z0-9._-]+$/.test(name)) {
return null;
}
return name;
}
interface SkillFrontmatter {
name?: string;
@@ -15,141 +27,201 @@ export class PublishCommand extends Command {
static override paths = [['publish']];
static override usage = Command.Usage({
description: 'Publish your skill to the SkillKit marketplace',
description: 'Generate well-known skills structure for hosting',
details: `
This command generates the RFC 8615 well-known URI structure for hosting skills.
The output includes:
- .well-known/skills/index.json - Skill manifest for auto-discovery
- .well-known/skills/{skill-name}/SKILL.md - Individual skill files
Users can then install skills via: skillkit add https://your-domain.com
`,
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'],
['Generate from current directory', '$0 publish'],
['Generate from specific path', '$0 publish ./my-skills'],
['Generate to custom output directory', '$0 publish --output ./public'],
['Preview without writing', '$0 publish --dry-run'],
],
});
skillPath = Option.String({ required: false, name: 'path' });
name = Option.String('--name,-n', {
description: 'Custom skill name (default: parsed from SKILL.md)',
output = Option.String('--output,-o', {
description: 'Output directory for well-known structure (default: current directory)',
});
dryRun = Option.Boolean('--dry-run', false, {
description: 'Show what would be published without actually publishing',
dryRun = Option.Boolean('--dry-run,-n', false, {
description: 'Show what would be generated without writing files',
});
async execute(): Promise<number> {
const skillPath = this.skillPath || process.cwd();
const skillMdPath = this.findSkillMd(skillPath);
const basePath = this.skillPath || process.cwd();
const outputDir = this.output || basePath;
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'));
console.log(chalk.cyan('Generating well-known skills structure...\n'));
const discoveredSkills = this.discoverSkills(basePath);
if (discoveredSkills.length === 0) {
console.error(chalk.red('No skills found'));
console.error(chalk.dim('Skills must contain a SKILL.md file with frontmatter'));
return 1;
}
console.log(chalk.cyan('Publishing skill to SkillKit marketplace...\n'));
console.log(chalk.white(`Found ${discoveredSkills.length} skill(s):\n`));
// Parse SKILL.md
const content = readFileSync(skillMdPath, 'utf-8');
const frontmatter = this.parseFrontmatter(content);
const skillName = this.name || frontmatter.name || basename(dirname(skillMdPath));
const wellKnownSkills: WellKnownSkill[] = [];
// 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'));
const validSkills: Array<{ name: string; safeName: string; description?: string; path: string }> = [];
for (const skill of discoveredSkills) {
const safeName = sanitizeSkillName(skill.name);
if (!safeName) {
console.log(chalk.yellow(` ${chalk.yellow('⚠')} Skipping "${skill.name}" (invalid name - must be alphanumeric with hyphens/underscores)`));
continue;
}
const files = this.getSkillFiles(skill.path);
console.log(chalk.dim(` ${chalk.green('●')} ${safeName}`));
console.log(chalk.dim(` Description: ${skill.description || 'No description'}`));
console.log(chalk.dim(` Files: ${files.join(', ')}`));
validSkills.push({ name: skill.name, safeName, description: skill.description, path: skill.path });
wellKnownSkills.push({
name: safeName,
description: skill.description,
files,
});
}
if (validSkills.length === 0) {
console.error(chalk.red('\nNo valid skills to publish'));
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();
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));
console.log(chalk.yellow('Dry run - not writing files\n'));
console.log(chalk.white('Would generate:'));
console.log(chalk.dim(` ${outputDir}/.well-known/skills/index.json`));
for (const skill of wellKnownSkills) {
for (const file of skill.files) {
console.log(chalk.dim(` ${outputDir}/.well-known/skills/${skill.name}/${file}`));
}
}
console.log('');
console.log(chalk.white('index.json preview:'));
console.log(JSON.stringify(generateWellKnownIndex(wellKnownSkills), 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`;
const wellKnownDir = join(outputDir, '.well-known', 'skills');
mkdirSync(wellKnownDir, { recursive: true });
console.log(chalk.green('Opening GitHub to submit your skill...\n'));
for (const skill of validSkills) {
const skillDir = join(wellKnownDir, skill.safeName);
const resolvedSkillDir = resolve(skillDir);
const resolvedWellKnownDir = resolve(wellKnownDir);
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' });
if (!resolvedSkillDir.startsWith(resolvedWellKnownDir)) {
console.log(chalk.yellow(` Skipping "${skill.name}" (path traversal detected)`));
continue;
}
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));
mkdirSync(skillDir, { recursive: true });
const files = this.getSkillFiles(skill.path);
for (const file of files) {
const safeFile = basename(file);
const sourcePath = join(skill.path, file);
const destPath = join(skillDir, safeFile);
const content = readFileSync(sourcePath, 'utf-8');
writeFileSync(destPath, content);
}
}
console.log();
const index = generateWellKnownIndex(wellKnownSkills);
writeFileSync(join(wellKnownDir, 'index.json'), JSON.stringify(index, null, 2));
console.log(chalk.green('Generated well-known structure:\n'));
console.log(chalk.dim(` ${wellKnownDir}/index.json`));
for (const skill of wellKnownSkills) {
console.log(chalk.dim(` ${wellKnownDir}/${skill.name}/`));
}
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'));
console.log(chalk.dim(' 1. Deploy the .well-known directory to your web server'));
console.log(chalk.dim(' 2. Users can install via: skillkit add https://your-domain.com'));
console.log(chalk.dim(' 3. Skills auto-discovered from /.well-known/skills/index.json'));
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;
private discoverSkills(basePath: string): Array<{ name: string; description?: string; path: string }> {
const skills: Array<{ name: string; description?: string; path: string }> = [];
const skillMdPath = join(basePath, 'SKILL.md');
if (existsSync(skillMdPath)) {
const content = readFileSync(skillMdPath, 'utf-8');
const frontmatter = this.parseFrontmatter(content);
skills.push({
name: frontmatter.name || basename(basePath),
description: frontmatter.description,
path: basePath,
});
return skills;
}
// 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'),
const searchDirs = [
basePath,
join(basePath, 'skills'),
join(basePath, '.claude', 'skills'),
];
for (const loc of locations) {
if (existsSync(loc)) {
return loc;
for (const searchDir of searchDirs) {
if (!existsSync(searchDir)) continue;
const entries = readdirSync(searchDir);
for (const entry of entries) {
const entryPath = join(searchDir, entry);
if (!statSync(entryPath).isDirectory()) continue;
const entrySkillMd = join(entryPath, 'SKILL.md');
if (existsSync(entrySkillMd)) {
const content = readFileSync(entrySkillMd, 'utf-8');
const frontmatter = this.parseFrontmatter(content);
skills.push({
name: frontmatter.name || entry,
description: frontmatter.description,
path: entryPath,
});
}
}
}
return null;
return skills;
}
private getSkillFiles(skillPath: string): string[] {
const files: string[] = [];
const entries = readdirSync(skillPath);
for (const entry of entries) {
const entryPath = join(skillPath, entry);
if (statSync(entryPath).isFile()) {
if (entry.startsWith('.') || entry === '.skillkit-metadata.json') continue;
files.push(entry);
}
}
if (!files.includes('SKILL.md')) {
files.unshift('SKILL.md');
}
return files;
}
private parseFrontmatter(content: string): SkillFrontmatter {
@@ -161,7 +233,6 @@ export class PublishCommand extends Command {
let inTagsList = false;
for (const line of lines) {
// Handle multiline tags list
if (inTagsList) {
const tagMatch = line.match(/^\s*-\s*(.+)$/);
if (tagMatch) {
@@ -190,7 +261,6 @@ export class PublishCommand extends Command {
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)
@@ -207,6 +277,171 @@ export class PublishCommand extends Command {
return frontmatter;
}
}
export class PublishSubmitCommand extends Command {
static override paths = [['publish', 'submit']];
static override usage = Command.Usage({
description: 'Submit skill to SkillKit marketplace (requires review)',
examples: [
['Submit skill from current directory', '$0 publish submit'],
['Submit with custom name', '$0 publish submit --name my-skill'],
],
});
skillPath = Option.String({ required: false, name: 'path' });
name = Option.String('--name,-n', {
description: 'Custom skill name',
});
dryRun = Option.Boolean('--dry-run', false, {
description: 'Show what would be submitted',
});
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'));
return 1;
}
console.log(chalk.cyan('Submitting skill to SkillKit marketplace...\n'));
const content = readFileSync(skillMdPath, 'utf-8');
const frontmatter = this.parseFrontmatter(content);
const skillName = this.name || frontmatter.name || basename(dirname(skillMdPath));
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;
}
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 for ${this.formatName(skillName)}`,
source: `${repoInfo.owner}/${repoInfo.repo}`,
tags: frontmatter.tags || ['general'],
};
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 submitting'));
console.log(JSON.stringify(skillEntry, null, 2));
return 0;
}
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 {
const { execSync } = await import('node:child_process');
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.'));
} 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));
}
return 0;
}
private findSkillMd(basePath: string): string | null {
if (basePath.endsWith('SKILL.md') && existsSync(basePath)) {
return basePath;
}
const direct = join(basePath, 'SKILL.md');
if (existsSync(direct)) {
return direct;
}
const locations = [
join(basePath, 'skills', 'SKILL.md'),
join(basePath, '.claude', '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/);
for (const line of lines) {
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':
if (value.startsWith('[')) {
frontmatter.tags = value
.slice(1, -1)
.split(',')
.map(t => t.trim().replace(/^["']|["']$/g, ''))
.filter(t => t.length > 0);
}
break;
}
}
return frontmatter;
}
private slugify(name: string): string {
return name
@@ -218,19 +453,19 @@ export class PublishCommand extends Command {
private getRepoInfo(dir: string): { owner: string; repo: string } | null {
try {
const { execSync } = require('node:child_process');
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
// Not a git repo
}
return null;
@@ -243,31 +478,6 @@ export class PublishCommand extends Command {
.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 {
@@ -292,6 +502,6 @@ ${JSON.stringify(skill, null, 2)}
- [ ] Tags are appropriate
---
Submitted via \`skillkit publish\``;
Submitted via \`skillkit publish submit\``;
}
}
+170
View File
@@ -3,8 +3,10 @@ import { resolve } from 'node:path';
import {
type ProjectProfile,
type ScoredSkill,
type ExplainedScoredSkill,
ContextManager,
RecommendationEngine,
ReasoningRecommendationEngine,
buildSkillIndex,
saveIndex,
loadIndex as loadIndexFromCache,
@@ -108,6 +110,21 @@ export class RecommendCommand extends Command {
description: 'Minimal output',
});
// Explain mode (reasoning-based recommendations)
explain = Option.Boolean('--explain,-e', false, {
description: 'Show detailed explanations for recommendations (uses reasoning engine)',
});
// Reasoning mode
reasoning = Option.Boolean('--reasoning,-r', false, {
description: 'Use LLM-based reasoning for recommendations',
});
// Show tree path
showPath = Option.Boolean('--show-path', false, {
description: 'Show category path for each recommendation',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
@@ -139,6 +156,11 @@ export class RecommendCommand extends Command {
return 0;
}
// Use reasoning engine if explain/reasoning flags are set
if (this.explain || this.reasoning || this.showPath) {
return await this.handleReasoningRecommendations(profile, index);
}
// Create recommendation engine
const engine = new RecommendationEngine();
engine.loadIndex(index);
@@ -168,6 +190,63 @@ export class RecommendCommand extends Command {
return 0;
}
private async handleReasoningRecommendations(
profile: ProjectProfile,
index: { skills: ScoredSkill['skill'][]; sources: { name: string; url: string; lastFetched: string; skillCount: number }[]; version: number; lastUpdated: string }
): Promise<number> {
const s = !this.quiet && !this.json ? spinner() : null;
s?.start('Analyzing with reasoning engine...');
try {
const engine = new ReasoningRecommendationEngine();
engine.loadIndex(index);
await engine.initReasoning();
const result = await engine.recommendWithReasoning(profile, {
limit: this.limit ? parseInt(this.limit, 10) : 10,
minScore: this.minScore ? parseInt(this.minScore, 10) : 30,
categories: this.category,
excludeInstalled: !this.includeInstalled,
includeReasons: this.verbose,
reasoning: this.reasoning,
explainResults: this.explain,
useTree: true,
});
s?.stop('Analysis complete');
if (this.json) {
console.log(JSON.stringify(result, null, 2));
return 0;
}
this.displayExplainedRecommendations(
result.recommendations,
profile,
result.totalSkillsScanned,
result.reasoningSummary
);
return 0;
} catch (err) {
s?.stop(colors.error('Reasoning analysis failed'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
console.log(colors.muted('Falling back to standard recommendations...'));
console.log('');
const engine = new RecommendationEngine();
engine.loadIndex(index);
const result = engine.recommend(profile, {
limit: this.limit ? parseInt(this.limit, 10) : 10,
minScore: this.minScore ? parseInt(this.minScore, 10) : 30,
categories: this.category,
excludeInstalled: !this.includeInstalled,
includeReasons: this.verbose,
});
this.displayRecommendations(result.recommendations, profile, result.totalSkillsScanned);
return 0;
}
}
private async getProjectProfile(projectPath: string): Promise<ProjectProfile | null> {
const manager = new ContextManager(projectPath);
let context = manager.get();
@@ -276,6 +355,97 @@ export class RecommendCommand extends Command {
console.log(colors.muted('Install with: skillkit install <source>'));
}
private displayExplainedRecommendations(
recommendations: ExplainedScoredSkill[],
profile: ProjectProfile,
totalScanned: number,
reasoningSummary?: string
): void {
this.showProjectProfile(profile);
if (reasoningSummary && !this.quiet) {
console.log(colors.dim('Reasoning: ') + colors.muted(reasoningSummary));
console.log('');
}
if (recommendations.length === 0) {
warn('No matching skills found.');
console.log(colors.muted('Try lowering the minimum score with --min-score'));
return;
}
console.log(colors.bold(`Explained Recommendations (${recommendations.length} of ${totalScanned} scanned):`));
console.log('');
for (const rec of recommendations) {
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}%`)} ${colors.dim(scoreBar)} ${colors.bold(rec.skill.name)}${qualityDisplay}`);
if (this.showPath && rec.treePath && rec.treePath.length > 0) {
console.log(` ${colors.accent('Path:')} ${rec.treePath.join(' > ')}`);
}
if (rec.skill.description) {
console.log(` ${colors.muted(truncate(rec.skill.description, 70))}`);
}
if (rec.skill.source) {
console.log(` ${colors.dim('Source:')} ${rec.skill.source}`);
}
if (this.explain && rec.explanation) {
console.log(colors.dim(' Why this skill:'));
if (rec.explanation.matchedBecause.length > 0) {
console.log(` ${colors.success('├─')} Matched: ${rec.explanation.matchedBecause.join(', ')}`);
}
if (rec.explanation.relevantFor.length > 0) {
console.log(` ${colors.accent('├─')} Relevant for: ${rec.explanation.relevantFor.join(', ')}`);
}
if (rec.explanation.confidence) {
const confidenceColor = rec.explanation.confidence === 'high' ? colors.success :
rec.explanation.confidence === 'medium' ? colors.warning :
colors.muted;
console.log(` ${colors.dim('└─')} Confidence: ${confidenceColor(rec.explanation.confidence)}`);
}
}
if (this.verbose && rec.reasons.length > 0) {
console.log(colors.dim(' Score breakdown:'));
for (const reason of rec.reasons.filter(r => r.weight > 0)) {
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(` ${colors.warning(symbols.warning)} ${warning}`);
}
}
console.log('');
}
console.log(colors.muted('Install with: skillkit install <source>'));
console.log(colors.muted('More details: skillkit recommend --explain --verbose'));
}
private handleSearch(engine: RecommendationEngine, query: string): number {
if (!this.quiet && !this.json) {
header(`Search: "${query}"`);
+5 -6
View File
@@ -1,7 +1,7 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { Command, Option } from 'clipanion';
import { loadConfig, findAllSkills } from '@skillkit/core';
import { findAllSkills } from '@skillkit/core';
import type { AgentType } from '@skillkit/core';
import { getAdapter, detectAgent, getAllAdapters } from '@skillkit/agents';
import { getSearchDirs, getAgentConfigPath } from '../helpers.js';
@@ -67,10 +67,9 @@ export class SyncCommand extends Command {
if (this.agent) {
agentType = this.agent as AgentType;
} else if (isInteractive) {
// Let user select agent
// Let user select agent - always detect, don't rely on default config
s.start('Detecting agent...');
const config = loadConfig();
const detected = config.agent || (await detectAgent());
const detected = await detectAgent();
s.stop(`Detected: ${formatAgent(detected)}`);
const allAgents = getAllAdapters().map(a => a.type);
@@ -92,8 +91,8 @@ export class SyncCommand extends Command {
agentType = agentResult as AgentType;
} else {
const config = loadConfig();
agentType = config.agent || (await detectAgent());
// Non-interactive: always detect, don't rely on default config
agentType = await detectAgent();
}
const adapter = getAdapter(agentType);
+266
View File
@@ -0,0 +1,266 @@
import { Command, Option } from 'clipanion';
import { join } from 'node:path';
import { homedir } from 'node:os';
import {
loadIndex as loadIndexFromCache,
generateSkillTree,
saveTree,
loadTree,
type SkillTree,
type TreeNode,
} from '@skillkit/core';
import {
header,
colors,
symbols,
spinner,
warn,
} from '../onboarding/index.js';
const TREE_PATH = join(homedir(), '.skillkit', 'skill-tree.json');
export class TreeCommand extends Command {
static override paths = [['tree']];
static override usage = Command.Usage({
description: 'Browse skills in a hierarchical tree structure',
details: `
The tree command displays skills organized in a hierarchical taxonomy.
Navigate through categories like Development, Testing, DevOps, AI/ML, etc.
Features:
- Visual tree structure of all skills
- Filter by category path (e.g., "Frontend > React")
- Generate tree from skill index
- Export to markdown format
`,
examples: [
['Show full tree', '$0 tree'],
['Show specific category', '$0 tree Frontend'],
['Show subcategory', '$0 tree "Frontend > React"'],
['Limit depth', '$0 tree --depth 2'],
['Generate/update tree', '$0 tree --generate'],
['Export to markdown', '$0 tree --markdown'],
['Show tree stats', '$0 tree --stats'],
],
});
treePath = Option.String({ required: false });
depth = Option.String('--depth,-d', {
description: 'Maximum depth to display',
});
generate = Option.Boolean('--generate,-g', false, {
description: 'Generate/update tree from skill index',
});
markdown = Option.Boolean('--markdown,-m', false, {
description: 'Output in markdown format',
});
stats = Option.Boolean('--stats,-s', false, {
description: 'Show tree statistics',
});
json = Option.Boolean('--json,-j', false, {
description: 'Output in JSON format',
});
quiet = Option.Boolean('--quiet,-q', false, {
description: 'Minimal output',
});
async execute(): Promise<number> {
if (this.generate) {
return await this.generateTree();
}
const tree = this.loadOrGenerateTree();
if (!tree) {
warn('No skill tree found. Run "skillkit tree --generate" first.');
return 1;
}
if (this.stats) {
return this.showStats(tree);
}
if (this.json) {
console.log(JSON.stringify(tree, null, 2));
return 0;
}
if (this.markdown) {
const { treeToMarkdown } = await import('@skillkit/core');
console.log(treeToMarkdown(tree));
return 0;
}
return this.displayTree(tree);
}
private async generateTree(): Promise<number> {
if (!this.quiet) {
header('Generate Skill Tree');
}
const index = loadIndexFromCache();
if (!index || index.skills.length === 0) {
warn('No skill index found. Run "skillkit recommend --update" first.');
return 1;
}
const s = spinner();
s.start('Generating skill tree...');
try {
const tree = generateSkillTree(index.skills);
saveTree(tree, TREE_PATH);
s.stop(`Generated tree with ${tree.totalCategories} categories`);
console.log('');
console.log(colors.success(`${symbols.success} Tree generated successfully`));
console.log(colors.muted(` Total skills: ${tree.totalSkills}`));
console.log(colors.muted(` Categories: ${tree.totalCategories}`));
console.log(colors.muted(` Max depth: ${tree.maxDepth}`));
console.log(colors.muted(` Saved to: ${TREE_PATH}`));
console.log('');
return 0;
} catch (err) {
s.stop(colors.error('Failed to generate tree'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
private loadOrGenerateTree(): SkillTree | null {
let tree = loadTree(TREE_PATH);
if (!tree) {
const index = loadIndexFromCache();
if (index && index.skills.length > 0) {
tree = generateSkillTree(index.skills);
saveTree(tree, TREE_PATH);
}
}
return tree;
}
private showStats(tree: SkillTree): number {
if (!this.quiet) {
header('Skill Tree Statistics');
}
console.log('');
console.log(colors.bold('Overview:'));
console.log(` Total Skills: ${colors.accent(String(tree.totalSkills))}`);
console.log(` Categories: ${colors.accent(String(tree.totalCategories))}`);
console.log(` Max Depth: ${colors.accent(String(tree.maxDepth))}`);
console.log(` Generated: ${colors.muted(tree.generatedAt)}`);
console.log('');
console.log(colors.bold('Top-Level Categories:'));
for (const child of tree.rootNode.children) {
const percentage = tree.totalSkills > 0
? ((child.skillCount / tree.totalSkills) * 100).toFixed(1)
: '0.0';
console.log(
` ${colors.accent(child.name.padEnd(15))} ${String(child.skillCount).padStart(6)} skills (${percentage}%)`
);
if (child.children.length > 0) {
const subcats = child.children
.sort((a, b) => b.skillCount - a.skillCount)
.slice(0, 3)
.map((c) => `${c.name} (${c.skillCount})`)
.join(', ');
console.log(` ${colors.muted(subcats)}`);
}
}
console.log('');
return 0;
}
private displayTree(tree: SkillTree): number {
if (!this.quiet) {
header('Skill Tree');
console.log(colors.muted(`${tree.totalSkills} skills in ${tree.totalCategories} categories`));
console.log('');
}
let targetNode: TreeNode = tree.rootNode;
if (this.treePath) {
const segments = this.treePath.split('>').map((s) => s.trim());
let current = tree.rootNode;
for (const segment of segments) {
const child = current.children.find(
(c) => c.name.toLowerCase() === segment.toLowerCase()
);
if (!child) {
warn(`Category not found: ${segment}`);
console.log(colors.muted(`Available categories: ${current.children.map((c) => c.name).join(', ')}`));
return 1;
}
current = child;
}
targetNode = current;
}
let maxDepth = this.depth ? parseInt(this.depth, 10) : 3;
if (Number.isNaN(maxDepth) || maxDepth < 0) {
warn('Invalid depth value. Using default depth of 3.');
maxDepth = 3;
}
this.renderNode(targetNode, '', true, 0, maxDepth);
console.log('');
console.log(colors.muted('Navigate: skillkit tree "Category > Subcategory"'));
console.log(colors.muted('Generate: skillkit tree --generate'));
return 0;
}
private renderNode(
node: TreeNode,
prefix: string,
isLast: boolean,
depth: number,
maxDepth: number
): void {
if (depth > maxDepth) return;
const connector = depth === 0 ? '' : isLast ? '└── ' : '├── ';
const icon = node.children.length > 0 ? '📁 ' : '📄 ';
const skillInfo =
node.skillCount > 0 ? colors.muted(` (${node.skillCount})`) : '';
const nameColor = depth === 0 ? colors.bold : depth === 1 ? colors.accent : colors.dim;
console.log(`${prefix}${connector}${icon}${nameColor(node.name)}${skillInfo}`);
if (depth === maxDepth && node.skills.length > 0 && node.skills.length <= 5) {
const childPrefix = prefix + (isLast ? ' ' : '│ ');
for (const skill of node.skills) {
console.log(`${childPrefix} • ${colors.muted(skill)}`);
}
}
const newPrefix = prefix + (depth === 0 ? '' : isLast ? ' ' : '│ ');
if (depth < maxDepth) {
node.children.forEach((child, index) => {
const childIsLast = index === node.children.length - 1;
this.renderNode(child, newPrefix, childIsLast, depth + 1, maxDepth);
});
} else if (node.children.length > 0) {
console.log(`${newPrefix} ${colors.muted(`... ${node.children.length} more subcategories`)}`);
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/core",
"version": "1.8.0",
"version": "1.9.0",
"description": "Core functionality for SkillKit - skill discovery, parsing, and translation",
"type": "module",
"main": "./dist/index.js",
@@ -0,0 +1,332 @@
/**
* Skill to Subagent Converter Tests
*/
import { describe, it, expect } from 'vitest';
import {
skillToSubagent,
generateSubagentFromSkill,
} from '../skill-converter.js';
import type { Skill } from '../../types.js';
describe('Skill Converter', () => {
const mockSkill: Skill = {
name: 'code-simplifier',
description: 'Simplifies and refines code for clarity and maintainability',
path: '/path/to/skills/code-simplifier',
location: 'project',
enabled: true,
};
const mockSkillContent = `---
name: code-simplifier
description: Simplifies and refines code for clarity and maintainability
version: "1.0.0"
author: skillkit
tags: [refactoring, code-quality]
allowed-tools: Edit, Read, Grep
---
# Code Simplifier
You are an expert at simplifying code.
## Guidelines
- Remove unnecessary complexity
- Improve readability
- Preserve functionality
`;
describe('skillToSubagent', () => {
it('should convert skill to canonical agent in reference mode', () => {
const result = skillToSubagent(mockSkill, mockSkillContent);
expect(result.name).toBe('code-simplifier');
expect(result.description).toBe('Simplifies and refines code for clarity and maintainability');
expect(result.skills).toEqual(['code-simplifier']);
expect(result.sourceFormat).toBe('claude-agent');
expect(result.userInvocable).toBe(true);
});
it('should not include skills array in inline mode', () => {
const result = skillToSubagent(mockSkill, mockSkillContent, { inline: true });
expect(result.name).toBe('code-simplifier');
expect(result.skills).toBeUndefined();
expect(result.content).toContain('Code Simplifier');
expect(result.content).toContain('Remove unnecessary complexity');
});
it('should parse allowed-tools from skill frontmatter', () => {
const result = skillToSubagent(mockSkill, mockSkillContent);
expect(result.allowedTools).toEqual(['Edit', 'Read', 'Grep']);
});
it('should use option tools over frontmatter tools', () => {
const result = skillToSubagent(mockSkill, mockSkillContent, {
tools: ['Bash', 'Write'],
});
expect(result.allowedTools).toEqual(['Bash', 'Write']);
});
it('should set model from options', () => {
const result = skillToSubagent(mockSkill, mockSkillContent, {
model: 'opus',
});
expect(result.model).toBe('opus');
});
it('should not set model when inherit is specified', () => {
const result = skillToSubagent(mockSkill, mockSkillContent, {
model: 'inherit',
});
expect(result.model).toBeUndefined();
});
it('should set permission mode from options', () => {
const result = skillToSubagent(mockSkill, mockSkillContent, {
permissionMode: 'plan',
});
expect(result.permissionMode).toBe('plan');
});
it('should set disallowed tools from options', () => {
const result = skillToSubagent(mockSkill, mockSkillContent, {
disallowedTools: ['Bash', 'Write'],
});
expect(result.disallowedTools).toEqual(['Bash', 'Write']);
});
it('should preserve version and author from frontmatter', () => {
const result = skillToSubagent(mockSkill, mockSkillContent);
expect(result.version).toBe('1.0.0');
expect(result.author).toBe('skillkit');
});
it('should preserve tags from frontmatter', () => {
const result = skillToSubagent(mockSkill, mockSkillContent);
expect(result.tags).toEqual(['refactoring', 'code-quality']);
});
});
describe('generateSubagentFromSkill', () => {
it('should generate valid markdown with frontmatter in reference mode', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
expect(content).toContain('---');
expect(content).toContain('name: code-simplifier');
expect(content).toContain('description: Simplifies and refines code');
expect(content).toContain('skills:');
expect(content).toContain(' - code-simplifier');
expect(content).toContain('user-invocable: true');
});
it('should generate valid markdown in inline mode', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, { inline: true });
expect(content).toContain('---');
expect(content).toContain('name: code-simplifier');
expect(content).not.toContain('skills:');
expect(content).toContain('# Code Simplifier');
expect(content).toContain('Remove unnecessary complexity');
});
it('should include tools in frontmatter', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
expect(content).toContain('tools:');
expect(content).toContain(' - Edit');
expect(content).toContain(' - Read');
expect(content).toContain(' - Grep');
});
it('should include model in frontmatter when specified', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, {
model: 'opus',
});
expect(content).toContain('model: opus');
});
it('should include permission mode in frontmatter when specified', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, {
permissionMode: 'plan',
});
expect(content).toContain('permissionMode: plan');
});
it('should include disallowed tools in frontmatter when specified', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, {
disallowedTools: ['Bash'],
});
expect(content).toContain('disallowedTools:');
expect(content).toContain(' - Bash');
});
it('should include version and author in frontmatter', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
expect(content).toContain('version: "1.0.0"');
expect(content).toContain('author: skillkit');
});
it('should include tags in frontmatter', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
expect(content).toContain('tags: [refactoring, code-quality]');
});
it('should generate reference content with skill description', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent);
expect(content).toContain('# Code Simplifier');
expect(content).toContain('uses the "code-simplifier" skill');
expect(content).toContain('## Skill Description');
expect(content).toContain('Simplifies and refines code');
});
it('should embed full skill content in inline mode', () => {
const content = generateSubagentFromSkill(mockSkill, mockSkillContent, { inline: true });
expect(content).toContain('You are a specialized assistant');
expect(content).toContain('Remove unnecessary complexity');
expect(content).toContain('Improve readability');
expect(content).toContain('Preserve functionality');
});
});
describe('edge cases', () => {
it('should handle skill without frontmatter', () => {
const noFrontmatterContent = `# Simple Skill
Just some content without frontmatter.
`;
const result = skillToSubagent(mockSkill, noFrontmatterContent);
expect(result.name).toBe('code-simplifier');
expect(result.description).toBe('Simplifies and refines code for clarity and maintainability');
expect(result.allowedTools).toBeUndefined();
});
it('should handle skill with empty allowed-tools', () => {
const contentWithEmptyTools = `---
name: test-skill
description: Test
allowed-tools:
---
Content here.
`;
const skill: Skill = {
name: 'test-skill',
description: 'Test',
path: '/path/to/test-skill',
location: 'project',
enabled: true,
};
const result = skillToSubagent(skill, contentWithEmptyTools);
expect(result.allowedTools).toBeUndefined();
});
it('should handle skill name with multiple hyphens', () => {
const skill: Skill = {
name: 'my-complex-skill-name',
description: 'A complex skill',
path: '/path/to/skill',
location: 'project',
enabled: true,
};
const content = generateSubagentFromSkill(skill, `---
name: my-complex-skill-name
description: A complex skill
---
Content.
`);
expect(content).toContain('# My Complex Skill Name');
});
it('should handle space-separated allowed-tools format', () => {
const contentWithSpaceSeparated = `---
name: test-skill
description: Test
allowed-tools: Bash(git:*) Read Write Edit
---
Content here.
`;
const skill: Skill = {
name: 'test-skill',
description: 'Test',
path: '/path/to/test-skill',
location: 'project',
enabled: true,
};
const result = skillToSubagent(skill, contentWithSpaceSeparated);
expect(result.allowedTools).toEqual(['Bash(git:*)', 'Read', 'Write', 'Edit']);
});
it('should handle YAML array format for allowed-tools', () => {
const contentWithArrayTools = `---
name: test-skill
description: Test
allowed-tools:
- Read
- Write
- Bash(npm:*)
---
Content here.
`;
const skill: Skill = {
name: 'test-skill',
description: 'Test',
path: '/path/to/test-skill',
location: 'project',
enabled: true,
};
const result = skillToSubagent(skill, contentWithArrayTools);
expect(result.allowedTools).toEqual(['Read', 'Write', 'Bash(npm:*)']);
});
it('should handle CRLF line endings', () => {
const crlfContent = `---\r\nname: test-skill\r\ndescription: Test\r\n---\r\n\r\n# Content\r\n\r\nWith CRLF endings.\r\n`;
const skill: Skill = {
name: 'test-skill',
description: 'Test',
path: '/path/to/test-skill',
location: 'project',
enabled: true,
};
const result = skillToSubagent(skill, crlfContent, { inline: true });
expect(result.content).toContain('# Content');
expect(result.content).toContain('With CRLF endings.');
});
});
});
+8
View File
@@ -60,3 +60,11 @@ export {
getAgentTargetDirectory,
isAgentCompatible,
} from './translator.js';
// Skill Converter
export {
skillToSubagent,
generateSubagentFromSkill,
loadAndConvertSkill,
type SkillToSubagentOptions,
} from './skill-converter.js';
+285
View File
@@ -0,0 +1,285 @@
/**
* Skill to Subagent Converter
*
* Converts SkillKit skills into Claude Code native subagent format (.md files).
* Supports both reference mode (skills: [skill-name]) and inline mode (embedded content).
*/
import type { Skill, SkillFrontmatter } from '../types.js';
import type { CanonicalAgent, AgentPermissionMode } from './types.js';
import { extractFrontmatter, readSkillContent } from '../skills.js';
/**
* Options for skill-to-subagent conversion
*/
export interface SkillToSubagentOptions {
/** Embed full skill content in system prompt (default: false - use skills reference) */
inline?: boolean;
/** Model to use (sonnet, opus, haiku, inherit) */
model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';
/** Permission mode for the agent */
permissionMode?: AgentPermissionMode;
/** Tools the agent is allowed to use */
tools?: string[];
/** Tools the agent cannot use */
disallowedTools?: string[];
}
/**
* Convert a skill to a CanonicalAgent representation
*/
export function skillToSubagent(
skill: Skill,
skillContent: string,
options?: SkillToSubagentOptions
): CanonicalAgent {
const frontmatter = extractFrontmatter(skillContent) as Partial<SkillFrontmatter> | null;
const inline = options?.inline ?? false;
const allowedTools = parseAllowedTools(frontmatter, options?.tools);
const content = inline
? generateInlineContent(skill, skillContent)
: generateReferenceContent(skill, frontmatter);
return {
name: skill.name,
description: skill.description,
model: options?.model === 'inherit' ? undefined : options?.model,
permissionMode: options?.permissionMode,
disallowedTools: options?.disallowedTools,
allowedTools,
skills: inline ? undefined : [skill.name],
content,
sourceFormat: 'claude-agent',
sourceAgent: 'claude-code',
version: frontmatter?.version,
author: frontmatter?.author,
tags: frontmatter?.tags,
userInvocable: true,
};
}
/**
* Generate the markdown content for a Claude Code subagent from a skill
*/
export function generateSubagentFromSkill(
skill: Skill,
skillContent: string,
options?: SkillToSubagentOptions
): string {
const canonical = skillToSubagent(skill, skillContent, options);
return generateSubagentMarkdown(canonical, options?.inline ?? false);
}
/**
* Parse allowed-tools from skill frontmatter
* Handles both string (comma or space-separated) and array formats
*/
function parseAllowedTools(
frontmatter: Partial<SkillFrontmatter> | null,
optionTools?: string[]
): string[] | undefined {
if (optionTools && optionTools.length > 0) {
return optionTools;
}
const allowedTools = frontmatter?.['allowed-tools'];
if (!allowedTools) {
return undefined;
}
if (Array.isArray(allowedTools)) {
const result = allowedTools
.map(t => (typeof t === 'string' ? t.trim() : ''))
.filter(Boolean);
return result.length > 0 ? result : undefined;
}
if (typeof allowedTools === 'string') {
const result = allowedTools
.split(/[,\s]+/)
.map(t => t.trim())
.filter(Boolean);
return result.length > 0 ? result : undefined;
}
return undefined;
}
/**
* Generate inline content (full skill embedded)
*/
function generateInlineContent(skill: Skill, skillContent: string): string {
const bodyContent = extractBodyContent(skillContent);
const lines: string[] = [];
lines.push(`# ${formatAgentName(skill.name)}`);
lines.push('');
lines.push('You are a specialized assistant powered by the following skill.');
lines.push('');
lines.push('---');
lines.push('');
lines.push(bodyContent.trim());
return lines.join('\n');
}
/**
* Generate reference content (skill referenced by name)
*/
function generateReferenceContent(
skill: Skill,
frontmatter: Partial<SkillFrontmatter> | null
): string {
const lines: string[] = [];
lines.push(`# ${formatAgentName(skill.name)}`);
lines.push('');
lines.push(`You are a specialized assistant that uses the "${skill.name}" skill.`);
lines.push('');
lines.push('## Skill Description');
lines.push('');
lines.push(skill.description);
lines.push('');
lines.push('## Usage');
lines.push('');
lines.push(`This agent automatically loads the "${skill.name}" skill.`);
lines.push('Follow the skill instructions to complete tasks effectively.');
if (frontmatter?.tags && frontmatter.tags.length > 0) {
lines.push('');
lines.push('## Related Topics');
lines.push('');
lines.push(frontmatter.tags.map(t => `- ${t}`).join('\n'));
}
return lines.join('\n');
}
/**
* Generate full subagent markdown file content
*/
function generateSubagentMarkdown(
canonical: CanonicalAgent,
isInline: boolean
): string {
const lines: string[] = ['---'];
lines.push(`name: ${escapeYamlString(canonical.name)}`);
lines.push(`description: ${escapeYamlString(canonical.description)}`);
if (canonical.model) {
lines.push(`model: ${canonical.model}`);
}
if (canonical.permissionMode) {
lines.push(`permissionMode: ${canonical.permissionMode}`);
}
appendYamlList(lines, 'tools', canonical.allowedTools);
appendYamlList(lines, 'disallowedTools', canonical.disallowedTools);
if (!isInline) {
appendYamlList(lines, 'skills', canonical.skills);
}
if (canonical.version) {
lines.push(`version: "${canonical.version}"`);
}
if (canonical.author) {
lines.push(`author: ${escapeYamlString(canonical.author)}`);
}
if (canonical.tags && canonical.tags.length > 0) {
lines.push(`tags: [${canonical.tags.map(t => escapeYamlString(t)).join(', ')}]`);
}
if (canonical.userInvocable !== undefined) {
lines.push(`user-invocable: ${canonical.userInvocable}`);
}
lines.push('---', '', canonical.content);
return lines.join('\n');
}
function appendYamlList(lines: string[], key: string, items?: string[]): void {
if (!items || items.length === 0) return;
lines.push(`${key}:`);
for (const item of items) {
lines.push(` - ${escapeYamlString(item)}`);
}
}
/**
* Extract body content from skill markdown (without frontmatter)
* Handles both Unix (LF) and Windows (CRLF) line endings
*/
function extractBodyContent(content: string): string {
const normalized = content.replace(/\r\n/g, '\n');
const match = normalized.match(/^---\s*\n[\s\S]*?\n---\s*\n([\s\S]*)$/);
if (match) {
return match[1];
}
return content;
}
/**
* Format agent name for display (kebab-case to Title Case)
*/
function formatAgentName(name: string): string {
return name
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
/**
* Escape special characters in YAML strings
* Only escapes when necessary for valid YAML parsing
*/
function escapeYamlString(str: string): string {
if (
str.includes('\n') ||
str.includes(':') ||
str.includes('#') ||
str.startsWith('-') ||
str.startsWith('*') ||
str.startsWith('&') ||
str.startsWith('!') ||
str.startsWith('{') ||
str.startsWith('[') ||
str.startsWith('>') ||
str.startsWith('|') ||
str.startsWith('@') ||
str.startsWith('`') ||
/^['"]/.test(str)
) {
return `"${str.replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
}
return str;
}
/**
* Load a skill and generate subagent content
* Convenience function that reads skill content and generates subagent markdown
*/
export function loadAndConvertSkill(
skill: Skill,
options?: SkillToSubagentOptions
): { success: boolean; content?: string; error?: string } {
const skillContent = readSkillContent(skill.path);
if (!skillContent) {
return {
success: false,
error: `Could not read skill content from: ${skill.path}`,
};
}
try {
const content = generateSubagentFromSkill(skill, skillContent, options);
return { success: true, content };
} catch (err) {
return {
success: false,
error: err instanceof Error ? err.message : 'Unknown error',
};
}
}
+6 -1
View File
@@ -64,7 +64,12 @@ export const AgentFrontmatter = z.object({
/** Allowed tools for this agent */
allowedTools: z.union([
z.array(z.string()),
z.string(), // YAML-style list in frontmatter
z.string(),
]).optional(),
/** Tools (Claude Code native format alias for allowedTools) */
tools: z.union([
z.array(z.string()),
z.string(),
]).optional(),
/** Agent-scoped hooks */
hooks: z.array(AgentHook).optional(),
+22
View File
@@ -0,0 +1,22 @@
export * from './types.js';
export * from './utils.js';
export {
STANDARD_PLACEHOLDERS,
ConnectorCategorySchema,
ConnectorPlaceholderSchema,
ConnectorMappingSchema,
ConnectorConfigSchema,
} from './types.js';
export {
detectPlaceholders,
analyzePlaceholders,
replacePlaceholders,
applyConnectorConfig,
getPlaceholderInfo,
generateConnectorsMarkdown,
createConnectorConfig,
validateConnectorConfig,
suggestMappingsFromMcp,
} from './utils.js';
+162
View File
@@ -0,0 +1,162 @@
import { z } from 'zod';
export const ConnectorCategorySchema = z.enum([
'crm',
'chat',
'email',
'calendar',
'docs',
'data',
'search',
'enrichment',
'analytics',
'storage',
'notifications',
'ai',
'custom',
]);
export type ConnectorCategory = z.infer<typeof ConnectorCategorySchema>;
export const ConnectorPlaceholderSchema = z.object({
placeholder: z.string(),
category: ConnectorCategorySchema,
description: z.string(),
examples: z.array(z.string()).default([]),
required: z.boolean().default(false),
});
export type ConnectorPlaceholder = z.infer<typeof ConnectorPlaceholderSchema>;
export const ConnectorMappingSchema = z.object({
placeholder: z.string(),
tool: z.string(),
mcpServer: z.string().optional(),
config: z.record(z.unknown()).optional(),
});
export type ConnectorMapping = z.infer<typeof ConnectorMappingSchema>;
export const ConnectorConfigSchema = z.object({
version: z.number().default(1),
mappings: z.array(ConnectorMappingSchema),
description: z.string().optional(),
});
export type ConnectorConfig = z.infer<typeof ConnectorConfigSchema>;
export const STANDARD_PLACEHOLDERS: Record<ConnectorCategory, ConnectorPlaceholder> = {
crm: {
placeholder: '~~CRM',
category: 'crm',
description: 'Customer Relationship Management system',
examples: ['Salesforce', 'HubSpot', 'Pipedrive', 'Zoho CRM'],
required: false,
},
chat: {
placeholder: '~~chat',
category: 'chat',
description: 'Team communication and messaging platform',
examples: ['Slack', 'Microsoft Teams', 'Discord'],
required: false,
},
email: {
placeholder: '~~email',
category: 'email',
description: 'Email service for sending and receiving messages',
examples: ['Gmail', 'Outlook', 'SendGrid'],
required: false,
},
calendar: {
placeholder: '~~calendar',
category: 'calendar',
description: 'Calendar and scheduling system',
examples: ['Google Calendar', 'Outlook Calendar', 'Calendly'],
required: false,
},
docs: {
placeholder: '~~docs',
category: 'docs',
description: 'Document management and collaboration',
examples: ['Google Docs', 'Notion', 'Confluence', 'Coda'],
required: false,
},
data: {
placeholder: '~~data',
category: 'data',
description: 'Data warehouse or database',
examples: ['BigQuery', 'Snowflake', 'PostgreSQL', 'Databricks'],
required: false,
},
search: {
placeholder: '~~search',
category: 'search',
description: 'Enterprise search across tools',
examples: ['Glean', 'Elastic', 'Algolia'],
required: false,
},
enrichment: {
placeholder: '~~enrichment',
category: 'enrichment',
description: 'Data enrichment service',
examples: ['Clearbit', 'ZoomInfo', 'Apollo'],
required: false,
},
analytics: {
placeholder: '~~analytics',
category: 'analytics',
description: 'Analytics and reporting platform',
examples: ['Mixpanel', 'Amplitude', 'Google Analytics'],
required: false,
},
storage: {
placeholder: '~~storage',
category: 'storage',
description: 'File storage service',
examples: ['Google Drive', 'Dropbox', 'S3', 'Box'],
required: false,
},
notifications: {
placeholder: '~~notifications',
category: 'notifications',
description: 'Notification and alerting service',
examples: ['PagerDuty', 'Opsgenie', 'SMS'],
required: false,
},
ai: {
placeholder: '~~ai',
category: 'ai',
description: 'AI/ML model or service',
examples: ['OpenAI', 'Anthropic', 'Hugging Face'],
required: false,
},
custom: {
placeholder: '~~custom',
category: 'custom',
description: 'Custom integration',
examples: [],
required: false,
},
};
export interface PlaceholderMatch {
placeholder: string;
category: ConnectorCategory | null;
line: number;
column: number;
context: string;
}
export interface PlaceholderReplacement {
original: string;
replacement: string;
category: ConnectorCategory | null;
}
export interface ConnectorAnalysis {
placeholders: PlaceholderMatch[];
categories: ConnectorCategory[];
requiredCount: number;
optionalCount: number;
hasUnknownPlaceholders: boolean;
}
+268
View File
@@ -0,0 +1,268 @@
import {
type ConnectorCategory,
type ConnectorPlaceholder,
type ConnectorMapping,
type ConnectorConfig,
type PlaceholderMatch,
type PlaceholderReplacement,
type ConnectorAnalysis,
STANDARD_PLACEHOLDERS,
ConnectorCategorySchema,
} from './types.js';
const PLACEHOLDER_REGEX = /~~(\w+)/g;
export function detectPlaceholders(content: string): PlaceholderMatch[] {
const matches: PlaceholderMatch[] = [];
const lines = content.split('\n');
for (let lineNum = 0; lineNum < lines.length; lineNum++) {
const line = lines[lineNum];
let match: RegExpExecArray | null;
const regex = new RegExp(PLACEHOLDER_REGEX.source, 'g');
while ((match = regex.exec(line)) !== null) {
const placeholder = match[0];
const categoryName = match[1].toLowerCase();
let category: ConnectorCategory | null = null;
try {
category = ConnectorCategorySchema.parse(categoryName);
} catch {
category = null;
}
const contextStart = Math.max(0, match.index - 20);
const contextEnd = Math.min(line.length, match.index + placeholder.length + 20);
const context = line.slice(contextStart, contextEnd);
matches.push({
placeholder,
category,
line: lineNum + 1,
column: match.index + 1,
context: context.trim(),
});
}
}
return matches;
}
export function analyzePlaceholders(content: string): ConnectorAnalysis {
const matches = detectPlaceholders(content);
const categories = new Set<ConnectorCategory>();
let requiredCount = 0;
let optionalCount = 0;
let hasUnknownPlaceholders = false;
for (const match of matches) {
if (match.category) {
categories.add(match.category);
const standardPlaceholder = STANDARD_PLACEHOLDERS[match.category];
if (standardPlaceholder?.required) {
requiredCount++;
} else {
optionalCount++;
}
} else {
hasUnknownPlaceholders = true;
}
}
return {
placeholders: matches,
categories: Array.from(categories),
requiredCount,
optionalCount,
hasUnknownPlaceholders,
};
}
export function replacePlaceholders(
content: string,
mappings: ConnectorMapping[]
): { result: string; replacements: PlaceholderReplacement[] } {
const replacements: PlaceholderReplacement[] = [];
let result = content;
for (const mapping of mappings) {
const regex = new RegExp(escapeRegExp(mapping.placeholder), 'g');
const originalMatches = content.match(regex);
if (originalMatches) {
result = result.replace(regex, mapping.tool);
const categoryName = mapping.placeholder.replace('~~', '').toLowerCase();
let category: ConnectorCategory | null = null;
try {
category = ConnectorCategorySchema.parse(categoryName);
} catch {
category = null;
}
replacements.push({
original: mapping.placeholder,
replacement: mapping.tool,
category,
});
}
}
return { result, replacements };
}
export function applyConnectorConfig(
content: string,
config: ConnectorConfig
): { result: string; replacements: PlaceholderReplacement[] } {
return replacePlaceholders(content, config.mappings);
}
export function getPlaceholderInfo(placeholder: string): ConnectorPlaceholder | null {
const categoryName = placeholder.replace('~~', '').toLowerCase();
try {
const category = ConnectorCategorySchema.parse(categoryName);
return STANDARD_PLACEHOLDERS[category];
} catch {
return null;
}
}
export function generateConnectorsMarkdown(analysis: ConnectorAnalysis): string {
const lines: string[] = [];
lines.push('# Connectors');
lines.push('');
lines.push('This skill uses the following connector placeholders. Replace them with your specific tools.');
lines.push('');
lines.push('| Placeholder | Category | Description | Examples |');
lines.push('|-------------|----------|-------------|----------|');
for (const match of analysis.placeholders) {
if (match.category) {
const info = STANDARD_PLACEHOLDERS[match.category];
lines.push(
`| \`${match.placeholder}\` | ${match.category} | ${info.description} | ${info.examples.slice(0, 3).join(', ')} |`
);
} else {
lines.push(
`| \`${match.placeholder}\` | custom | Custom integration | - |`
);
}
}
lines.push('');
lines.push('## How to Customize');
lines.push('');
lines.push('1. Find all placeholders: `grep -n "~~" SKILL.md`');
lines.push('2. Replace each `~~category` with your specific tool name');
lines.push('3. Configure MCP server in `.mcp.json` if needed');
lines.push('');
return lines.join('\n');
}
export function createConnectorConfig(
mappings: Array<{ placeholder: string; tool: string; mcpServer?: string }>
): ConnectorConfig {
return {
version: 1,
mappings: mappings.map((m) => ({
placeholder: m.placeholder,
tool: m.tool,
mcpServer: m.mcpServer,
})),
};
}
export function validateConnectorConfig(
config: ConnectorConfig,
content: string
): { valid: boolean; errors: string[]; warnings: string[] } {
const errors: string[] = [];
const warnings: string[] = [];
const analysis = analyzePlaceholders(content);
const placeholdersInContent = new Set(analysis.placeholders.map((p) => p.placeholder));
const mappedPlaceholders = new Set(config.mappings.map((m) => m.placeholder));
for (const placeholder of placeholdersInContent) {
if (!mappedPlaceholders.has(placeholder)) {
const info = getPlaceholderInfo(placeholder);
if (info?.required) {
errors.push(`Required placeholder ${placeholder} is not mapped`);
} else {
warnings.push(`Optional placeholder ${placeholder} is not mapped`);
}
}
}
for (const mapping of config.mappings) {
if (!placeholdersInContent.has(mapping.placeholder)) {
warnings.push(`Mapping for ${mapping.placeholder} exists but placeholder not found in content`);
}
}
return {
valid: errors.length === 0,
errors,
warnings,
};
}
export function suggestMappingsFromMcp(
mcpServers: string[]
): ConnectorMapping[] {
const suggestions: ConnectorMapping[] = [];
const serverLower = mcpServers.map((s) => s.toLowerCase());
const serverToCategory: Record<string, { category: ConnectorCategory; tool: string }[]> = {
slack: [{ category: 'chat', tool: 'Slack' }],
teams: [{ category: 'chat', tool: 'Microsoft Teams' }],
discord: [{ category: 'chat', tool: 'Discord' }],
gmail: [{ category: 'email', tool: 'Gmail' }],
outlook: [{ category: 'email', tool: 'Outlook' }],
sendgrid: [{ category: 'email', tool: 'SendGrid' }],
salesforce: [{ category: 'crm', tool: 'Salesforce' }],
hubspot: [{ category: 'crm', tool: 'HubSpot' }],
pipedrive: [{ category: 'crm', tool: 'Pipedrive' }],
notion: [{ category: 'docs', tool: 'Notion' }],
confluence: [{ category: 'docs', tool: 'Confluence' }],
google: [
{ category: 'docs', tool: 'Google Docs' },
{ category: 'calendar', tool: 'Google Calendar' },
{ category: 'storage', tool: 'Google Drive' },
],
bigquery: [{ category: 'data', tool: 'BigQuery' }],
snowflake: [{ category: 'data', tool: 'Snowflake' }],
postgres: [{ category: 'data', tool: 'PostgreSQL' }],
supabase: [{ category: 'data', tool: 'Supabase' }],
clearbit: [{ category: 'enrichment', tool: 'Clearbit' }],
zoominfo: [{ category: 'enrichment', tool: 'ZoomInfo' }],
apollo: [{ category: 'enrichment', tool: 'Apollo' }],
openai: [{ category: 'ai', tool: 'OpenAI' }],
anthropic: [{ category: 'ai', tool: 'Anthropic Claude' }],
};
for (const server of serverLower) {
for (const [keyword, mappings] of Object.entries(serverToCategory)) {
if (server.includes(keyword)) {
for (const mapping of mappings) {
suggestions.push({
placeholder: STANDARD_PLACEHOLDERS[mapping.category].placeholder,
tool: mapping.tool,
mcpServer: server,
});
}
}
}
}
return suggestions;
}
function escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
+23
View File
@@ -0,0 +1,23 @@
export * from './types.js';
export * from './manager.js';
export * from './mode.js';
export {
ExecutionManager,
createExecutionManager,
} from './manager.js';
export {
ExecutionStepStatusSchema,
ExecutionStepSchema,
ExecutionFlowSchema,
} from './types.js';
export {
detectExecutionMode,
getModeDescription,
requireEnhancedMode,
requireCapability,
getStandaloneAlternative,
createModeAwareExecutor,
} from './mode.js';
+314
View File
@@ -0,0 +1,314 @@
import { randomUUID } from 'node:crypto';
import {
type ExecutionFlow,
type ExecutionStep,
type ExecutionFlowConfig,
type StepDefinition,
type ExecutionContext,
type FlowSummary,
type FlowMetrics,
ExecutionFlowSchema,
} from './types.js';
const DEFAULT_MAX_RETRIES = 3;
const DEFAULT_RETRY_DELAY = 1000;
const DEFAULT_TIMEOUT = 30000;
export class ExecutionManager {
private flows: Map<string, ExecutionFlow> = new Map();
private stepDefinitions: Map<string, Map<string, StepDefinition>> = new Map();
private config: ExecutionFlowConfig;
private metrics: FlowMetrics;
constructor(config: ExecutionFlowConfig = {}) {
this.config = config;
this.metrics = {
totalFlows: 0,
completedFlows: 0,
failedFlows: 0,
averageDuration: 0,
stepMetrics: new Map(),
};
}
createFlow(
skillName: string,
steps: Array<{ name: string; description?: string }>,
options: {
mode?: 'standalone' | 'enhanced';
mcpServers?: string[];
context?: Record<string, unknown>;
} = {}
): ExecutionFlow {
const flowId = randomUUID();
const executionSteps: ExecutionStep[] = steps.map((step, index) => ({
id: `${flowId}-step-${index}`,
name: step.name,
description: step.description,
status: 'pending',
retryCount: 0,
}));
const flow: ExecutionFlow = ExecutionFlowSchema.parse({
id: flowId,
skillName,
version: 1,
steps: executionSteps,
currentStepIndex: -1,
status: 'pending',
context: options.context,
mode: options.mode || 'standalone',
mcpServers: options.mcpServers,
});
this.flows.set(flowId, flow);
this.metrics.totalFlows++;
return flow;
}
registerStepDefinitions(skillName: string, definitions: StepDefinition[]): void {
const skillSteps = new Map<string, StepDefinition>();
for (const def of definitions) {
skillSteps.set(def.name, def);
}
this.stepDefinitions.set(skillName, skillSteps);
}
async executeFlow(flowId: string): Promise<ExecutionFlow> {
const flow = this.flows.get(flowId);
if (!flow) {
throw new Error(`Flow ${flowId} not found`);
}
flow.status = 'running';
flow.startedAt = new Date().toISOString();
const skillSteps = this.stepDefinitions.get(flow.skillName);
try {
let previousOutput: Record<string, unknown> = {};
for (let i = 0; i < flow.steps.length; i++) {
const step = flow.steps[i];
flow.currentStepIndex = i;
const context: ExecutionContext = {
flow,
stepIndex: i,
previousOutput,
mcpTools: flow.mcpServers,
isEnhanced: flow.mode === 'enhanced',
};
const stepDef = skillSteps?.get(step.name);
if (stepDef?.condition && !stepDef.condition(context)) {
step.status = 'skipped';
continue;
}
const result = await this.executeStep(step, stepDef, context);
if (result.status === 'completed' && result.output) {
previousOutput = { ...previousOutput, ...result.output };
}
if (result.status === 'failed') {
flow.status = 'failed';
flow.completedAt = new Date().toISOString();
flow.totalDuration = this.calculateDuration(flow.startedAt, flow.completedAt);
this.metrics.failedFlows++;
this.config.onFlowComplete?.(flow);
return flow;
}
}
flow.status = 'completed';
flow.completedAt = new Date().toISOString();
flow.totalDuration = this.calculateDuration(flow.startedAt, flow.completedAt);
this.metrics.completedFlows++;
this.updateAverageDuration(flow.totalDuration);
this.config.onFlowComplete?.(flow);
return flow;
} catch (error) {
flow.status = 'failed';
flow.completedAt = new Date().toISOString();
flow.totalDuration = this.calculateDuration(flow.startedAt, flow.completedAt);
this.metrics.failedFlows++;
throw error;
}
}
private async executeStep(
step: ExecutionStep,
stepDef: StepDefinition | undefined,
context: ExecutionContext
): Promise<ExecutionStep> {
const maxRetries = this.config.maxRetries ?? DEFAULT_MAX_RETRIES;
const retryDelay = this.config.retryDelay ?? DEFAULT_RETRY_DELAY;
const timeout = stepDef?.timeout ?? this.config.timeout ?? DEFAULT_TIMEOUT;
step.status = 'running';
step.startedAt = new Date().toISOString();
this.config.onStepStart?.(step, context.flow);
let lastError: Error | null = null;
while (step.retryCount <= maxRetries) {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
try {
if (stepDef) {
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(
() => reject(new Error(`Step ${step.name} timed out`)),
timeout
);
});
const executePromise = stepDef.execute(step.input || {}, context);
try {
step.output = await Promise.race([executePromise, timeoutPromise]);
} finally {
if (timeoutId) clearTimeout(timeoutId);
}
}
step.status = 'completed';
step.completedAt = new Date().toISOString();
step.duration = this.calculateDuration(step.startedAt, step.completedAt);
this.config.onStepComplete?.(step, context.flow);
this.updateStepMetrics(step.name, true, step.duration);
return step;
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
step.retryCount++;
if (stepDef?.retryable !== false && step.retryCount <= maxRetries) {
await this.delay(retryDelay * step.retryCount);
} else {
break;
}
}
}
step.status = 'failed';
step.error = lastError?.message || 'Unknown error';
step.completedAt = new Date().toISOString();
step.duration = this.calculateDuration(step.startedAt, step.completedAt);
this.config.onStepError?.(step, lastError || new Error('Unknown error'), context.flow);
this.updateStepMetrics(step.name, false, step.duration);
return step;
}
getFlow(flowId: string): ExecutionFlow | undefined {
return this.flows.get(flowId);
}
getFlowSummary(flowId: string): FlowSummary | null {
const flow = this.flows.get(flowId);
if (!flow) return null;
const completedSteps = flow.steps.filter(
(s) => s.status === 'completed' || s.status === 'skipped'
).length;
const currentStep =
flow.currentStepIndex >= 0 ? flow.steps[flow.currentStepIndex]?.name : undefined;
return {
id: flow.id,
skillName: flow.skillName,
status: flow.status,
progress: flow.steps.length > 0 ? (completedSteps / flow.steps.length) * 100 : 0,
currentStep,
startedAt: flow.startedAt,
completedAt: flow.completedAt,
totalDuration: flow.totalDuration,
stepsCompleted: completedSteps,
totalSteps: flow.steps.length,
mode: flow.mode,
};
}
getAllFlowSummaries(): FlowSummary[] {
return [...this.flows.keys()]
.map((id) => this.getFlowSummary(id))
.filter((s): s is FlowSummary => s !== null);
}
getMetrics(): FlowMetrics {
return { ...this.metrics };
}
cancelFlow(flowId: string): boolean {
const flow = this.flows.get(flowId);
if (!flow || flow.status !== 'running') return false;
flow.status = 'failed';
flow.completedAt = new Date().toISOString();
const currentStep = flow.steps[flow.currentStepIndex];
if (currentStep && currentStep.status === 'running') {
currentStep.status = 'failed';
currentStep.error = 'Cancelled';
currentStep.completedAt = new Date().toISOString();
}
return true;
}
clearCompletedFlows(): number {
let cleared = 0;
for (const [id, flow] of this.flows) {
if (flow.status === 'completed' || flow.status === 'failed') {
this.flows.delete(id);
cleared++;
}
}
return cleared;
}
private calculateDuration(start?: string, end?: string): number {
if (!start || !end) return 0;
return new Date(end).getTime() - new Date(start).getTime();
}
private updateAverageDuration(duration: number): void {
const completedCount = this.metrics.completedFlows;
this.metrics.averageDuration =
(this.metrics.averageDuration * (completedCount - 1) + duration) / completedCount;
}
private updateStepMetrics(stepName: string, success: boolean, duration: number): void {
const existing = this.metrics.stepMetrics.get(stepName) || {
executionCount: 0,
successCount: 0,
failureCount: 0,
averageDuration: 0,
};
existing.executionCount++;
if (success) {
existing.successCount++;
} else {
existing.failureCount++;
}
existing.averageDuration =
(existing.averageDuration * (existing.executionCount - 1) + duration) /
existing.executionCount;
this.metrics.stepMetrics.set(stepName, existing);
}
private delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
export function createExecutionManager(config?: ExecutionFlowConfig): ExecutionManager {
return new ExecutionManager(config);
}
+257
View File
@@ -0,0 +1,257 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { ConnectorMapping } from '../connectors/types.js';
import { suggestMappingsFromMcp } from '../connectors/utils.js';
export type ExecutionMode = 'standalone' | 'enhanced';
export interface ModeDetectionResult {
mode: ExecutionMode;
availableServers: string[];
missingServers: string[];
capabilities: ModeCapabilities;
connectorMappings: ConnectorMapping[];
}
export interface ModeCapabilities {
canAccessCRM: boolean;
canSendEmails: boolean;
canAccessCalendar: boolean;
canAccessDocs: boolean;
canQueryData: boolean;
canEnrichData: boolean;
canSendNotifications: boolean;
canUseAI: boolean;
hasChat: boolean;
hasStorage: boolean;
hasSearch: boolean;
hasAnalytics: boolean;
}
export interface ExecutionModeConfig {
requiredServers?: string[];
optionalServers?: string[];
mcpConfigPaths?: string[];
fallbackToStandalone?: boolean;
}
const DEFAULT_MCP_CONFIG_PATHS = [
join(homedir(), '.mcp.json'),
join(homedir(), '.config', 'claude', 'mcp.json'),
'.mcp.json',
'mcp.json',
];
const CAPABILITY_SERVERS: Record<keyof ModeCapabilities, string[]> = {
canAccessCRM: ['salesforce', 'hubspot', 'pipedrive', 'zoho'],
canSendEmails: ['gmail', 'outlook', 'sendgrid', 'mailgun', 'ses'],
canAccessCalendar: ['google-calendar', 'outlook', 'calendly'],
canAccessDocs: ['notion', 'confluence', 'google-docs', 'coda'],
canQueryData: ['postgres', 'mysql', 'bigquery', 'snowflake', 'supabase', 'mongodb'],
canEnrichData: ['clearbit', 'zoominfo', 'apollo', 'hunter'],
canSendNotifications: ['slack', 'teams', 'discord', 'pagerduty', 'opsgenie'],
canUseAI: ['openai', 'anthropic', 'ollama', 'huggingface'],
hasChat: ['slack', 'teams', 'discord'],
hasStorage: ['s3', 'gcs', 'dropbox', 'drive', 'box'],
hasSearch: ['glean', 'elastic', 'algolia', 'typesense'],
hasAnalytics: ['mixpanel', 'amplitude', 'posthog', 'segment'],
};
export function detectExecutionMode(config: ExecutionModeConfig = {}): ModeDetectionResult {
const { requiredServers = [], optionalServers = [], mcpConfigPaths, fallbackToStandalone = true } = config;
const configPaths = mcpConfigPaths || DEFAULT_MCP_CONFIG_PATHS;
const availableServers = detectMcpServers(configPaths);
const missingRequired = requiredServers.filter(
(server) => !availableServers.some((s) => s.toLowerCase().includes(server.toLowerCase()))
);
const capabilities = detectCapabilities(availableServers);
const connectorMappings = suggestMappingsFromMcp(availableServers);
let mode: ExecutionMode = 'standalone';
if (missingRequired.length === 0 && availableServers.length > 0) {
mode = 'enhanced';
} else if (missingRequired.length > 0 && !fallbackToStandalone) {
throw new Error(`Missing required MCP servers: ${missingRequired.join(', ')}`);
}
const missingOptional = optionalServers.filter(
(server) => !availableServers.some((s) => s.toLowerCase().includes(server.toLowerCase()))
);
return {
mode,
availableServers,
missingServers: [...missingRequired, ...missingOptional],
capabilities,
connectorMappings,
};
}
function detectMcpServers(configPaths: string[]): string[] {
const servers: string[] = [];
for (const configPath of configPaths) {
try {
const fullPath = configPath.startsWith('~')
? configPath.replace('~', process.env.HOME || '')
: configPath;
if (existsSync(fullPath)) {
const content = readFileSync(fullPath, 'utf-8');
const config = JSON.parse(content);
if (config.mcpServers) {
servers.push(...Object.keys(config.mcpServers));
}
if (config.servers) {
servers.push(...Object.keys(config.servers));
}
}
} catch {
continue;
}
}
return [...new Set(servers)];
}
function detectCapabilities(servers: string[]): ModeCapabilities {
const serverLower = servers.map((s) => s.toLowerCase());
const capabilities: ModeCapabilities = {
canAccessCRM: false,
canSendEmails: false,
canAccessCalendar: false,
canAccessDocs: false,
canQueryData: false,
canEnrichData: false,
canSendNotifications: false,
canUseAI: false,
hasChat: false,
hasStorage: false,
hasSearch: false,
hasAnalytics: false,
};
for (const [capability, keywords] of Object.entries(CAPABILITY_SERVERS)) {
for (const keyword of keywords) {
if (serverLower.some((server) => server.includes(keyword))) {
capabilities[capability as keyof ModeCapabilities] = true;
break;
}
}
}
return capabilities;
}
export function getModeDescription(result: ModeDetectionResult): string {
const lines: string[] = [];
lines.push(`Mode: ${result.mode.toUpperCase()}`);
lines.push('');
if (result.availableServers.length > 0) {
lines.push(`Available MCP Servers (${result.availableServers.length}):`);
for (const server of result.availableServers.slice(0, 10)) {
lines.push(` - ${server}`);
}
if (result.availableServers.length > 10) {
lines.push(` ... and ${result.availableServers.length - 10} more`);
}
lines.push('');
}
if (result.missingServers.length > 0) {
lines.push(`Missing Servers:`);
for (const server of result.missingServers) {
lines.push(` - ${server}`);
}
lines.push('');
}
lines.push('Capabilities:');
const capabilityLabels: Record<keyof ModeCapabilities, string> = {
canAccessCRM: 'CRM Access',
canSendEmails: 'Email',
canAccessCalendar: 'Calendar',
canAccessDocs: 'Documents',
canQueryData: 'Data Queries',
canEnrichData: 'Data Enrichment',
canSendNotifications: 'Notifications',
canUseAI: 'AI Services',
hasChat: 'Chat',
hasStorage: 'Storage',
hasSearch: 'Search',
hasAnalytics: 'Analytics',
};
for (const [key, label] of Object.entries(capabilityLabels)) {
const enabled = result.capabilities[key as keyof ModeCapabilities];
lines.push(` ${enabled ? '✓' : '✗'} ${label}`);
}
if (result.connectorMappings.length > 0) {
lines.push('');
lines.push('Suggested Connector Mappings:');
for (const mapping of result.connectorMappings.slice(0, 5)) {
lines.push(` ${mapping.placeholder} → ${mapping.tool}`);
}
}
return lines.join('\n');
}
export function requireEnhancedMode(result: ModeDetectionResult): void {
if (result.mode !== 'enhanced') {
throw new Error(
`This skill requires enhanced mode with MCP servers. Missing: ${result.missingServers.join(', ')}`
);
}
}
export function requireCapability(
result: ModeDetectionResult,
capability: keyof ModeCapabilities
): void {
if (!result.capabilities[capability]) {
throw new Error(`This skill requires the ${capability} capability which is not available.`);
}
}
export function getStandaloneAlternative(capability: keyof ModeCapabilities): string {
const alternatives: Record<keyof ModeCapabilities, string> = {
canAccessCRM: 'Use a local JSON file to store contact information',
canSendEmails: 'Output email content to the terminal for manual sending',
canAccessCalendar: 'Use a local iCal file for scheduling',
canAccessDocs: 'Use local markdown files for documentation',
canQueryData: 'Use a local SQLite database or JSON files',
canEnrichData: 'Skip enrichment or use cached data',
canSendNotifications: 'Output notifications to the terminal',
canUseAI: 'Use simpler rule-based logic or skip AI features',
hasChat: 'Output messages to the terminal',
hasStorage: 'Use the local filesystem',
hasSearch: 'Use grep or local file search',
hasAnalytics: 'Skip analytics or use local logging',
};
return alternatives[capability];
}
export function createModeAwareExecutor<T>(
enhancedFn: () => Promise<T>,
standaloneFn: () => Promise<T>,
modeResult: ModeDetectionResult
): () => Promise<T> {
return async () => {
if (modeResult.mode === 'enhanced') {
return enhancedFn();
}
return standaloneFn();
};
}
+106
View File
@@ -0,0 +1,106 @@
import { z } from 'zod';
export const ExecutionStepStatusSchema = z.enum([
'pending',
'running',
'completed',
'failed',
'skipped',
]);
export type ExecutionStepStatus = z.infer<typeof ExecutionStepStatusSchema>;
export const ExecutionStepSchema = z.object({
id: z.string(),
name: z.string(),
description: z.string().optional(),
status: ExecutionStepStatusSchema.default('pending'),
startedAt: z.string().datetime().optional(),
completedAt: z.string().datetime().optional(),
duration: z.number().optional(),
input: z.record(z.unknown()).optional(),
output: z.record(z.unknown()).optional(),
error: z.string().optional(),
retryCount: z.number().default(0),
metadata: z.record(z.unknown()).optional(),
});
export type ExecutionStep = z.infer<typeof ExecutionStepSchema>;
export const ExecutionFlowSchema = z.object({
id: z.string(),
skillName: z.string(),
version: z.number().default(1),
steps: z.array(ExecutionStepSchema),
currentStepIndex: z.number().default(-1),
status: ExecutionStepStatusSchema.default('pending'),
startedAt: z.string().datetime().optional(),
completedAt: z.string().datetime().optional(),
totalDuration: z.number().optional(),
context: z.record(z.unknown()).optional(),
mode: z.enum(['standalone', 'enhanced']).default('standalone'),
mcpServers: z.array(z.string()).optional(),
});
export type ExecutionFlow = z.infer<typeof ExecutionFlowSchema>;
export interface ExecutionFlowConfig {
maxRetries?: number;
retryDelay?: number;
timeout?: number;
onStepStart?: (step: ExecutionStep, flow: ExecutionFlow) => void;
onStepComplete?: (step: ExecutionStep, flow: ExecutionFlow) => void;
onStepError?: (step: ExecutionStep, error: Error, flow: ExecutionFlow) => void;
onFlowComplete?: (flow: ExecutionFlow) => void;
}
export interface StepDefinition {
name: string;
description?: string;
execute: (
input: Record<string, unknown>,
context: ExecutionContext
) => Promise<Record<string, unknown>>;
rollback?: (context: ExecutionContext) => Promise<void>;
condition?: (context: ExecutionContext) => boolean;
retryable?: boolean;
timeout?: number;
}
export interface ExecutionContext {
flow: ExecutionFlow;
stepIndex: number;
previousOutput?: Record<string, unknown>;
mcpTools?: string[];
isEnhanced: boolean;
}
export interface FlowSummary {
id: string;
skillName: string;
status: ExecutionStepStatus;
progress: number;
currentStep?: string;
startedAt?: string;
completedAt?: string;
totalDuration?: number;
stepsCompleted: number;
totalSteps: number;
mode: 'standalone' | 'enhanced';
}
export interface FlowMetrics {
totalFlows: number;
completedFlows: number;
failedFlows: number;
averageDuration: number;
stepMetrics: Map<
string,
{
executionCount: number;
successCount: number;
failureCount: number;
averageDuration: number;
}
>;
}
+12
View File
@@ -89,3 +89,15 @@ export * from './profiles/index.js';
// Coding Guidelines System
export * from './guidelines/index.js';
// Skill Tree (Hierarchical Taxonomy - Phase 21)
export * from './tree/index.js';
// Reasoning Engine (LLM-based Tree Search - Phase 21)
export * from './reasoning/index.js';
// Connectors (Tool-Agnostic Placeholders - Phase 21)
export * from './connectors/index.js';
// Execution Flow (Step Tracking & Metrics - Phase 21)
export * from './execution/index.js';
@@ -0,0 +1,194 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { WellKnownProvider, generateWellKnownIndex, generateWellKnownStructure, calculateBaseSkillsUrl } from '../wellknown.js';
import { existsSync, rmSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { randomUUID } from 'node:crypto';
describe('WellKnownProvider', () => {
const provider = new WellKnownProvider();
describe('matches', () => {
it('should match https URLs not on github/gitlab/bitbucket', () => {
expect(provider.matches('https://example.com')).toBe(true);
expect(provider.matches('https://skills.vercel.app')).toBe(true);
expect(provider.matches('https://my-skills.com/api')).toBe(true);
});
it('should not match github.com URLs', () => {
expect(provider.matches('https://github.com/owner/repo')).toBe(false);
});
it('should not match gitlab.com URLs', () => {
expect(provider.matches('https://gitlab.com/owner/repo')).toBe(false);
});
it('should not match bitbucket.org URLs', () => {
expect(provider.matches('https://bitbucket.org/owner/repo')).toBe(false);
});
it('should not match local paths', () => {
expect(provider.matches('./my-skills')).toBe(false);
expect(provider.matches('/absolute/path')).toBe(false);
expect(provider.matches('~/home/skills')).toBe(false);
});
it('should not match shorthand GitHub format', () => {
expect(provider.matches('owner/repo')).toBe(false);
});
});
describe('parseSource', () => {
it('should parse URL hostname and path', () => {
const result = provider.parseSource('https://example.com/api');
expect(result).toEqual({ owner: 'example.com', repo: 'api' });
});
it('should handle root URLs', () => {
const result = provider.parseSource('https://skills.example.com');
expect(result).toEqual({ owner: 'skills.example.com', repo: 'skills' });
});
it('should return null for invalid URLs', () => {
const result = provider.parseSource('not-a-url');
expect(result).toBeNull();
});
});
describe('type and name', () => {
it('should have correct type', () => {
expect(provider.type).toBe('wellknown');
});
it('should have correct name', () => {
expect(provider.name).toBe('Well-Known');
});
});
});
describe('calculateBaseSkillsUrl', () => {
it('should handle index.json URL correctly', () => {
const result = calculateBaseSkillsUrl('https://example.com/.well-known/skills/index.json');
expect(result).toBe('https://example.com/.well-known/skills');
});
it('should handle skills.json URL correctly without duplicating .well-known', () => {
const result = calculateBaseSkillsUrl('https://example.com/.well-known/skills.json');
expect(result).toBe('https://example.com/.well-known/skills');
});
it('should handle nested paths with index.json', () => {
const result = calculateBaseSkillsUrl('https://cdn.example.com/v1/.well-known/skills/index.json');
expect(result).toBe('https://cdn.example.com/v1/.well-known/skills');
});
it('should handle nested paths with skills.json', () => {
const result = calculateBaseSkillsUrl('https://cdn.example.com/v1/.well-known/skills.json');
expect(result).toBe('https://cdn.example.com/v1/.well-known/skills');
});
});
describe('generateWellKnownIndex', () => {
it('should generate valid index structure', () => {
const skills = [
{ name: 'test-skill', description: 'A test skill', files: ['SKILL.md', 'README.md'] },
{ name: 'another-skill', description: 'Another skill', files: ['SKILL.md'] },
];
const index = generateWellKnownIndex(skills);
expect(index.version).toBe('1.0');
expect(index.skills).toHaveLength(2);
expect(index.skills[0]).toEqual({
name: 'test-skill',
description: 'A test skill',
files: ['SKILL.md', 'README.md'],
});
expect(index.skills[1]).toEqual({
name: 'another-skill',
description: 'Another skill',
files: ['SKILL.md'],
});
});
it('should handle empty skills array', () => {
const index = generateWellKnownIndex([]);
expect(index.version).toBe('1.0');
expect(index.skills).toEqual([]);
});
});
describe('generateWellKnownStructure', () => {
let tempDir: string;
beforeEach(() => {
tempDir = join(tmpdir(), `skillkit-test-${randomUUID()}`);
});
afterEach(() => {
if (existsSync(tempDir)) {
rmSync(tempDir, { recursive: true, force: true });
}
});
it('should create well-known directory structure', () => {
const skills = [
{
name: 'test-skill',
description: 'A test skill',
content: '---\nname: test-skill\ndescription: A test skill\n---\n\n# Test Skill\n\nContent here.',
},
];
const result = generateWellKnownStructure(tempDir, skills);
expect(existsSync(join(tempDir, '.well-known', 'skills'))).toBe(true);
expect(existsSync(result.indexPath)).toBe(true);
expect(result.skillPaths).toContain(join(tempDir, '.well-known', 'skills', 'test-skill', 'SKILL.md'));
const index = JSON.parse(readFileSync(result.indexPath, 'utf-8'));
expect(index.skills[0].name).toBe('test-skill');
expect(index.skills[0].files).toContain('SKILL.md');
});
it('should include additional files', () => {
const skills = [
{
name: 'test-skill',
description: 'Test',
content: '# Test',
additionalFiles: {
'README.md': '# README',
'config.json': '{"key": "value"}',
},
},
];
const result = generateWellKnownStructure(tempDir, skills);
expect(result.skillPaths).toContain(join(tempDir, '.well-known', 'skills', 'test-skill', 'README.md'));
expect(result.skillPaths).toContain(join(tempDir, '.well-known', 'skills', 'test-skill', 'config.json'));
const readme = readFileSync(join(tempDir, '.well-known', 'skills', 'test-skill', 'README.md'), 'utf-8');
expect(readme).toBe('# README');
const index = JSON.parse(readFileSync(result.indexPath, 'utf-8'));
expect(index.skills[0].files).toContain('README.md');
expect(index.skills[0].files).toContain('config.json');
});
it('should handle multiple skills', () => {
const skills = [
{ name: 'skill-one', description: 'First', content: '# Skill One' },
{ name: 'skill-two', description: 'Second', content: '# Skill Two' },
];
const result = generateWellKnownStructure(tempDir, skills);
expect(existsSync(join(tempDir, '.well-known', 'skills', 'skill-one', 'SKILL.md'))).toBe(true);
expect(existsSync(join(tempDir, '.well-known', 'skills', 'skill-two', 'SKILL.md'))).toBe(true);
const index = JSON.parse(readFileSync(result.indexPath, 'utf-8'));
expect(index.skills).toHaveLength(2);
});
});
+3
View File
@@ -4,17 +4,20 @@ import { GitHubProvider } from './github.js';
import { GitLabProvider } from './gitlab.js';
import { BitbucketProvider } from './bitbucket.js';
import { LocalProvider } from './local.js';
import { WellKnownProvider } from './wellknown.js';
export * from './base.js';
export * from './github.js';
export * from './gitlab.js';
export * from './bitbucket.js';
export * from './local.js';
export * from './wellknown.js';
const providers: GitProviderAdapter[] = [
new LocalProvider(),
new GitLabProvider(),
new BitbucketProvider(),
new WellKnownProvider(),
new GitHubProvider(),
];
+248
View File
@@ -0,0 +1,248 @@
import { existsSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
import { join, basename, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
import { randomUUID } from 'node:crypto';
import type { GitProviderAdapter, CloneOptions } from './base.js';
import { isGitUrl, isLocalPath } from './base.js';
import type { GitProvider, CloneResult } from '../types.js';
function sanitizeSkillName(name: string): string | null {
if (!name || typeof name !== 'string') return null;
const base = basename(name);
if (base !== name || name.includes('..') || name.includes('/') || name.includes('\\')) {
return null;
}
if (!/^[a-zA-Z0-9._-]+$/.test(name)) {
return null;
}
return name;
}
export interface WellKnownSkill {
name: string;
description?: string;
files: string[];
}
export interface WellKnownIndex {
version?: string;
skills: WellKnownSkill[];
}
export class WellKnownProvider implements GitProviderAdapter {
readonly type: GitProvider = 'wellknown';
readonly name = 'Well-Known';
readonly baseUrl = '';
parseSource(source: string): { owner: string; repo: string; subpath?: string } | null {
try {
const url = new URL(source);
return { owner: url.hostname, repo: url.pathname.replace(/^\//, '') || 'skills' };
} catch {
return null;
}
}
matches(source: string): boolean {
if (isLocalPath(source)) return false;
if (!isGitUrl(source)) return false;
if (source.includes('github.com')) return false;
if (source.includes('gitlab.com')) return false;
if (source.includes('bitbucket.org')) return false;
try {
new URL(source);
return true;
} catch {
return false;
}
}
getCloneUrl(_owner: string, _repo: string): string {
return '';
}
getSshUrl(_owner: string, _repo: string): string {
return '';
}
async clone(source: string, _targetDir: string, _options: CloneOptions = {}): Promise<CloneResult> {
const tempDir = join(tmpdir(), `skillkit-wellknown-${randomUUID()}`);
try {
mkdirSync(tempDir, { recursive: true });
const baseUrl = source.replace(/\/$/, '');
const indexUrls = [
`${baseUrl}/.well-known/skills/index.json`,
`${baseUrl}/.well-known/skills.json`,
];
let index: WellKnownIndex | null = null;
let foundUrl = '';
for (const url of indexUrls) {
try {
const response = await fetch(url);
if (response.ok) {
index = await response.json() as WellKnownIndex;
foundUrl = url;
break;
}
} catch {
continue;
}
}
if (!index || !index.skills || index.skills.length === 0) {
return {
success: false,
error: `No skills found at ${baseUrl}/.well-known/skills/index.json`,
};
}
const skills: string[] = [];
const discoveredSkills: Array<{ name: string; dirName: string; path: string }> = [];
const baseSkillsUrl = calculateBaseSkillsUrl(foundUrl);
for (const skill of index.skills) {
const safeName = sanitizeSkillName(skill.name);
if (!safeName) {
continue;
}
const skillDir = join(tempDir, safeName);
const resolvedSkillDir = resolve(skillDir);
const resolvedTempDir = resolve(tempDir);
if (!resolvedSkillDir.startsWith(resolvedTempDir + sep) && resolvedSkillDir !== resolvedTempDir) {
continue;
}
mkdirSync(skillDir, { recursive: true });
let hasSkillMd = false;
for (const file of skill.files) {
const fileUrl = `${baseSkillsUrl}/${encodeURIComponent(skill.name)}/${encodeURIComponent(file)}`;
try {
const response = await fetch(fileUrl);
if (response.ok) {
const content = await response.text();
const safeFileName = basename(file);
writeFileSync(join(skillDir, safeFileName), content);
if (file === 'SKILL.md' || file.endsWith('/SKILL.md')) {
hasSkillMd = true;
}
}
} catch {
continue;
}
}
if (hasSkillMd) {
skills.push(safeName);
discoveredSkills.push({
name: safeName,
dirName: safeName,
path: skillDir,
});
}
}
if (skills.length === 0) {
rmSync(tempDir, { recursive: true, force: true });
return {
success: false,
error: 'No valid skills found (skills must contain SKILL.md)',
};
}
return {
success: true,
path: tempDir,
tempRoot: tempDir,
skills,
discoveredSkills,
};
} catch (error) {
if (existsSync(tempDir)) {
rmSync(tempDir, { recursive: true, force: true });
}
const message = error instanceof Error ? error.message : String(error);
return { success: false, error: `Failed to fetch skills: ${message}` };
}
}
}
export function calculateBaseSkillsUrl(foundUrl: string): string {
return foundUrl.endsWith('/index.json')
? foundUrl.replace('/index.json', '')
: foundUrl.replace('/skills.json', '/skills');
}
export function generateWellKnownIndex(skills: Array<{ name: string; description?: string; files: string[] }>): WellKnownIndex {
return {
version: '1.0',
skills: skills.map(s => ({
name: s.name,
description: s.description,
files: s.files,
})),
};
}
export function generateWellKnownStructure(
outputDir: string,
skills: Array<{ name: string; description?: string; content: string; additionalFiles?: Record<string, string> }>
): { indexPath: string; skillPaths: string[] } {
const wellKnownDir = join(outputDir, '.well-known', 'skills');
const resolvedWellKnownDir = resolve(wellKnownDir);
mkdirSync(wellKnownDir, { recursive: true });
const indexSkills: WellKnownSkill[] = [];
const skillPaths: string[] = [];
for (const skill of skills) {
const safeName = sanitizeSkillName(skill.name);
if (!safeName) {
continue;
}
const skillDir = join(wellKnownDir, safeName);
const resolvedSkillDir = resolve(skillDir);
if (!resolvedSkillDir.startsWith(resolvedWellKnownDir + sep) && resolvedSkillDir !== resolvedWellKnownDir) {
continue;
}
mkdirSync(skillDir, { recursive: true });
writeFileSync(join(skillDir, 'SKILL.md'), skill.content);
skillPaths.push(join(skillDir, 'SKILL.md'));
const files = ['SKILL.md'];
if (skill.additionalFiles) {
for (const [filename, content] of Object.entries(skill.additionalFiles)) {
writeFileSync(join(skillDir, filename), content);
files.push(filename);
skillPaths.push(join(skillDir, filename));
}
}
indexSkills.push({
name: skill.name,
description: skill.description,
files,
});
}
const index = generateWellKnownIndex(indexSkills);
const indexPath = join(wellKnownDir, 'index.json');
writeFileSync(indexPath, JSON.stringify(index, null, 2));
return { indexPath, skillPaths };
}
+618
View File
@@ -0,0 +1,618 @@
import type { SkillSummary, ProjectProfile } from '../recommend/types.js';
import type { SkillTree, TreeNode } from '../tree/types.js';
import { TreeGenerator } from '../tree/generator.js';
import {
type ReasoningConfig,
type TreeSearchQuery,
type TreeSearchResult,
type TreeReasoningResult,
type ExplainedRecommendation,
type ExplainedMatch,
type SearchPlan,
type ReasoningCacheEntry,
type ReasoningEngineStats,
DEFAULT_REASONING_CONFIG,
} from './types.js';
import {
buildSearchPlanPrompt,
buildExplanationPrompt,
extractJsonFromResponse,
validateSearchPlan,
} from './prompts.js';
import { CATEGORY_TAXONOMY } from '../tree/types.js';
const CACHE_TTL_MS = 5 * 60 * 1000;
const MAX_CACHE_SIZE = 100;
export class ReasoningEngine {
private config: ReasoningConfig;
private skillMap: Map<string, SkillSummary> = new Map();
private tree: SkillTree | null = null;
private cache: Map<string, ReasoningCacheEntry> = new Map();
private stats: ReasoningEngineStats = {
totalQueries: 0,
cacheHits: 0,
cacheMisses: 0,
averageProcessingTimeMs: 0,
averageResultsPerQuery: 0,
};
constructor(config?: Partial<ReasoningConfig>) {
this.config = { ...DEFAULT_REASONING_CONFIG, ...config };
}
loadSkills(skills: SkillSummary[]): void {
this.skillMap.clear();
for (const skill of skills) {
this.skillMap.set(skill.name, skill);
}
}
loadTree(tree: SkillTree): void {
this.tree = tree;
}
generateTree(skills: SkillSummary[]): void {
const generator = new TreeGenerator();
this.tree = generator.generateTree(skills);
this.loadSkills(skills);
}
async search(query: TreeSearchQuery): Promise<TreeReasoningResult> {
const startTime = Date.now();
this.stats.totalQueries++;
const cacheKey = this.getCacheKey(query);
const cached = this.getFromCache(cacheKey);
if (cached) {
this.stats.cacheHits++;
return {
query: query.query,
results: cached.results,
exploredPaths: [],
reasoning: 'Retrieved from cache',
totalNodesVisited: 0,
processingTimeMs: Date.now() - startTime,
};
}
this.stats.cacheMisses++;
const maxResults = query.maxResults ?? 10;
const minConfidence = query.minConfidence ?? 30;
const plan = await this.createSearchPlan(query);
const results: TreeSearchResult[] = [];
const exploredPaths: string[][] = [];
let totalNodesVisited = 0;
if (this.tree) {
const traversalResult = await this.traverseTree(query, plan);
results.push(...traversalResult.results);
exploredPaths.push(...traversalResult.exploredPaths);
totalNodesVisited = traversalResult.nodesVisited;
} else {
const fallbackResults = this.fallbackSearch(query);
results.push(...fallbackResults);
}
const filteredResults = results
.filter((r) => r.confidence >= minConfidence)
.sort((a, b) => b.confidence - a.confidence)
.slice(0, maxResults);
const processingTimeMs = Date.now() - startTime;
this.updateStats(processingTimeMs, filteredResults.length);
this.addToCache(cacheKey, filteredResults);
return {
query: query.query,
results: filteredResults,
exploredPaths,
reasoning: this.buildReasoningSummary(plan, filteredResults),
totalNodesVisited,
processingTimeMs,
};
}
async explain(
skill: SkillSummary,
score: number,
profile: ProjectProfile
): Promise<ExplainedRecommendation> {
const treePath = this.getSkillPath(skill.name);
const explanation = await this.generateExplanation(skill, score, profile);
return {
skill,
score,
reasoning: explanation,
treePath,
};
}
async explainBatch(
skills: Array<{ skill: SkillSummary; score: number }>,
profile: ProjectProfile
): Promise<ExplainedRecommendation[]> {
const results: ExplainedRecommendation[] = [];
for (const { skill, score } of skills) {
const explained = await this.explain(skill, score, profile);
results.push(explained);
}
return results;
}
private async createSearchPlan(query: TreeSearchQuery): Promise<SearchPlan> {
const categories = CATEGORY_TAXONOMY.map((c) => c.category);
if (this.config.provider === 'mock') {
return this.mockSearchPlan(query.query, query.context);
}
const prompt = buildSearchPlanPrompt(
query.query,
categories,
query.context
);
const response = await this.callLLM(prompt);
try {
const data = extractJsonFromResponse(response);
return validateSearchPlan(data);
} catch {
return this.mockSearchPlan(query.query, query.context);
}
}
private mockSearchPlan(query: string, context?: ProjectProfile): SearchPlan {
const queryLower = query.toLowerCase();
const keywords = queryLower
.split(/\s+/)
.filter((w) => w.length > 2);
const categoryScores: { category: string; score: number }[] = [];
for (const mapping of CATEGORY_TAXONOMY) {
let score = 0;
for (const keyword of keywords) {
if (mapping.category.toLowerCase().includes(keyword)) {
score += 30;
}
for (const tag of mapping.tags) {
if (tag.includes(keyword) || keyword.includes(tag)) {
score += 20;
}
}
for (const kw of mapping.keywords) {
if (kw.includes(keyword) || keyword.includes(kw)) {
score += 15;
}
}
}
if (context) {
for (const framework of context.stack.frameworks) {
if (mapping.tags.includes(framework.name.toLowerCase())) {
score += 10;
}
}
for (const language of context.stack.languages) {
if (mapping.tags.includes(language.name.toLowerCase())) {
score += 5;
}
}
}
if (score > 0) {
categoryScores.push({ category: mapping.category, score });
}
}
categoryScores.sort((a, b) => b.score - a.score);
const primaryCategories = categoryScores
.slice(0, 3)
.map((c) => c.category);
const secondaryCategories = categoryScores
.slice(3, 6)
.map((c) => c.category);
const filters: SearchPlan['filters'] = {
tags: keywords.filter((k) =>
CATEGORY_TAXONOMY.some((m) => m.tags.includes(k))
),
frameworks: context?.stack.frameworks.map((f) => f.name) || [],
languages: context?.stack.languages.map((l) => l.name) || [],
};
return {
primaryCategories: primaryCategories.length > 0 ? primaryCategories : ['Development'],
secondaryCategories,
keywords,
filters,
strategy: keywords.length <= 2 ? 'breadth-first' : 'targeted',
};
}
private async traverseTree(
query: TreeSearchQuery,
plan: SearchPlan
): Promise<{
results: TreeSearchResult[];
exploredPaths: string[][];
nodesVisited: number;
}> {
if (!this.tree) {
return { results: [], exploredPaths: [], nodesVisited: 0 };
}
const results: TreeSearchResult[] = [];
const exploredPaths: string[][] = [];
let nodesVisited = 0;
const relevantNodes = this.findRelevantNodes(plan);
for (const { node, path } of relevantNodes) {
nodesVisited++;
exploredPaths.push(path);
for (const skillName of node.skills) {
const skill = this.skillMap.get(skillName);
if (!skill) continue;
const matchResult = this.evaluateSkillMatch(query.query, skill, query.context);
if (matchResult.confidence >= (query.minConfidence ?? 30)) {
results.push({
skill,
path,
reasoning: matchResult.reasoning,
confidence: matchResult.confidence,
relevantSections: matchResult.relevantSections,
matchedKeywords: matchResult.matchedKeywords,
});
}
}
}
return { results, exploredPaths, nodesVisited };
}
private findRelevantNodes(
plan: SearchPlan
): Array<{ node: TreeNode; path: string[] }> {
if (!this.tree) return [];
const relevant: Array<{ node: TreeNode; path: string[]; priority: number }> = [];
const traverse = (node: TreeNode, path: string[], priorityBoost: number) => {
const nodeName = node.name.toLowerCase();
let priority = priorityBoost;
if (plan.primaryCategories.some((c) => c.toLowerCase() === nodeName)) {
priority += 100;
}
if (plan.secondaryCategories.some((c) => c.toLowerCase() === nodeName)) {
priority += 50;
}
for (const keyword of plan.keywords) {
if (nodeName.includes(keyword) || keyword.includes(nodeName)) {
priority += 25;
}
}
if (priority > 0 || node.depth === 0) {
relevant.push({ node, path: [...path, node.name], priority });
}
for (const child of node.children) {
traverse(child, [...path, node.name], priority > 0 ? priority * 0.5 : 0);
}
};
traverse(this.tree.rootNode, [], 0);
relevant.sort((a, b) => b.priority - a.priority);
return relevant.slice(0, 20).map(({ node, path }) => ({ node, path }));
}
private evaluateSkillMatch(
query: string,
skill: SkillSummary,
context?: ProjectProfile
): {
confidence: number;
reasoning: string;
relevantSections: string[];
matchedKeywords: string[];
} {
const queryTerms = query.toLowerCase().split(/\s+/);
const matchedKeywords: string[] = [];
let confidence = 0;
const nameLower = skill.name.toLowerCase();
for (const term of queryTerms) {
if (nameLower.includes(term)) {
confidence += 30;
matchedKeywords.push(term);
}
}
const descLower = (skill.description || '').toLowerCase();
for (const term of queryTerms) {
if (descLower.includes(term) && !matchedKeywords.includes(term)) {
confidence += 20;
matchedKeywords.push(term);
}
}
const tagsLower = (skill.tags || []).map((t) => t.toLowerCase());
for (const term of queryTerms) {
if (tagsLower.some((t) => t.includes(term) || term.includes(t))) {
if (!matchedKeywords.includes(term)) {
confidence += 25;
matchedKeywords.push(term);
}
}
}
if (context) {
for (const framework of context.stack.frameworks) {
const fwLower = framework.name.toLowerCase();
if (tagsLower.includes(fwLower) || nameLower.includes(fwLower)) {
confidence += 15;
}
}
for (const language of context.stack.languages) {
const langLower = language.name.toLowerCase();
if (tagsLower.includes(langLower) || nameLower.includes(langLower)) {
confidence += 10;
}
}
}
confidence = Math.min(100, confidence);
const relevantSections: string[] = [];
if (matchedKeywords.length > 0) {
relevantSections.push('description', 'tags');
}
const reasoning = matchedKeywords.length > 0
? `Matches keywords: ${matchedKeywords.join(', ')}`
: 'No direct keyword match';
return {
confidence,
reasoning,
relevantSections,
matchedKeywords,
};
}
private fallbackSearch(query: TreeSearchQuery): TreeSearchResult[] {
const results: TreeSearchResult[] = [];
for (const skill of this.skillMap.values()) {
const matchResult = this.evaluateSkillMatch(
query.query,
skill,
query.context
);
if (matchResult.confidence >= (query.minConfidence ?? 30)) {
results.push({
skill,
path: ['Uncategorized'],
reasoning: matchResult.reasoning,
confidence: matchResult.confidence,
relevantSections: matchResult.relevantSections,
matchedKeywords: matchResult.matchedKeywords,
});
}
}
return results;
}
private async generateExplanation(
skill: SkillSummary,
score: number,
profile: ProjectProfile
): Promise<ExplainedMatch> {
if (this.config.provider === 'mock') {
return this.mockExplanation(skill, score, profile);
}
const prompt = buildExplanationPrompt(skill, score, profile);
try {
const response = await this.callLLM(prompt);
const data = extractJsonFromResponse(response) as Partial<ExplainedMatch>;
return {
matchedBecause: data.matchedBecause || [],
relevantFor: data.relevantFor || [],
differentFrom: data.differentFrom || [],
confidence: data.confidence || this.scoreToConfidence(score),
};
} catch {
return this.mockExplanation(skill, score, profile);
}
}
private mockExplanation(
skill: SkillSummary,
score: number,
profile: ProjectProfile
): ExplainedMatch {
const matchedBecause: string[] = [];
const relevantFor: string[] = [];
const differentFrom: string[] = [];
const skillTags = skill.tags || [];
for (const framework of profile.stack.frameworks) {
const fwLower = framework.name.toLowerCase();
if (
skillTags.some((t) => t.toLowerCase().includes(fwLower)) ||
skill.name.toLowerCase().includes(fwLower)
) {
matchedBecause.push(`Uses ${framework.name}`);
}
}
for (const language of profile.stack.languages) {
const langLower = language.name.toLowerCase();
if (skillTags.some((t) => t.toLowerCase().includes(langLower))) {
matchedBecause.push(`Supports ${language.name}`);
}
}
if (matchedBecause.length === 0) {
matchedBecause.push(`Related tags: ${skillTags.slice(0, 3).join(', ')}`);
}
relevantFor.push(`Your ${profile.type || 'project'} project`);
if (profile.name) {
relevantFor.push(`Specifically for ${profile.name}`);
}
differentFrom.push('General-purpose alternatives');
return {
matchedBecause,
relevantFor,
differentFrom,
confidence: this.scoreToConfidence(score),
};
}
private scoreToConfidence(score: number): 'high' | 'medium' | 'low' {
if (score >= 70) return 'high';
if (score >= 50) return 'medium';
return 'low';
}
private getSkillPath(skillName: string): string[] {
if (!this.tree) return ['Uncategorized'];
const generator = new TreeGenerator();
const path = generator.getPath(this.tree, skillName);
return path || ['Uncategorized'];
}
private buildReasoningSummary(
plan: SearchPlan,
results: TreeSearchResult[]
): string {
const parts: string[] = [];
parts.push(`Search strategy: ${plan.strategy}`);
parts.push(`Primary categories: ${plan.primaryCategories.join(', ')}`);
if (plan.keywords.length > 0) {
parts.push(`Keywords extracted: ${plan.keywords.join(', ')}`);
}
parts.push(`Found ${results.length} matching skills`);
if (results.length > 0) {
const avgConfidence = results.reduce((sum, r) => sum + r.confidence, 0) / results.length;
parts.push(`Average confidence: ${Math.round(avgConfidence)}%`);
}
return parts.join('. ');
}
private async callLLM(prompt: string): Promise<string> {
return `Mock response for: ${prompt.slice(0, 50)}...`;
}
private getCacheKey(query: TreeSearchQuery): string {
return JSON.stringify({
query: query.query,
contextName: query.context?.name,
maxResults: query.maxResults,
minConfidence: query.minConfidence,
});
}
private getFromCache(key: string): ReasoningCacheEntry | null {
const entry = this.cache.get(key);
if (!entry) return null;
const now = Date.now();
if (now - entry.timestamp > entry.ttl) {
this.cache.delete(key);
return null;
}
return entry;
}
private addToCache(key: string, results: TreeSearchResult[]): void {
if (this.cache.size >= MAX_CACHE_SIZE) {
const oldestKey = this.cache.keys().next().value;
if (oldestKey) {
this.cache.delete(oldestKey);
}
}
this.cache.set(key, {
query: key,
results,
timestamp: Date.now(),
ttl: CACHE_TTL_MS,
});
}
private updateStats(processingTimeMs: number, resultCount: number): void {
const cacheMisses = this.stats.cacheMisses;
if (cacheMisses === 1) {
this.stats.averageProcessingTimeMs = processingTimeMs;
this.stats.averageResultsPerQuery = resultCount;
} else {
this.stats.averageProcessingTimeMs =
(this.stats.averageProcessingTimeMs * (cacheMisses - 1) + processingTimeMs) / cacheMisses;
this.stats.averageResultsPerQuery =
(this.stats.averageResultsPerQuery * (cacheMisses - 1) + resultCount) / cacheMisses;
}
}
getStats(): ReasoningEngineStats {
return { ...this.stats };
}
clearCache(): void {
this.cache.clear();
}
getTree(): SkillTree | null {
return this.tree;
}
}
export function createReasoningEngine(
config?: Partial<ReasoningConfig>
): ReasoningEngine {
return new ReasoningEngine(config);
}
+14
View File
@@ -0,0 +1,14 @@
export * from './types.js';
export * from './engine.js';
export * from './prompts.js';
export { ReasoningEngine, createReasoningEngine } from './engine.js';
export {
buildSearchPlanPrompt,
buildCategoryRelevancePrompt,
buildSkillMatchPrompt,
buildExplanationPrompt,
extractJsonFromResponse,
validateSearchPlan,
validateCategoryScore,
} from './prompts.js';
+227
View File
@@ -0,0 +1,227 @@
import type { TreeNode } from '../tree/types.js';
import type { ProjectProfile } from '../recommend/types.js';
import type { SearchPlan, CategoryScore } from './types.js';
export const SEARCH_PLANNING_PROMPT = `You are a skill discovery assistant. Given a user query and optional project context, create a search plan.
User Query: {{query}}
{{#if context}}
Project Context:
- Languages: {{context.languages}}
- Frameworks: {{context.frameworks}}
- Project Type: {{context.type}}
{{/if}}
Available Categories:
{{categories}}
Respond with a JSON search plan:
{
"primaryCategories": ["most relevant categories"],
"secondaryCategories": ["somewhat relevant categories"],
"keywords": ["extracted search terms"],
"filters": {
"tags": ["relevant tags"],
"frameworks": ["relevant frameworks"],
"languages": ["relevant languages"]
},
"strategy": "breadth-first" | "depth-first" | "targeted"
}`;
export const CATEGORY_RELEVANCE_PROMPT = `Rate the relevance of this category for the user's query.
Query: {{query}}
Category: {{category.name}}
Skills in category: {{category.skillCount}}
Subcategories: {{category.subcategories}}
Rate from 0-100 and explain briefly.
Respond as JSON: {"score": number, "reasoning": "brief explanation"}`;
export const SKILL_MATCH_PROMPT = `Evaluate how well this skill matches the user's query.
Query: {{query}}
Skill: {{skill.name}}
Description: {{skill.description}}
Tags: {{skill.tags}}
{{#if context}}
Project Stack:
- Languages: {{context.languages}}
- Frameworks: {{context.frameworks}}
{{/if}}
Evaluate match quality and explain why.
Respond as JSON:
{
"confidence": 0-100,
"matchedKeywords": ["words from query that match"],
"relevantSections": ["which parts of skill are relevant"],
"reasoning": "explanation of match quality"
}`;
export const EXPLANATION_PROMPT = `Explain why this skill was recommended for the user's project.
Skill: {{skill.name}}
Description: {{skill.description}}
Tags: {{skill.tags}}
Score: {{score}}
Project:
- Name: {{project.name}}
- Type: {{project.type}}
- Languages: {{project.languages}}
- Frameworks: {{project.frameworks}}
Explain the match clearly and concisely.
Respond as JSON:
{
"matchedBecause": ["specific match reasons"],
"relevantFor": ["how it helps this project"],
"differentFrom": ["what distinguishes it from alternatives"],
"confidence": "high" | "medium" | "low"
}`;
export function buildSearchPlanPrompt(
query: string,
categories: string[],
context?: ProjectProfile
): string {
let prompt = SEARCH_PLANNING_PROMPT
.replace('{{query}}', query)
.replace('{{categories}}', categories.join('\n'));
if (context) {
const languages = context.stack.languages.map(l => l.name).join(', ');
const frameworks = context.stack.frameworks.map(f => f.name).join(', ');
prompt = prompt
.replace('{{#if context}}', '')
.replace('{{/if}}', '')
.replace('{{context.languages}}', languages)
.replace('{{context.frameworks}}', frameworks)
.replace('{{context.type}}', context.type || 'unknown');
} else {
prompt = prompt.replace(/\{\{#if context\}\}[\s\S]*?\{\{\/if\}\}/g, '');
}
return prompt;
}
export function buildCategoryRelevancePrompt(
query: string,
node: TreeNode
): string {
const subcategories = node.children.map(c => c.name).join(', ');
return CATEGORY_RELEVANCE_PROMPT
.replace('{{query}}', query)
.replace('{{category.name}}', node.name)
.replace('{{category.skillCount}}', String(node.skillCount))
.replace('{{category.subcategories}}', subcategories || 'none');
}
export function buildSkillMatchPrompt(
query: string,
skill: { name: string; description?: string; tags?: string[] },
context?: ProjectProfile
): string {
let prompt = SKILL_MATCH_PROMPT
.replace('{{query}}', query)
.replace('{{skill.name}}', skill.name)
.replace('{{skill.description}}', skill.description || 'No description')
.replace('{{skill.tags}}', skill.tags?.join(', ') || 'No tags');
if (context) {
const languages = context.stack.languages.map(l => l.name).join(', ');
const frameworks = context.stack.frameworks.map(f => f.name).join(', ');
prompt = prompt
.replace('{{#if context}}', '')
.replace('{{/if}}', '')
.replace('{{context.languages}}', languages)
.replace('{{context.frameworks}}', frameworks);
} else {
prompt = prompt.replace(/\{\{#if context\}\}[\s\S]*?\{\{\/if\}\}/g, '');
}
return prompt;
}
export function buildExplanationPrompt(
skill: { name: string; description?: string; tags?: string[] },
score: number,
project: ProjectProfile
): string {
const languages = project.stack.languages.map(l => l.name).join(', ');
const frameworks = project.stack.frameworks.map(f => f.name).join(', ');
return EXPLANATION_PROMPT
.replace('{{skill.name}}', skill.name)
.replace('{{skill.description}}', skill.description || 'No description')
.replace('{{skill.tags}}', skill.tags?.join(', ') || 'No tags')
.replace('{{score}}', String(score))
.replace('{{project.name}}', project.name)
.replace('{{project.type}}', project.type || 'unknown')
.replace('{{project.languages}}', languages)
.replace('{{project.frameworks}}', frameworks);
}
export function extractJsonFromResponse(response: string): unknown {
const jsonMatch = response.match(/\{[\s\S]*\}/);
if (!jsonMatch) {
throw new Error('No JSON found in response');
}
try {
return JSON.parse(jsonMatch[0]);
} catch {
throw new Error('Invalid JSON in response');
}
}
export function validateSearchPlan(data: unknown): SearchPlan {
const plan = data as Record<string, unknown>;
return {
primaryCategories: Array.isArray(plan.primaryCategories)
? plan.primaryCategories
: [],
secondaryCategories: Array.isArray(plan.secondaryCategories)
? plan.secondaryCategories
: [],
keywords: Array.isArray(plan.keywords) ? plan.keywords : [],
filters: {
tags: Array.isArray((plan.filters as Record<string, unknown>)?.tags)
? (plan.filters as Record<string, unknown>).tags as string[]
: [],
frameworks: Array.isArray((plan.filters as Record<string, unknown>)?.frameworks)
? (plan.filters as Record<string, unknown>).frameworks as string[]
: [],
languages: Array.isArray((plan.filters as Record<string, unknown>)?.languages)
? (plan.filters as Record<string, unknown>).languages as string[]
: [],
},
strategy: ['breadth-first', 'depth-first', 'targeted'].includes(
plan.strategy as string
)
? (plan.strategy as 'breadth-first' | 'depth-first' | 'targeted')
: 'breadth-first',
};
}
export function validateCategoryScore(
data: unknown,
fallbackCategory = ''
): CategoryScore {
const score = data as Record<string, unknown>;
return {
category: typeof score.category === 'string' ? score.category : fallbackCategory,
score: typeof score.score === 'number' ? Math.min(100, Math.max(0, score.score)) : 0,
reasoning: typeof score.reasoning === 'string' ? score.reasoning : '',
};
}
+115
View File
@@ -0,0 +1,115 @@
import { z } from 'zod';
import type { SkillSummary, ProjectProfile } from '../recommend/types.js';
import type { TreeNode } from '../tree/types.js';
export const ReasoningProviderSchema = z.enum(['openai', 'anthropic', 'ollama', 'mock']);
export type ReasoningProvider = z.infer<typeof ReasoningProviderSchema>;
export interface ReasoningConfig {
provider: ReasoningProvider;
apiKey?: string;
model?: string;
maxTokens?: number;
temperature?: number;
baseUrl?: string;
}
export interface TreeSearchQuery {
query: string;
context?: ProjectProfile;
maxResults?: number;
minConfidence?: number;
searchDepth?: number;
}
export interface TreeTraversalStep {
node: TreeNode;
reasoning: string;
confidence: number;
action: 'explore' | 'skip' | 'select';
selectedSkills: string[];
}
export interface TreeSearchResult {
skill: SkillSummary;
path: string[];
reasoning: string;
confidence: number;
relevantSections: string[];
matchedKeywords: string[];
}
export interface TreeReasoningResult {
query: string;
results: TreeSearchResult[];
exploredPaths: string[][];
reasoning: string;
totalNodesVisited: number;
processingTimeMs: number;
}
export interface ExplainedMatch {
matchedBecause: string[];
relevantFor: string[];
differentFrom: string[];
confidence: 'high' | 'medium' | 'low';
}
export interface ExplainedRecommendation {
skill: SkillSummary;
score: number;
reasoning: ExplainedMatch;
treePath: string[];
}
export interface ReasoningPrompt {
name: string;
template: string;
variables: string[];
}
export interface LLMResponse {
content: string;
tokensUsed: number;
model: string;
}
export interface ReasoningCacheEntry {
query: string;
results: TreeSearchResult[];
timestamp: number;
ttl: number;
}
export const DEFAULT_REASONING_CONFIG: ReasoningConfig = {
provider: 'mock',
model: 'gpt-4o-mini',
maxTokens: 1000,
temperature: 0.3,
};
export interface CategoryScore {
category: string;
score: number;
reasoning: string;
}
export interface SearchPlan {
primaryCategories: string[];
secondaryCategories: string[];
keywords: string[];
filters: {
tags?: string[];
frameworks?: string[];
languages?: string[];
};
strategy: 'breadth-first' | 'depth-first' | 'targeted';
}
export interface ReasoningEngineStats {
totalQueries: number;
cacheHits: number;
cacheMisses: number;
averageProcessingTimeMs: number;
averageResultsPerQuery: number;
}
+142
View File
@@ -665,3 +665,145 @@ export function createRecommendationEngine(
): RecommendationEngine {
return new RecommendationEngine(weights);
}
/**
* Enhanced Recommendation Engine with reasoning support
*/
export class ReasoningRecommendationEngine extends RecommendationEngine {
private reasoningEngine: import('../reasoning/engine.js').ReasoningEngine | null = null;
private reasoningConfig?: import('../reasoning/types.js').ReasoningConfig;
constructor(
weights?: Partial<ScoringWeights>,
reasoningConfig?: Partial<import('../reasoning/types.js').ReasoningConfig>
) {
super(weights);
this.reasoningConfig = reasoningConfig as import('../reasoning/types.js').ReasoningConfig;
}
async initReasoning(): Promise<void> {
const { createReasoningEngine } = await import('../reasoning/engine.js');
this.reasoningEngine = createReasoningEngine(this.reasoningConfig);
const index = this.getIndex();
if (index) {
this.reasoningEngine.loadSkills(index.skills);
this.reasoningEngine.generateTree(index.skills);
}
}
async recommendWithReasoning(
profile: ProjectProfile,
options: import('./types.js').ReasoningRecommendOptions = {}
): Promise<import('./types.js').ReasoningRecommendationResult> {
const baseResult = this.recommend(profile, options);
if (!options.reasoning || !this.reasoningEngine) {
return {
...baseResult,
recommendations: baseResult.recommendations.map((r) => ({
...r,
treePath: [],
})),
};
}
const searchResult = await this.reasoningEngine.search({
query: this.buildQueryFromProfile(profile),
context: profile,
maxResults: options.limit ?? 10,
minConfidence: options.minScore ?? 30,
});
const enhancedRecommendations: import('./types.js').ExplainedScoredSkill[] = [];
for (const rec of baseResult.recommendations) {
const treeResult = searchResult.results.find(
(r) => r.skill.name === rec.skill.name
);
let explanation: import('./types.js').ExplainedMatchDetails | undefined;
if (options.explainResults) {
const explainedRec = await this.reasoningEngine.explain(
rec.skill,
rec.score,
profile
);
explanation = explainedRec.reasoning;
}
enhancedRecommendations.push({
...rec,
explanation,
treePath: treeResult?.path ?? [],
reasoningDetails: treeResult?.reasoning,
});
}
return {
...baseResult,
recommendations: enhancedRecommendations,
reasoningSummary: searchResult.reasoning,
searchPlan: {
primaryCategories: [],
secondaryCategories: [],
keywords: this.extractKeywords(profile),
strategy: 'breadth-first',
},
};
}
private buildQueryFromProfile(profile: ProjectProfile): string {
const parts: string[] = [];
if (profile.type) {
parts.push(profile.type);
}
for (const framework of profile.stack.frameworks.slice(0, 3)) {
parts.push(framework.name);
}
for (const language of profile.stack.languages.slice(0, 2)) {
parts.push(language.name);
}
return parts.join(' ');
}
private extractKeywords(profile: ProjectProfile): string[] {
const keywords: string[] = [];
if (profile.type) {
keywords.push(profile.type);
}
for (const framework of profile.stack.frameworks) {
keywords.push(framework.name.toLowerCase());
}
for (const language of profile.stack.languages) {
keywords.push(language.name.toLowerCase());
}
return [...new Set(keywords)];
}
getReasoningStats(): import('../reasoning/types.js').ReasoningEngineStats | null {
return this.reasoningEngine?.getStats() ?? null;
}
getSkillTree(): import('../tree/types.js').SkillTree | null {
return this.reasoningEngine?.getTree() ?? null;
}
}
/**
* Create an enhanced recommendation engine with reasoning support
*/
export function createReasoningRecommendationEngine(
weights?: Partial<ScoringWeights>
): ReasoningRecommendationEngine {
return new ReasoningRecommendationEngine(weights);
}
+6 -1
View File
@@ -14,7 +14,12 @@
export * from './types.js';
export * from './engine.js';
export * from './fetcher.js';
export { createRecommendationEngine, RecommendationEngine } from './engine.js';
export {
createRecommendationEngine,
RecommendationEngine,
ReasoningRecommendationEngine,
createReasoningRecommendationEngine,
} from './engine.js';
export {
fetchSkillsFromRepo,
buildSkillIndex,
+42
View File
@@ -284,3 +284,45 @@ export function getTechTags(techName: string): string[] {
}
return tags;
}
/**
* Enhanced recommendation options with reasoning support
*/
export interface ReasoningRecommendOptions extends RecommendOptions {
reasoning?: boolean;
explainResults?: boolean;
useTree?: boolean;
}
/**
* Explained match details
*/
export interface ExplainedMatchDetails {
matchedBecause: string[];
relevantFor: string[];
differentFrom: string[];
confidence: 'high' | 'medium' | 'low';
}
/**
* Enhanced scored skill with reasoning
*/
export interface ExplainedScoredSkill extends ScoredSkill {
explanation?: ExplainedMatchDetails;
treePath?: string[];
reasoningDetails?: string;
}
/**
* Enhanced recommendation result with reasoning
*/
export interface ReasoningRecommendationResult extends RecommendationResult {
recommendations: ExplainedScoredSkill[];
reasoningSummary?: string;
searchPlan?: {
primaryCategories: string[];
secondaryCategories: string[];
keywords: string[];
strategy: string;
};
}
+352
View File
@@ -0,0 +1,352 @@
import type { SkillSummary } from '../recommend/types.js';
import {
type TreeNode,
type SkillTree,
type TreeGeneratorOptions,
type CategoryMapping,
CATEGORY_TAXONOMY,
} from './types.js';
const DEFAULT_OPTIONS: Required<TreeGeneratorOptions> = {
maxDepth: 3,
minSkillsPerNode: 1,
includeEmpty: false,
};
export class TreeGenerator {
private options: Required<TreeGeneratorOptions>;
constructor(options?: TreeGeneratorOptions) {
this.options = { ...DEFAULT_OPTIONS, ...options };
}
generateTree(skills: SkillSummary[]): SkillTree {
const rootNode = this.buildTreeFromTaxonomy(skills);
const { totalCategories, maxDepth } = this.countTreeStats(rootNode);
return {
version: 1,
generatedAt: new Date().toISOString(),
rootNode,
totalSkills: skills.length,
totalCategories,
maxDepth,
};
}
private buildTreeFromTaxonomy(skills: SkillSummary[]): TreeNode {
const root: TreeNode = {
id: 'root',
name: 'Skills',
description: 'All available skills organized by category',
children: [],
skills: [],
skillCount: skills.length,
depth: 0,
};
const uncategorized: string[] = [];
for (const category of CATEGORY_TAXONOMY) {
const categoryNode = this.buildCategoryNode(category, skills, 1);
if (categoryNode.skillCount > 0 || this.options.includeEmpty) {
root.children.push(categoryNode);
}
}
for (const skill of skills) {
if (!this.isSkillCategorized(skill)) {
uncategorized.push(skill.name);
}
}
if (uncategorized.length > 0) {
root.children.push({
id: 'other',
name: 'Other',
description: 'Skills without specific categorization',
children: [],
skills: uncategorized,
skillCount: uncategorized.length,
depth: 1,
});
}
return root;
}
private buildCategoryNode(
category: CategoryMapping,
skills: SkillSummary[],
depth: number
): TreeNode {
const categorySkills = this.filterSkillsByCategory(skills, category);
const subcategoryNodes: TreeNode[] = [];
if (depth < this.options.maxDepth) {
for (const subcategory of category.subcategories) {
const subcategorySkills = this.filterSkillsBySubcategory(
categorySkills,
subcategory,
category
);
if (
subcategorySkills.length >= this.options.minSkillsPerNode ||
this.options.includeEmpty
) {
subcategoryNodes.push({
id: `${category.category.toLowerCase().replace(/[^a-z0-9]/g, '-')}-${subcategory.toLowerCase().replace(/[^a-z0-9]/g, '-')}`,
name: subcategory,
description: `${subcategory} skills in ${category.category}`,
children: [],
skills: subcategorySkills.map((s) => s.name),
skillCount: subcategorySkills.length,
depth: depth + 1,
});
}
}
}
const directSkills = categorySkills.filter(
(skill) =>
!subcategoryNodes.some((node) => node.skills.includes(skill.name))
);
const totalSkillCount =
directSkills.length +
subcategoryNodes.reduce((sum, node) => sum + node.skillCount, 0);
return {
id: category.category.toLowerCase().replace(/[^a-z0-9]/g, '-'),
name: category.category,
description: `${category.category} related skills`,
children: subcategoryNodes,
skills: directSkills.map((s) => s.name),
skillCount: totalSkillCount,
depth,
};
}
private filterSkillsByCategory(
skills: SkillSummary[],
category: CategoryMapping
): SkillSummary[] {
return skills.filter((skill) => {
const skillTags = (skill.tags || []).map((t) => t.toLowerCase());
const skillName = skill.name.toLowerCase();
const skillDesc = (skill.description || '').toLowerCase();
const tagMatch = skillTags.some((tag) =>
category.tags.includes(tag)
);
const keywordMatch = category.keywords.some(
(keyword) =>
skillName.includes(keyword) || skillDesc.includes(keyword)
);
const categoryNameMatch =
skillName.includes(category.category.toLowerCase()) ||
skillDesc.includes(category.category.toLowerCase());
return tagMatch || keywordMatch || categoryNameMatch;
});
}
private filterSkillsBySubcategory(
skills: SkillSummary[],
subcategory: string,
_parentCategory: CategoryMapping
): SkillSummary[] {
const subcategoryLower = subcategory.toLowerCase();
const subcategoryNormalized = subcategoryLower.replace(/[^a-z0-9]/g, '');
return skills.filter((skill) => {
const skillTags = (skill.tags || []).map((t) => t.toLowerCase());
const skillName = skill.name.toLowerCase();
const skillDesc = (skill.description || '').toLowerCase();
const tagMatch = skillTags.some(
(tag) =>
tag === subcategoryLower ||
tag === subcategoryNormalized ||
tag.includes(subcategoryLower)
);
const nameMatch =
skillName.includes(subcategoryLower) ||
skillName.includes(subcategoryNormalized);
const descMatch =
skillDesc.includes(subcategoryLower) ||
skillDesc.includes(subcategoryNormalized);
const compatibilityMatch =
skill.compatibility?.frameworks?.some(
(f) =>
f.toLowerCase() === subcategoryLower ||
f.toLowerCase() === subcategoryNormalized
) ||
skill.compatibility?.languages?.some(
(l) =>
l.toLowerCase() === subcategoryLower ||
l.toLowerCase() === subcategoryNormalized
);
return tagMatch || nameMatch || descMatch || compatibilityMatch;
});
}
private isSkillCategorized(skill: SkillSummary): boolean {
for (const category of CATEGORY_TAXONOMY) {
const skillTags = (skill.tags || []).map((t) => t.toLowerCase());
const skillName = skill.name.toLowerCase();
const skillDesc = (skill.description || '').toLowerCase();
const tagMatch = skillTags.some((tag) => category.tags.includes(tag));
const keywordMatch = category.keywords.some(
(keyword) =>
skillName.includes(keyword) || skillDesc.includes(keyword)
);
if (tagMatch || keywordMatch) {
return true;
}
}
return false;
}
private countTreeStats(node: TreeNode): {
totalCategories: number;
maxDepth: number;
} {
let totalCategories = 1;
let maxDepth = node.depth;
for (const child of node.children) {
const childStats = this.countTreeStats(child);
totalCategories += childStats.totalCategories;
maxDepth = Math.max(maxDepth, childStats.maxDepth);
}
return { totalCategories, maxDepth };
}
findNode(tree: SkillTree, path: string[]): TreeNode | null {
let current = tree.rootNode;
for (const segment of path) {
const child = current.children.find(
(c) => c.name.toLowerCase() === segment.toLowerCase()
);
if (!child) {
return null;
}
current = child;
}
return current;
}
getPath(tree: SkillTree, skillName: string): string[] | null {
const findPath = (node: TreeNode, path: string[]): string[] | null => {
if (node.skills.includes(skillName)) {
return [...path, node.name];
}
for (const child of node.children) {
const result = findPath(child, [...path, node.name]);
if (result) {
return result;
}
}
return null;
};
const result = findPath(tree.rootNode, []);
return result ? result.slice(1) : null;
}
getAllPaths(tree: SkillTree): Map<string, string[]> {
const paths = new Map<string, string[]>();
const traverse = (node: TreeNode, currentPath: string[]) => {
for (const skillName of node.skills) {
paths.set(skillName, currentPath);
}
for (const child of node.children) {
traverse(child, [...currentPath, child.name]);
}
};
traverse(tree.rootNode, []);
return paths;
}
getNodesAtDepth(tree: SkillTree, depth: number): TreeNode[] {
const nodes: TreeNode[] = [];
const traverse = (node: TreeNode) => {
if (node.depth === depth) {
nodes.push(node);
} else if (node.depth < depth) {
for (const child of node.children) {
traverse(child);
}
}
};
traverse(tree.rootNode);
return nodes;
}
flattenTree(tree: SkillTree): TreeNode[] {
const nodes: TreeNode[] = [];
const traverse = (node: TreeNode) => {
nodes.push(node);
for (const child of node.children) {
traverse(child);
}
};
traverse(tree.rootNode);
return nodes;
}
searchTree(tree: SkillTree, query: string): TreeNode[] {
const queryLower = query.toLowerCase();
const results: TreeNode[] = [];
const traverse = (node: TreeNode) => {
const nameMatch = node.name.toLowerCase().includes(queryLower);
const descMatch = (node.description || '').toLowerCase().includes(queryLower);
const skillMatch = node.skills.some((s) =>
s.toLowerCase().includes(queryLower)
);
if (nameMatch || descMatch || skillMatch) {
results.push(node);
}
for (const child of node.children) {
traverse(child);
}
};
traverse(tree.rootNode);
return results;
}
}
export function generateSkillTree(
skills: SkillSummary[],
options?: TreeGeneratorOptions
): SkillTree {
const generator = new TreeGenerator(options);
return generator.generateTree(skills);
}
+322
View File
@@ -0,0 +1,322 @@
import type { SkillSummary } from '../recommend/types.js';
import type { TreeNode, SkillTree } from './types.js';
export type RelationType = 'similar' | 'complementary' | 'dependency' | 'alternative';
export interface SkillRelation {
skillName: string;
relationType: RelationType;
strength: number;
reason: string;
}
export interface SkillNode {
name: string;
tags: string[];
source?: string;
relations: SkillRelation[];
}
export interface SkillGraph {
version: number;
generatedAt: string;
nodes: Map<string, SkillNode>;
totalSkills: number;
totalRelations: number;
}
export interface RelatedSkillResult {
skill: SkillSummary;
relationType: RelationType;
strength: number;
reason: string;
path?: string[];
}
const TAG_SIMILARITY_THRESHOLD = 0.3;
const MAX_RELATIONS_PER_SKILL = 10;
export function buildSkillGraph(skills: SkillSummary[]): SkillGraph {
const nodes = new Map<string, SkillNode>();
let totalRelations = 0;
for (const skill of skills) {
const node: SkillNode = {
name: skill.name,
tags: skill.tags || [],
source: skill.source,
relations: [],
};
nodes.set(skill.name, node);
}
for (const skill of skills) {
const node = nodes.get(skill.name);
if (!node) continue;
const relatedSkills = findRelatedSkills(skill, skills);
node.relations = relatedSkills.slice(0, MAX_RELATIONS_PER_SKILL);
totalRelations += node.relations.length;
}
return {
version: 1,
generatedAt: new Date().toISOString(),
nodes,
totalSkills: skills.length,
totalRelations,
};
}
function findRelatedSkills(
skill: SkillSummary,
allSkills: SkillSummary[]
): SkillRelation[] {
const relations: SkillRelation[] = [];
const skillTags = new Set<string>(skill.tags || []);
const skillName = skill.name.toLowerCase();
for (const other of allSkills) {
if (other.name === skill.name) continue;
const otherTags = new Set<string>(other.tags || []);
const otherName = other.name.toLowerCase();
const commonTags: string[] = [...skillTags].filter((tag) => otherTags.has(tag));
const totalTags = new Set([...skillTags, ...otherTags]).size;
const tagSimilarity = totalTags > 0 ? commonTags.length / totalTags : 0;
if (tagSimilarity >= TAG_SIMILARITY_THRESHOLD) {
const relationType = determineRelationType(skill, other, commonTags);
const reason = generateRelationReason(relationType, commonTags);
relations.push({
skillName: other.name,
relationType,
strength: Math.round(tagSimilarity * 100),
reason,
});
}
if (skillName.includes(otherName) || otherName.includes(skillName)) {
const existing = relations.find((r) => r.skillName === other.name);
if (!existing) {
relations.push({
skillName: other.name,
relationType: 'similar',
strength: 50,
reason: 'Related by name',
});
}
}
if (skill.source && other.source && skill.source === other.source) {
const existing = relations.find((r) => r.skillName === other.name);
if (existing) {
existing.strength = Math.min(100, existing.strength + 20);
} else if (commonTags.length > 0) {
relations.push({
skillName: other.name,
relationType: 'similar',
strength: 30,
reason: `Same source: ${skill.source}`,
});
}
}
}
return relations.sort((a, b) => b.strength - a.strength);
}
function determineRelationType(
skill: SkillSummary,
other: SkillSummary,
_commonTags: string[]
): RelationType {
const complementaryPairs = [
['frontend', 'backend'],
['testing', 'development'],
['security', 'api'],
['database', 'api'],
['docker', 'kubernetes'],
];
const skillTags = skill.tags || [];
const otherTags = other.tags || [];
for (const [tag1, tag2] of complementaryPairs) {
if (
(skillTags.includes(tag1) && otherTags.includes(tag2)) ||
(skillTags.includes(tag2) && otherTags.includes(tag1))
) {
return 'complementary';
}
}
const alternativeIndicators = ['vs', 'alternative', 'instead'];
const skillName = skill.name.toLowerCase();
const otherName = other.name.toLowerCase();
for (const indicator of alternativeIndicators) {
if (skillName.includes(indicator) || otherName.includes(indicator)) {
return 'alternative';
}
}
return 'similar';
}
function generateRelationReason(relationType: RelationType, commonTags: string[]): string {
switch (relationType) {
case 'similar':
return commonTags.length > 0
? `Shares tags: ${commonTags.slice(0, 3).join(', ')}`
: 'Similar functionality';
case 'complementary':
return 'Works well together';
case 'dependency':
return 'Required by this skill';
case 'alternative':
return 'Alternative approach';
default:
return 'Related skill';
}
}
export function getRelatedSkills(
skillName: string,
graph: SkillGraph,
skills: SkillSummary[],
options: {
limit?: number;
types?: RelationType[];
minStrength?: number;
} = {}
): RelatedSkillResult[] {
const { limit = 5, types, minStrength = 0 } = options;
const node = graph.nodes.get(skillName);
if (!node) return [];
const skillMap = new Map(skills.map((s) => [s.name, s]));
return node.relations
.filter((r) => {
if (types && !types.includes(r.relationType)) return false;
if (r.strength < minStrength) return false;
return true;
})
.slice(0, limit)
.map((r) => ({
skill: skillMap.get(r.skillName)!,
relationType: r.relationType,
strength: r.strength,
reason: r.reason,
}))
.filter((r) => r.skill);
}
export function findSkillsByRelationType(
graph: SkillGraph,
skills: SkillSummary[],
relationType: RelationType,
limit: number = 10
): Array<{ skill: SkillSummary; relatedCount: number }> {
const skillMap = new Map(skills.map((s) => [s.name, s]));
const counts: Map<string, number> = new Map();
for (const [_skillName, node] of graph.nodes) {
const typeRelations = node.relations.filter((r) => r.relationType === relationType);
counts.set(node.name, typeRelations.length);
}
return [...counts.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, limit)
.map(([name, count]) => ({
skill: skillMap.get(name)!,
relatedCount: count,
}))
.filter((r) => r.skill);
}
export function getSkillPath(
fromSkillName: string,
toSkillName: string,
graph: SkillGraph,
maxHops: number = 3
): string[] | null {
if (fromSkillName === toSkillName) return [fromSkillName];
const visited = new Set<string>();
const queue: Array<{ name: string; path: string[] }> = [
{ name: fromSkillName, path: [fromSkillName] },
];
while (queue.length > 0) {
const current = queue.shift()!;
if (current.path.length > maxHops + 1) continue;
const node = graph.nodes.get(current.name);
if (!node) continue;
for (const relation of node.relations) {
if (relation.skillName === toSkillName) {
return [...current.path, toSkillName];
}
if (!visited.has(relation.skillName)) {
visited.add(relation.skillName);
queue.push({
name: relation.skillName,
path: [...current.path, relation.skillName],
});
}
}
}
return null;
}
export function findSkillsInCategory(tree: SkillTree, categoryPath: string[]): string[] {
let current: TreeNode = tree.rootNode;
for (const segment of categoryPath) {
const child = current.children.find(
(c) => c.name.toLowerCase() === segment.toLowerCase()
);
if (!child) return [];
current = child;
}
return collectSkillsRecursive(current);
}
function collectSkillsRecursive(node: TreeNode): string[] {
const skills: string[] = [...node.skills];
for (const child of node.children) {
skills.push(...collectSkillsRecursive(child));
}
return skills;
}
export function serializeGraph(graph: SkillGraph): string {
const serialized = {
version: graph.version,
generatedAt: graph.generatedAt,
totalSkills: graph.totalSkills,
totalRelations: graph.totalRelations,
nodes: Object.fromEntries(graph.nodes),
};
return JSON.stringify(serialized, null, 2);
}
export function deserializeGraph(json: string): SkillGraph {
const parsed = JSON.parse(json);
return {
version: parsed.version,
generatedAt: parsed.generatedAt,
totalSkills: parsed.totalSkills,
totalRelations: parsed.totalRelations,
nodes: new Map(Object.entries(parsed.nodes)),
};
}
+25
View File
@@ -0,0 +1,25 @@
export * from './types.js';
export * from './generator.js';
export * from './serializer.js';
export * from './graph.js';
export { TreeGenerator, generateSkillTree } from './generator.js';
export {
serializeTree,
deserializeTree,
saveTree,
loadTree,
treeToText,
treeToMarkdown,
compareTreeVersions,
TREE_FILE_NAME,
} from './serializer.js';
export {
buildSkillGraph,
getRelatedSkills,
findSkillsByRelationType,
getSkillPath,
findSkillsInCategory,
serializeGraph,
deserializeGraph,
} from './graph.js';
+191
View File
@@ -0,0 +1,191 @@
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import type { SkillTree, TreeNode } from './types.js';
import { SkillTreeSchema } from './types.js';
export const TREE_FILE_NAME = 'skill-tree.json';
export function serializeTree(tree: SkillTree): string {
return JSON.stringify(tree, null, 2);
}
export function deserializeTree(json: string): SkillTree {
const parsed = JSON.parse(json);
return SkillTreeSchema.parse(parsed);
}
export function saveTree(tree: SkillTree, path: string): void {
const dir = dirname(path);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
const json = serializeTree(tree);
writeFileSync(path, json, 'utf-8');
}
export function loadTree(path: string): SkillTree | null {
if (!existsSync(path)) {
return null;
}
try {
const json = readFileSync(path, 'utf-8');
return deserializeTree(json);
} catch {
return null;
}
}
export function treeToText(tree: SkillTree, options?: { maxDepth?: number }): string {
const maxDepth = options?.maxDepth ?? Infinity;
const lines: string[] = [];
lines.push(`Skill Tree (${tree.totalSkills} skills, ${tree.totalCategories} categories)`);
lines.push(`Generated: ${tree.generatedAt}`);
lines.push('');
const renderNode = (node: TreeNode, prefix: string, isLast: boolean, depth: number) => {
if (depth > maxDepth) return;
const connector = isLast ? '└── ' : '├── ';
const skillInfo =
node.skillCount > 0 ? ` (${node.skillCount} skills)` : '';
lines.push(`${prefix}${connector}${node.name}${skillInfo}`);
const newPrefix = prefix + (isLast ? ' ' : '│ ');
if (node.children.length > 0 && depth < maxDepth) {
node.children.forEach((child, index) => {
const childIsLast = index === node.children.length - 1;
renderNode(child, newPrefix, childIsLast, depth + 1);
});
}
};
const root = tree.rootNode;
lines.push(root.name);
root.children.forEach((child, index) => {
const isLast = index === root.children.length - 1;
renderNode(child, '', isLast, 1);
});
return lines.join('\n');
}
export function treeToMarkdown(tree: SkillTree): string {
const lines: string[] = [];
lines.push(`# Skill Tree`);
lines.push('');
lines.push(`> ${tree.totalSkills} skills organized in ${tree.totalCategories} categories`);
lines.push('');
lines.push(`*Generated: ${tree.generatedAt}*`);
lines.push('');
const renderNode = (node: TreeNode, depth: number) => {
const indent = ' '.repeat(depth);
const bullet = depth === 0 ? '##' : '-';
if (depth === 0) {
lines.push(`${bullet} ${node.name}`);
} else {
const skillCount = node.skillCount > 0 ? ` *(${node.skillCount})*` : '';
lines.push(`${indent}${bullet} **${node.name}**${skillCount}`);
}
if (node.skills.length > 0 && node.skills.length <= 10) {
for (const skill of node.skills) {
lines.push(`${indent} - \`${skill}\``);
}
} else if (node.skills.length > 10) {
for (const skill of node.skills.slice(0, 5)) {
lines.push(`${indent} - \`${skill}\``);
}
lines.push(`${indent} - *... and ${node.skills.length - 5} more*`);
}
for (const child of node.children) {
renderNode(child, depth + 1);
}
};
for (const category of tree.rootNode.children) {
renderNode(category, 0);
lines.push('');
}
return lines.join('\n');
}
export function compareTreeVersions(
oldTree: SkillTree,
newTree: SkillTree
): {
added: string[];
removed: string[];
moved: { skill: string; from: string[]; to: string[] }[];
} {
const oldSkills = getAllSkillsWithPaths(oldTree.rootNode);
const newSkills = getAllSkillsWithPaths(newTree.rootNode);
const oldNames = new Set(oldSkills.map((s) => s.name));
const newNames = new Set(newSkills.map((s) => s.name));
const added: string[] = [];
const removed: string[] = [];
const moved: { skill: string; from: string[]; to: string[] }[] = [];
for (const skill of newSkills) {
if (!oldNames.has(skill.name)) {
added.push(skill.name);
}
}
for (const skill of oldSkills) {
if (!newNames.has(skill.name)) {
removed.push(skill.name);
}
}
for (const newSkill of newSkills) {
const oldSkill = oldSkills.find((s) => s.name === newSkill.name);
if (oldSkill && !arraysEqual(oldSkill.path, newSkill.path)) {
moved.push({
skill: newSkill.name,
from: oldSkill.path,
to: newSkill.path,
});
}
}
return { added, removed, moved };
}
function getAllSkillsWithPaths(
node: TreeNode,
currentPath: string[] = []
): { name: string; path: string[] }[] {
const results: { name: string; path: string[] }[] = [];
const path = [...currentPath, node.name];
for (const skill of node.skills) {
results.push({ name: skill, path });
}
for (const child of node.children) {
results.push(...getAllSkillsWithPaths(child, path));
}
return results;
}
function arraysEqual(a: string[], b: string[]): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
+142
View File
@@ -0,0 +1,142 @@
import { z } from 'zod';
const BaseTreeNodeSchema = z.object({
id: z.string(),
name: z.string(),
description: z.string().optional(),
skills: z.array(z.string()).default([]),
skillCount: z.number().default(0),
depth: z.number().default(0),
});
export interface TreeNode {
id: string;
name: string;
description?: string;
children: TreeNode[];
skills: string[];
skillCount: number;
depth: number;
}
export const TreeNodeSchema: z.ZodType<TreeNode> = BaseTreeNodeSchema.extend({
children: z.lazy(() => z.array(TreeNodeSchema)).default([]),
}) as z.ZodType<TreeNode>;
export const SkillTreeSchema = z.object({
version: z.number().default(1),
generatedAt: z.string(),
rootNode: TreeNodeSchema,
totalSkills: z.number(),
totalCategories: z.number(),
maxDepth: z.number(),
});
export type SkillTree = z.infer<typeof SkillTreeSchema>;
export interface TreePath {
segments: string[];
node: TreeNode;
}
export interface CategoryMapping {
category: string;
subcategories: string[];
tags: string[];
keywords: string[];
}
export const CATEGORY_TAXONOMY: CategoryMapping[] = [
{
category: 'Development',
subcategories: ['Frontend', 'Backend', 'Mobile', 'Desktop', 'Full-Stack'],
tags: ['development', 'coding', 'programming', 'software'],
keywords: ['build', 'create', 'develop', 'code', 'implement'],
},
{
category: 'Frontend',
subcategories: ['React', 'Vue', 'Angular', 'Svelte', 'Solid', 'Astro', 'Next.js', 'Nuxt', 'Remix'],
tags: ['frontend', 'ui', 'ux', 'web', 'client', 'browser', 'react', 'vue', 'angular', 'svelte', 'solid', 'astro', 'nextjs', 'nuxt', 'remix'],
keywords: ['component', 'ui', 'interface', 'layout', 'style', 'css', 'html'],
},
{
category: 'Backend',
subcategories: ['Node.js', 'Python', 'Go', 'Rust', 'Java', 'C#', 'Express', 'FastAPI', 'Django', 'Flask'],
tags: ['backend', 'server', 'api', 'node', 'nodejs', 'python', 'go', 'rust', 'java', 'express', 'fastapi', 'django', 'flask', 'fastify', 'koa', 'hono', 'nestjs'],
keywords: ['server', 'api', 'endpoint', 'route', 'handler', 'middleware'],
},
{
category: 'Mobile',
subcategories: ['React Native', 'Flutter', 'iOS', 'Android', 'Expo'],
tags: ['mobile', 'ios', 'android', 'react-native', 'flutter', 'expo', 'native'],
keywords: ['app', 'mobile', 'phone', 'tablet', 'native'],
},
{
category: 'DevOps',
subcategories: ['CI/CD', 'Kubernetes', 'Docker', 'Cloud', 'Infrastructure'],
tags: ['devops', 'ci', 'cd', 'cicd', 'kubernetes', 'k8s', 'docker', 'container', 'aws', 'gcp', 'azure', 'cloud', 'infrastructure', 'iac'],
keywords: ['deploy', 'pipeline', 'container', 'orchestration', 'infra'],
},
{
category: 'Testing',
subcategories: ['Unit Testing', 'E2E Testing', 'Integration Testing', 'TDD'],
tags: ['testing', 'test', 'unit', 'e2e', 'integration', 'jest', 'vitest', 'playwright', 'cypress', 'tdd'],
keywords: ['test', 'spec', 'assertion', 'mock', 'coverage'],
},
{
category: 'Security',
subcategories: ['Authentication', 'Authorization', 'Encryption', 'Audit'],
tags: ['security', 'auth', 'authentication', 'authorization', 'oauth', 'jwt', 'encryption', 'audit', 'vulnerability'],
keywords: ['secure', 'protect', 'encrypt', 'authenticate', 'authorize'],
},
{
category: 'AI/ML',
subcategories: ['LLM Integration', 'Agents', 'RAG', 'Training', 'Inference'],
tags: ['ai', 'ml', 'llm', 'openai', 'anthropic', 'gpt', 'claude', 'agent', 'rag', 'embedding', 'vector', 'training', 'inference'],
keywords: ['ai', 'model', 'predict', 'generate', 'embed', 'chat'],
},
{
category: 'Database',
subcategories: ['SQL', 'NoSQL', 'ORM', 'Migrations'],
tags: ['database', 'db', 'sql', 'nosql', 'postgres', 'postgresql', 'mysql', 'mongodb', 'redis', 'supabase', 'firebase', 'prisma', 'drizzle'],
keywords: ['query', 'schema', 'migration', 'model', 'record'],
},
{
category: 'Tooling',
subcategories: ['Linting', 'Formatting', 'Building', 'Bundling'],
tags: ['tooling', 'tool', 'eslint', 'prettier', 'biome', 'webpack', 'vite', 'rollup', 'turbo', 'turborepo', 'monorepo'],
keywords: ['lint', 'format', 'build', 'bundle', 'compile'],
},
{
category: 'Documentation',
subcategories: ['API Docs', 'Guides', 'READMEs', 'Comments'],
tags: ['documentation', 'docs', 'readme', 'api-docs', 'jsdoc', 'typedoc', 'storybook'],
keywords: ['doc', 'document', 'guide', 'readme', 'comment'],
},
{
category: 'Performance',
subcategories: ['Optimization', 'Caching', 'Profiling', 'Monitoring'],
tags: ['performance', 'optimization', 'cache', 'caching', 'profiling', 'monitoring', 'metrics', 'observability'],
keywords: ['optimize', 'fast', 'cache', 'profile', 'monitor'],
},
];
export const TAG_TO_CATEGORY: Record<string, string[]> = {};
for (const mapping of CATEGORY_TAXONOMY) {
for (const tag of mapping.tags) {
if (!TAG_TO_CATEGORY[tag]) {
TAG_TO_CATEGORY[tag] = [];
}
TAG_TO_CATEGORY[tag].push(mapping.category);
for (const subcategory of mapping.subcategories) {
TAG_TO_CATEGORY[tag].push(`${mapping.category} > ${subcategory}`);
}
}
}
export interface TreeGeneratorOptions {
maxDepth?: number;
minSkillsPerNode?: number;
includeEmpty?: boolean;
}
+1 -1
View File
@@ -36,7 +36,7 @@ export const AgentType = z.enum([
]);
export type AgentType = z.infer<typeof AgentType>;
export const GitProvider = z.enum(['github', 'gitlab', 'bitbucket', 'local']);
export const GitProvider = z.enum(['github', 'gitlab', 'bitbucket', 'local', 'wellknown']);
export type GitProvider = z.infer<typeof GitProvider>;
export const SkillFrontmatter = z.object({
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/mcp-memory",
"version": "1.8.0",
"version": "1.9.0",
"description": "MCP (Model Context Protocol) server for SkillKit persistent memory",
"type": "module",
"main": "./dist/index.js",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/memory",
"version": "1.8.0",
"version": "1.9.0",
"description": "CozoDB-backed semantic memory with embeddings for SkillKit",
"type": "module",
"main": "./dist/index.js",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/mesh",
"version": "1.8.0",
"version": "1.9.0",
"description": "Peer mesh network for multi-machine agent distribution",
"type": "module",
"main": "./dist/index.js",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/messaging",
"version": "1.8.0",
"version": "1.9.0",
"description": "Inter-agent messaging system for SkillKit",
"type": "module",
"main": "./dist/index.js",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/resources",
"version": "1.8.0",
"version": "1.9.0",
"description": "Bundled resources for SkillKit - agents, commands, profiles, guidelines, and hooks",
"type": "module",
"main": "./dist/index.js",
+6 -6
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/tui",
"version": "1.8.0",
"version": "1.9.0",
"description": "Unified Terminal UI for SkillKit - Built on OpenTUI",
"type": "module",
"main": "./dist/index.js",
@@ -21,15 +21,15 @@
"test": "vitest run"
},
"dependencies": {
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"@opentui/core": "^0.1.75",
"@opentui/react": "^0.1.75",
"react": "^19.0.0"
"@opentui/solid": "^0.1.75",
"@skillkit/agents": "workspace:*",
"@skillkit/core": "workspace:*",
"solid-js": "^1.9.0"
},
"devDependencies": {
"@types/node": "^22.10.5",
"@types/react": "^19.0.0",
"esbuild-plugin-solid": "^0.6.0",
"tsup": "^8.3.5",
"typescript": "^5.7.2",
"vitest": "^2.1.8"
+91 -67
View File
@@ -1,9 +1,10 @@
import { useState, useCallback, useEffect } from 'react';
import { useKeyboard } from '@opentui/react';
import { exec } from 'node:child_process';
import { createSignal, createEffect, onCleanup, Show, Switch, Match } from 'solid-js';
import { useKeyboard } from '@opentui/solid';
import { execFile } from 'node:child_process';
import { type Screen, NAV_KEYS } from './state/types.js';
import { Sidebar } from './components/Sidebar.js';
import { Splash } from './components/Splash.js';
import { Sidebar } from './components/Sidebar.js';
import { StatusBar } from './components/StatusBar.js';
import {
Home, Browse, Installed, Marketplace, Settings, Recommend,
Translate, Context, Memory, Team, Plugins, Methodology,
@@ -13,23 +14,28 @@ import {
const DOCS_URL = 'https://agenstskills.com/docs';
function openUrl(url: string): void {
const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';
exec(`${cmd} ${url}`);
if (process.platform === 'win32') {
execFile('cmd', ['/c', 'start', '', url]);
} else {
const cmd = process.platform === 'darwin' ? 'open' : 'xdg-open';
execFile(cmd, [url]);
}
}
interface AppProps {
onExit?: (code?: number) => void;
}
export function App({ onExit }: AppProps = {}) {
const [showSplash, setShowSplash] = useState(true);
const [screen, setScreen] = useState<Screen>('home');
const [dimensions, setDimensions] = useState({
export function App(props: AppProps) {
const [showSplash, setShowSplash] = createSignal(true);
const [currentScreen, setCurrentScreen] = createSignal<Screen>('home');
const [showSidebar, setShowSidebar] = createSignal(true);
const [dimensions, setDimensions] = createSignal({
cols: process.stdout.columns || 80,
rows: process.stdout.rows || 24,
});
useEffect(() => {
createEffect(() => {
const handleResize = () => {
setDimensions({
cols: process.stdout.columns || 80,
@@ -37,28 +43,38 @@ export function App({ onExit }: AppProps = {}) {
});
};
process.stdout.on('resize', handleResize);
return () => { process.stdout.off('resize', handleResize); };
}, []);
onCleanup(() => {
process.stdout.off('resize', handleResize);
});
});
const { cols, rows } = dimensions;
const showSidebar = cols >= 60;
const cols = () => dimensions().cols;
const rows = () => dimensions().rows;
const sidebarVisible = () => showSidebar() && cols() >= 80;
const sidebarWidth = () => {
if (!sidebarVisible()) return 0;
if (cols() >= 100) return 24;
return 18;
};
const statusBarHeight = 2;
const contentHeight = () => rows() - statusBarHeight;
const handleNavigate = useCallback((newScreen: Screen) => {
setScreen(newScreen);
}, []);
const handleNavigate = (newScreen: Screen) => {
setCurrentScreen(newScreen);
};
const handleSplashComplete = useCallback(() => {
const handleSplashComplete = () => {
setShowSplash(false);
}, []);
};
useKeyboard((key: { name?: string; ctrl?: boolean }) => {
if (showSplash) {
useKeyboard((key: { name?: string; ctrl?: boolean; sequence?: string }) => {
if (showSplash()) {
setShowSplash(false);
return;
}
if (key.name === 'q' || (key.ctrl && key.name === 'c')) {
onExit ? onExit(0) : process.exit(0);
props.onExit ? props.onExit(0) : process.exit(0);
return;
}
@@ -67,59 +83,67 @@ export function App({ onExit }: AppProps = {}) {
return;
}
const targetScreen = NAV_KEYS[key.name || ''];
if (targetScreen) {
setScreen(targetScreen);
if (key.sequence === '\\') {
setShowSidebar((v) => !v);
return;
}
if (key.name === 'escape' && screen !== 'home') {
setScreen('home');
const targetScreen = NAV_KEYS[key.name || ''];
if (targetScreen) {
setCurrentScreen(targetScreen);
}
if (key.name === 'escape' && currentScreen() !== 'home') {
setCurrentScreen('home');
}
});
if (showSplash) {
return <Splash onComplete={handleSplashComplete} duration={3000} />;
}
const screenProps = {
const screenProps = () => ({
onNavigate: handleNavigate,
cols: cols - (showSidebar ? 20 : 0),
rows,
};
const renderScreen = () => {
switch (screen) {
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} />;
case 'mesh': return <Mesh {...screenProps} />;
case 'message': return <Message {...screenProps} />;
default: return <Home {...screenProps} />;
}
};
cols: Math.max(1, cols() - sidebarWidth() - 2),
rows: Math.max(1, contentHeight() - 1),
});
return (
<box flexDirection="row" height={rows}>
{showSidebar && <Sidebar screen={screen} onNavigate={handleNavigate} />}
<box flexDirection="column" flexGrow={1} marginLeft={showSidebar ? 1 : 0} paddingRight={1}>
{renderScreen()}
<Show when={!showSplash()} fallback={<Splash onComplete={handleSplashComplete} duration={3000} />}>
<box flexDirection="column" height={rows()}>
<box flexDirection="row" height={contentHeight()}>
<Show when={sidebarVisible()}>
<Sidebar
screen={currentScreen()}
onNavigate={handleNavigate}
/>
</Show>
<box flexDirection="column" flexGrow={1} paddingX={1}>
<Switch fallback={<Home {...screenProps()} />}>
<Match when={currentScreen() === 'home'}><Home {...screenProps()} /></Match>
<Match when={currentScreen() === 'browse'}><Browse {...screenProps()} /></Match>
<Match when={currentScreen() === 'installed'}><Installed {...screenProps()} /></Match>
<Match when={currentScreen() === 'marketplace'}><Marketplace {...screenProps()} /></Match>
<Match when={currentScreen() === 'settings'}><Settings {...screenProps()} /></Match>
<Match when={currentScreen() === 'recommend'}><Recommend {...screenProps()} /></Match>
<Match when={currentScreen() === 'translate'}><Translate {...screenProps()} /></Match>
<Match when={currentScreen() === 'context'}><Context {...screenProps()} /></Match>
<Match when={currentScreen() === 'memory'}><Memory {...screenProps()} /></Match>
<Match when={currentScreen() === 'team'}><Team {...screenProps()} /></Match>
<Match when={currentScreen() === 'plugins'}><Plugins {...screenProps()} /></Match>
<Match when={currentScreen() === 'methodology'}><Methodology {...screenProps()} /></Match>
<Match when={currentScreen() === 'plan'}><Plan {...screenProps()} /></Match>
<Match when={currentScreen() === 'workflow'}><Workflow {...screenProps()} /></Match>
<Match when={currentScreen() === 'execute'}><Execute {...screenProps()} /></Match>
<Match when={currentScreen() === 'history'}><History {...screenProps()} /></Match>
<Match when={currentScreen() === 'sync'}><Sync {...screenProps()} /></Match>
<Match when={currentScreen() === 'help'}><Help {...screenProps()} /></Match>
<Match when={currentScreen() === 'mesh'}><Mesh {...screenProps()} /></Match>
<Match when={currentScreen() === 'message'}><Message {...screenProps()} /></Match>
</Switch>
</box>
</box>
<StatusBar />
</box>
</box>
</Show>
);
}
+47 -46
View File
@@ -1,36 +1,32 @@
/**
* AgentGrid Component
* Displays monochromatic agent logos in a grid layout
*/
import { Show, For, createMemo } from 'solid-js';
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;
export function AgentGrid(props: AgentGridProps) {
const maxVisible = () => props.maxVisible ?? 12;
const showStatus = () => props.showStatus ?? true;
const detectedAgents = () => props.detectedAgents ?? [];
const columns = () => Math.max(1, props.columns ?? 4);
const rows: [string, AgentLogo][][] = [];
for (let i = 0; i < visibleAgents.length; i += safeColumns) {
rows.push(visibleAgents.slice(i, i + safeColumns));
}
const allAgents = Object.entries(AGENT_LOGOS);
const visibleAgents = () => allAgents.slice(0, maxVisible());
const hiddenCount = () => allAgents.length - maxVisible();
const rows = createMemo((): [string, AgentLogo][][] => {
const result: [string, AgentLogo][][] = [];
const visible = visibleAgents();
for (let i = 0; i < visible.length; i += columns()) {
result.push(visible.slice(i, i + columns()));
}
return result;
});
return (
<box flexDirection="column">
@@ -38,31 +34,36 @@ export function AgentGrid({
<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;
<For each={rows()}>
{(row, rowIndex) => (
<box flexDirection="row">
<For each={row}>
{([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>
)}
return (
<box width={18}>
<text fg={fg()}>
{agent.icon} {agent.name}
<Show when={showStatus()}>
<span fg={isDetected() ? terminalColors.success : terminalColors.textMuted}>
{' '}
{statusIcon()}
</span>
</Show>
</text>
</box>
);
}}
</For>
</box>
)}
</For>
<Show when={hiddenCount() > 0}>
<text fg={terminalColors.textMuted}>+{hiddenCount()} more agents</text>
</Show>
</box>
);
}
@@ -0,0 +1,234 @@
/**
* AnimatedText Component
* Text with fade/slide animations
*/
import { Show, createSignal, createEffect, onCleanup } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
import { scrambleText } from '../theme/animations.js';
interface AnimatedTextProps {
text: string;
animation?: 'fadeIn' | 'typewriter' | 'scramble' | 'countUp' | 'none';
duration?: number;
delay?: number;
color?: string;
onComplete?: () => void;
}
export function AnimatedText(props: AnimatedTextProps) {
const [progress, setProgress] = createSignal(0);
const [isComplete, setIsComplete] = createSignal(false);
const animation = () => props.animation ?? 'fadeIn';
const duration = () => Math.max(1, props.duration ?? 500);
const delay = () => Math.max(0, props.delay ?? 0);
const color = () => props.color ?? terminalColors.text;
createEffect(() => {
const anim = animation();
const dur = duration();
const dly = delay();
setProgress(0);
setIsComplete(false);
if (anim === 'none') {
setProgress(100);
setIsComplete(true);
return;
}
let delayTimeoutId: ReturnType<typeof setTimeout> | undefined;
let animationTimeoutId: ReturnType<typeof setTimeout> | undefined;
let startTime: number | undefined;
let cancelled = false;
const animate = () => {
if (cancelled) return;
const now = Date.now();
if (!startTime) startTime = now;
const elapsed = now - startTime;
const p = Math.min((elapsed / dur) * 100, 100);
setProgress(p);
if (p < 100) {
animationTimeoutId = setTimeout(animate, 16);
} else {
setIsComplete(true);
props.onComplete?.();
}
};
if (dly > 0) {
delayTimeoutId = setTimeout(() => {
animationTimeoutId = setTimeout(animate, 16);
}, dly);
} else {
animationTimeoutId = setTimeout(animate, 16);
}
onCleanup(() => {
cancelled = true;
if (delayTimeoutId) clearTimeout(delayTimeoutId);
if (animationTimeoutId) clearTimeout(animationTimeoutId);
});
});
const displayText = () => {
switch (animation()) {
case 'typewriter': {
const charCount = Math.floor((progress() / 100) * props.text.length);
return props.text.slice(0, charCount);
}
case 'scramble': {
return scrambleText(props.text, progress());
}
case 'countUp': {
const num = parseFloat(props.text);
if (!isNaN(num)) {
return String(Math.round((progress() / 100) * num));
}
return props.text;
}
case 'fadeIn':
case 'none':
default:
return props.text;
}
};
return (
<text fg={color()}>
{displayText()}
<Show when={animation() === 'typewriter' && !isComplete()}>
<text fg={terminalColors.accent}>▌</text>
</Show>
</text>
);
}
interface CountUpTextProps {
value: number;
duration?: number;
delay?: number;
prefix?: string;
suffix?: string;
color?: string;
formatter?: (value: number) => string;
}
export function CountUpText(props: CountUpTextProps) {
const [displayValue, setDisplayValue] = createSignal(0);
const duration = () => Math.max(1, props.duration ?? 1000);
const delay = () => Math.max(0, props.delay ?? 0);
const color = () => props.color ?? terminalColors.text;
const formatter = () => props.formatter ?? ((v: number) => String(Math.round(v)));
createEffect(() => {
const target = props.value;
const dur = duration();
const dly = delay();
setDisplayValue(0);
let delayTimeoutId: ReturnType<typeof setTimeout> | undefined;
let animationTimeoutId: ReturnType<typeof setTimeout> | undefined;
let startTime: number | undefined;
let cancelled = false;
const animate = () => {
if (cancelled) return;
const now = Date.now();
if (!startTime) startTime = now;
const elapsed = now - startTime;
const progress = Math.min(elapsed / dur, 1);
const eased = 1 - Math.pow(1 - progress, 4);
setDisplayValue(eased * target);
if (progress < 1) {
animationTimeoutId = setTimeout(animate, 16);
}
};
if (dly > 0) {
delayTimeoutId = setTimeout(() => {
animationTimeoutId = setTimeout(animate, 16);
}, dly);
} else {
animationTimeoutId = setTimeout(animate, 16);
}
onCleanup(() => {
cancelled = true;
if (delayTimeoutId) clearTimeout(delayTimeoutId);
if (animationTimeoutId) clearTimeout(animationTimeoutId);
});
});
return (
<text fg={color()}>
{props.prefix ?? ''}
{formatter()(displayValue())}
{props.suffix ?? ''}
</text>
);
}
interface BlinkingTextProps {
text: string;
interval?: number;
color?: string;
blinkColor?: string;
}
export function BlinkingText(props: BlinkingTextProps) {
const [visible, setVisible] = createSignal(true);
const interval = () => props.interval ?? 500;
const color = () => props.color ?? terminalColors.text;
const blinkColor = () => props.blinkColor ?? terminalColors.textMuted;
createEffect(() => {
const timer = setInterval(() => {
setVisible((v) => !v);
}, interval());
onCleanup(() => clearInterval(timer));
});
return <text fg={visible() ? color() : blinkColor()}>{props.text}</text>;
}
interface PulsingTextProps {
text: string;
color?: string;
pulseColor?: string;
interval?: number;
}
export function PulsingText(props: PulsingTextProps) {
const [phase, setPhase] = createSignal(0);
const interval = () => props.interval ?? 100;
const color = () => props.color ?? terminalColors.accent;
const pulseColor = () => props.pulseColor ?? terminalColors.text;
createEffect(() => {
const timer = setInterval(() => {
setPhase((p) => (p + 1) % 20);
}, interval());
onCleanup(() => clearInterval(timer));
});
const currentColor = () => {
const p = phase();
if (p < 10) return color();
return pulseColor();
};
return <text fg={currentColor()}>{props.text}</text>;
}
@@ -0,0 +1,55 @@
import { type Screen } from '../state/types.js';
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
import { getVersion } from '../utils/helpers.js';
interface BottomStatusBarProps {
currentScreen: Screen;
}
const SCREEN_LABELS: Record<Screen, string> = {
home: 'Home',
browse: 'Browse',
marketplace: 'Marketplace',
installed: 'Installed',
settings: 'Settings',
recommend: 'Recommend',
translate: 'Translate',
context: 'Context',
memory: 'Memory',
team: 'Team',
plugins: 'Plugins',
methodology: 'Methodology',
plan: 'Plan',
workflow: 'Workflow',
execute: 'Execute',
history: 'History',
sync: 'Sync',
help: 'Help',
mesh: 'Mesh',
message: 'Message',
};
export function BottomStatusBar(props: BottomStatusBarProps) {
const version = getVersion();
return (
<box
flexDirection="row"
height={1}
borderTop
borderColor={terminalColors.border}
paddingX={1}
>
<text fg={terminalColors.accent}>
<b>{symbols.brandIcon} skillkit</b> v{version}
</text>
<text fg={terminalColors.border}> {symbols.verticalLine} </text>
<text fg={terminalColors.text}>
<b>{SCREEN_LABELS[props.currentScreen]}</b>
</text>
<text fg={terminalColors.border}> {symbols.verticalLine} </text>
<text fg={terminalColors.textMuted}>/ cmd h home m market q quit</text>
</box>
);
}
+179
View File
@@ -0,0 +1,179 @@
/**
* Breadcrumb Component
* Clickable breadcrumb navigation
*/
import { For, Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
export interface BreadcrumbItem {
id: string;
label: string;
icon?: string;
}
interface BreadcrumbProps {
items: BreadcrumbItem[];
separator?: string;
hoveredId?: string | null;
onNavigate?: (id: string) => void;
}
export function Breadcrumb(props: BreadcrumbProps) {
const separator = () => props.separator ?? ' / ';
const handleClick = (id: string) => {
props.onNavigate?.(id);
};
return (
<box flexDirection="row">
<For each={props.items}>
{(item, index) => {
const isLast = () => index() === props.items.length - 1;
const isHovered = () => item.id === props.hoveredId;
const fg = () => {
if (isLast()) return terminalColors.text;
if (isHovered()) return terminalColors.accent;
return terminalColors.textMuted;
};
return (
<>
<box
flexDirection="row"
onClick={() => handleClick(item.id)}
>
<Show when={item.icon}>
<text fg={fg()}>{item.icon} </text>
</Show>
<text fg={fg()}>
{isLast() ? <b>{item.label}</b> : item.label}
</text>
</box>
<Show when={!isLast()}>
<text fg={terminalColors.textMuted}>{separator()}</text>
</Show>
</>
);
}}
</For>
</box>
);
}
interface PathBreadcrumbProps {
path: string;
separator?: string;
maxSegments?: number;
hoveredSegment?: number | null;
onNavigate?: (path: string, segmentIndex: number) => void;
}
export function PathBreadcrumb(props: PathBreadcrumbProps) {
const separator = () => props.separator ?? '/';
const maxSegments = () => props.maxSegments ?? 5;
const segments = () => {
const parts = props.path.split('/').filter(Boolean);
if (parts.length <= maxSegments()) {
return parts;
}
return ['...', ...parts.slice(-(maxSegments() - 1))];
};
const getPathAtIndex = (index: number): string => {
const parts = props.path.split('/').filter(Boolean);
const segs = segments();
let actualIndex: number;
if (segs[0] === '...') {
const offset = parts.length - (segs.length - 1);
actualIndex = offset + index - 1;
} else {
actualIndex = index;
}
return '/' + parts.slice(0, actualIndex + 1).join('/');
};
const handleClick = (segment: string, index: number) => {
if (segment === '...') return;
props.onNavigate?.(getPathAtIndex(index), index);
};
return (
<box flexDirection="row">
<text fg={terminalColors.textMuted}>{separator()}</text>
<For each={segments()}>
{(segment, index) => {
const isLast = () => index() === segments().length - 1;
const isHovered = () => index() === props.hoveredSegment;
const isEllipsis = () => segment === '...';
const fg = () => {
if (isEllipsis()) return terminalColors.textMuted;
if (isLast()) return terminalColors.text;
if (isHovered()) return terminalColors.accent;
return terminalColors.textMuted;
};
return (
<>
<text
fg={fg()}
onClick={() => handleClick(segment, index())}
>
{isLast() ? <b>{segment}</b> : segment}
</text>
<Show when={!isLast()}>
<text fg={terminalColors.textMuted}>{separator()}</text>
</Show>
</>
);
}}
</For>
</box>
);
}
interface NavigationTrailProps {
items: Array<{ screen: string; label: string }>;
currentIndex: number;
hoveredIndex?: number | null;
}
export function NavigationTrail(props: NavigationTrailProps) {
return (
<box flexDirection="row">
<For each={props.items}>
{(item, index) => {
const isCurrent = () => index() === props.currentIndex;
const isPast = () => index() < props.currentIndex;
const isHovered = () => index() === props.hoveredIndex;
const fg = () => {
if (isCurrent()) return terminalColors.accent;
if (isHovered()) return terminalColors.text;
if (isPast()) return terminalColors.textSecondary;
return terminalColors.textMuted;
};
const indicator = () => {
if (isCurrent()) return '●';
if (isPast()) return '○';
return '○';
};
return (
<box flexDirection="row" marginRight={2}>
<text fg={fg()}>{indicator()} </text>
<text fg={fg()}>{item.label}</text>
</box>
);
}}
</For>
</box>
);
}
+197
View File
@@ -0,0 +1,197 @@
/**
* Button Component
* Clickable button with hover/active states
*/
import { Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
export type ButtonVariant = 'primary' | 'secondary' | 'ghost' | 'danger';
export type ButtonSize = 'sm' | 'md' | 'lg';
interface ButtonProps {
label: string;
shortcut?: string;
icon?: string;
variant?: ButtonVariant;
size?: ButtonSize;
disabled?: boolean;
focused?: boolean;
pressed?: boolean;
hovered?: boolean;
onClick?: () => void;
}
const VARIANT_COLORS: Record<
ButtonVariant,
{ fg: string; bg: string; border: string; hoverFg: string }
> = {
primary: {
fg: terminalColors.text,
bg: terminalColors.accent,
border: terminalColors.accent,
hoverFg: terminalColors.accent,
},
secondary: {
fg: terminalColors.text,
bg: terminalColors.surface,
border: terminalColors.border,
hoverFg: terminalColors.text,
},
ghost: {
fg: terminalColors.textSecondary,
bg: 'transparent',
border: 'transparent',
hoverFg: terminalColors.text,
},
danger: {
fg: terminalColors.text,
bg: terminalColors.error,
border: terminalColors.error,
hoverFg: terminalColors.error,
},
};
export function Button(props: ButtonProps) {
const variant = () => props.variant ?? 'secondary';
const size = () => props.size ?? 'md';
const disabled = () => props.disabled ?? false;
const focused = () => props.focused ?? false;
const pressed = () => props.pressed ?? false;
const hovered = () => props.hovered ?? false;
const colors = () => VARIANT_COLORS[variant()];
const fg = () => {
if (disabled()) return terminalColors.textMuted;
if (pressed()) return colors().hoverFg;
if (hovered() || focused()) return colors().hoverFg;
return colors().fg;
};
const borderColor = () => {
if (disabled()) return terminalColors.textMuted;
if (focused()) return terminalColors.accent;
return colors().border;
};
const paddingX = () => {
switch (size()) {
case 'sm':
return 1;
case 'lg':
return 3;
default:
return 2;
}
};
const brackets = () => {
if (variant() === 'ghost') return { left: '', right: '' };
if (pressed()) return { left: '▸', right: '◂' };
return { left: '[', right: ']' };
};
const padding = ' '.repeat(paddingX());
const handleClick = () => {
if (!disabled() && props.onClick) {
props.onClick();
}
};
return (
<box flexDirection="row" onClick={handleClick}>
<text fg={borderColor()}>{brackets().left}</text>
<text fg={fg()}>{padding}</text>
<Show when={props.icon}>
<text fg={fg()}>{props.icon} </text>
</Show>
<text fg={fg()}>{props.label}</text>
<Show when={props.shortcut}>
<text fg={terminalColors.textMuted}> ({props.shortcut})</text>
</Show>
<text fg={fg()}>{padding}</text>
<text fg={borderColor()}>{brackets().right}</text>
</box>
);
}
interface ButtonGroupProps {
buttons: Array<{
id: string;
label: string;
shortcut?: string;
icon?: string;
variant?: ButtonVariant;
disabled?: boolean;
onClick?: () => void;
}>;
selectedId?: string;
focusedId?: string;
direction?: 'horizontal' | 'vertical';
gap?: number;
}
export function ButtonGroup(props: ButtonGroupProps) {
const direction = () => props.direction ?? 'horizontal';
const gap = () => props.gap ?? 2;
return (
<box flexDirection={direction() === 'horizontal' ? 'row' : 'column'}>
{props.buttons.map((btn, index) => (
<box
marginRight={direction() === 'horizontal' && index < props.buttons.length - 1 ? gap() : 0}
marginBottom={direction() === 'vertical' && index < props.buttons.length - 1 ? gap() : 0}
>
<Button
label={btn.label}
shortcut={btn.shortcut}
icon={btn.icon}
variant={btn.variant}
disabled={btn.disabled}
focused={btn.id === props.focusedId}
hovered={btn.id === props.selectedId}
onClick={btn.onClick}
/>
</box>
))}
</box>
);
}
interface IconButtonProps {
icon: string;
label?: string;
disabled?: boolean;
focused?: boolean;
hovered?: boolean;
onClick?: () => void;
}
export function IconButton(props: IconButtonProps) {
const disabled = () => props.disabled ?? false;
const focused = () => props.focused ?? false;
const hovered = () => props.hovered ?? false;
const fg = () => {
if (disabled()) return terminalColors.textMuted;
if (focused() || hovered()) return terminalColors.accent;
return terminalColors.textSecondary;
};
const handleClick = () => {
if (!disabled() && props.onClick) {
props.onClick();
}
};
return (
<box flexDirection="row" onClick={handleClick}>
<text fg={fg()}>{props.icon}</text>
<Show when={props.label}>
<text fg={fg()}> {props.label}</text>
</Show>
</box>
);
}
+196
View File
@@ -0,0 +1,196 @@
/**
* Clickable Component
* Wrapper to make any element clickable with hover effects
*/
import { type JSX, Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
interface ClickableProps {
children: JSX.Element;
onClick?: () => void;
onDoubleClick?: () => void;
onRightClick?: () => void;
disabled?: boolean;
hovered?: boolean;
pressed?: boolean;
focusable?: boolean;
focused?: boolean;
cursor?: string;
hoverEffect?: 'highlight' | 'underline' | 'pointer' | 'none';
}
export function Clickable(props: ClickableProps) {
const disabled = () => props.disabled ?? false;
const hovered = () => props.hovered ?? false;
const focused = () => props.focused ?? false;
const hoverEffect = () => props.hoverEffect ?? 'highlight';
const showHighlight = () => {
if (disabled()) return false;
return hovered() || focused();
};
const cursor = () => {
if (disabled()) return '';
if (hovered()) return props.cursor ?? '▸';
return '';
};
const handleClick = () => {
if (!disabled() && props.onClick) {
props.onClick();
}
};
const handleDoubleClick = () => {
if (!disabled() && props.onDoubleClick) {
props.onDoubleClick();
}
};
const handleRightClick = () => {
if (!disabled() && props.onRightClick) {
props.onRightClick();
}
};
const renderContent = () => {
if (hoverEffect() === 'underline' && showHighlight()) {
return <text>{props.children}</text>;
}
return props.children;
};
return (
<box
flexDirection="row"
onClick={handleClick}
onDoubleClick={handleDoubleClick}
onContextMenu={handleRightClick}
>
<Show when={hoverEffect() === 'pointer' && showHighlight()}>
<text fg={terminalColors.accent}>{cursor()} </text>
</Show>
<box
fg={hoverEffect() === 'highlight' && showHighlight() ? terminalColors.accent : undefined}
>
{renderContent()}
</box>
</box>
);
}
interface ClickableTextProps {
children: string;
onClick?: () => void;
disabled?: boolean;
hovered?: boolean;
color?: string;
hoverColor?: string;
underlineOnHover?: boolean;
}
export function ClickableText(props: ClickableTextProps) {
const disabled = () => props.disabled ?? false;
const hovered = () => props.hovered ?? false;
const underlineOnHover = () => props.underlineOnHover ?? false;
const color = () => {
if (disabled()) return terminalColors.textMuted;
if (hovered()) return props.hoverColor ?? terminalColors.accent;
return props.color ?? terminalColors.text;
};
const handleClick = () => {
if (!disabled() && props.onClick) {
props.onClick();
}
};
return (
<text fg={color()} onClick={handleClick}>
{underlineOnHover() && hovered() ? (
<u>{props.children}</u>
) : (
props.children
)}
</text>
);
}
interface ClickableRowProps {
children: JSX.Element;
selected?: boolean;
hovered?: boolean;
disabled?: boolean;
showIndicator?: boolean;
indicatorChar?: string;
onClick?: () => void;
}
export function ClickableRow(props: ClickableRowProps) {
const selected = () => props.selected ?? false;
const hovered = () => props.hovered ?? false;
const disabled = () => props.disabled ?? false;
const showIndicator = () => props.showIndicator ?? true;
const indicatorChar = () => props.indicatorChar ?? '▸';
const indicator = () => {
if (!showIndicator()) return ' ';
if (selected()) return `${indicatorChar()} `;
if (hovered()) return '▹ ';
return ' ';
};
const fg = () => {
if (disabled()) return terminalColors.textMuted;
if (selected()) return terminalColors.accent;
if (hovered()) return terminalColors.text;
return terminalColors.textSecondary;
};
const handleClick = () => {
if (!disabled() && props.onClick) {
props.onClick();
}
};
return (
<box flexDirection="row" onClick={handleClick}>
<text fg={fg()}>{indicator()}</text>
{props.children}
</box>
);
}
interface InteractiveAreaProps {
children: JSX.Element;
x?: number;
y?: number;
width?: number;
height?: number;
onMouseOver?: () => void;
onMouseOut?: () => void;
onClick?: () => void;
onMouseDown?: () => void;
onMouseUp?: () => void;
}
export function InteractiveArea(props: InteractiveAreaProps) {
return (
<box
flexDirection="column"
width={props.width}
height={props.height}
style={{ left: props.x, top: props.y }}
onMouseEnter={props.onMouseOver}
onMouseLeave={props.onMouseOut}
onClick={props.onClick}
onMouseDown={props.onMouseDown}
onMouseUp={props.onMouseUp}
>
{props.children}
</box>
);
}
+194
View File
@@ -0,0 +1,194 @@
/**
* CodeBlock Component
* Basic syntax highlighting for code display
*/
import { For, Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
interface CodeBlockProps {
code: string;
language?: string;
showLineNumbers?: boolean;
maxLines?: number;
highlightLines?: number[];
title?: string;
}
const KEYWORDS = new Set([
'const',
'let',
'var',
'function',
'return',
'if',
'else',
'for',
'while',
'import',
'export',
'from',
'class',
'extends',
'async',
'await',
'try',
'catch',
'throw',
'new',
'this',
'true',
'false',
'null',
'undefined',
'type',
'interface',
]);
function tokenizeLine(line: string): Array<{ type: string; value: string }> {
const tokens: Array<{ type: string; value: string }> = [];
let remaining = line;
while (remaining.length > 0) {
if (remaining.startsWith('//')) {
tokens.push({ type: 'comment', value: remaining });
break;
}
const stringMatch = remaining.match(/^(['"`])(?:\\.|[^\\])*?\1/);
if (stringMatch) {
tokens.push({ type: 'string', value: stringMatch[0] });
remaining = remaining.slice(stringMatch[0].length);
continue;
}
const numberMatch = remaining.match(/^\d+\.?\d*/);
if (numberMatch) {
tokens.push({ type: 'number', value: numberMatch[0] });
remaining = remaining.slice(numberMatch[0].length);
continue;
}
const wordMatch = remaining.match(/^[a-zA-Z_$][a-zA-Z0-9_$]*/);
if (wordMatch) {
const word = wordMatch[0];
const type = KEYWORDS.has(word) ? 'keyword' : 'identifier';
tokens.push({ type, value: word });
remaining = remaining.slice(word.length);
continue;
}
const spaceMatch = remaining.match(/^\s+/);
if (spaceMatch) {
tokens.push({ type: 'space', value: spaceMatch[0] });
remaining = remaining.slice(spaceMatch[0].length);
continue;
}
tokens.push({ type: 'punctuation', value: remaining[0] });
remaining = remaining.slice(1);
}
return tokens;
}
function getTokenColor(type: string): string {
switch (type) {
case 'keyword':
return terminalColors.accent;
case 'string':
return terminalColors.warning;
case 'number':
return terminalColors.info;
case 'comment':
return terminalColors.textMuted;
default:
return terminalColors.text;
}
}
export function CodeBlock(props: CodeBlockProps) {
const showLineNumbers = () => props.showLineNumbers ?? true;
const highlightLines = () => new Set(props.highlightLines ?? []);
const lines = () => {
const allLines = props.code.split('\n');
if (props.maxLines && allLines.length > props.maxLines) {
return allLines.slice(0, props.maxLines);
}
return allLines;
};
const lineNumberWidth = () => String(lines().length).length + 1;
const isTruncated = () => {
const allLines = props.code.split('\n');
return props.maxLines !== undefined && allLines.length > props.maxLines;
};
return (
<box flexDirection="column">
<Show when={props.title}>
<box marginBottom={1}>
<text fg={terminalColors.textMuted}>
{props.title}
</text>
</box>
</Show>
<box
flexDirection="column"
borderStyle="round"
borderColor={terminalColors.border}
paddingX={1}
>
<For each={lines()}>
{(line, index) => {
const lineNum = index() + 1;
const isHighlighted = highlightLines().has(lineNum);
const tokens = tokenizeLine(line);
return (
<box flexDirection="row">
<Show when={showLineNumbers()}>
<text
fg={isHighlighted ? terminalColors.accent : terminalColors.textMuted}
width={lineNumberWidth()}
>
{isHighlighted ? '▸' : ' '}
{String(lineNum).padStart(lineNumberWidth() - 1, ' ')}{' '}
</text>
</Show>
<For each={tokens}>
{(token) => (
<text fg={isHighlighted ? terminalColors.accent : getTokenColor(token.type)}>
{token.value}
</text>
)}
</For>
</box>
);
}}
</For>
<Show when={isTruncated()}>
<text fg={terminalColors.textMuted}>
... {props.code.split('\n').length - (props.maxLines ?? 0)} more lines
</text>
</Show>
</box>
</box>
);
}
interface InlineCodeProps {
children: string;
}
export function InlineCode(props: InlineCodeProps) {
return (
<text fg={terminalColors.accent}>
`{props.children}`
</text>
);
}
+135
View File
@@ -0,0 +1,135 @@
/**
* DetailPane Component
* Right-side detail panel with animated slide-in
*/
import { Show, For, createSignal, createEffect, onCleanup, type JSX } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
export interface DetailField {
label: string;
value: string | string[];
color?: string;
}
interface DetailPaneProps {
title: string;
subtitle?: string;
icon?: string;
fields?: DetailField[];
content?: string;
actions?: Array<{ key: string; label: string }>;
width?: number;
visible?: boolean;
onClose?: () => void;
children?: JSX.Element;
}
export function DetailPane(props: DetailPaneProps) {
const [slideProgress, setSlideProgress] = createSignal(0);
const width = () => props.width ?? 30;
const visible = () => props.visible ?? true;
createEffect(() => {
if (visible()) {
let frame = 0;
let timeoutId: ReturnType<typeof setTimeout>;
const animate = () => {
frame++;
const progress = Math.min(frame / 10, 1);
setSlideProgress(progress);
if (progress < 1) {
timeoutId = setTimeout(animate, 16);
}
};
timeoutId = setTimeout(animate, 16);
onCleanup(() => clearTimeout(timeoutId));
} else {
setSlideProgress(0);
}
});
const effectiveWidth = () => Math.round(width() * slideProgress());
return (
<Show when={visible() && slideProgress() > 0}>
<box
flexDirection="column"
width={effectiveWidth()}
borderStyle="round"
borderColor={terminalColors.border}
paddingX={1}
paddingY={1}
>
<box flexDirection="row" marginBottom={1}>
<Show when={props.icon}>
<text fg={terminalColors.accent}>{props.icon} </text>
</Show>
<text fg={terminalColors.text}>
<b>{props.title}</b>
</text>
<Show when={props.onClose}>
<box onClick={() => props.onClose?.()}>
<text fg={terminalColors.textMuted}> [x]</text>
</box>
</Show>
</box>
<Show when={props.subtitle}>
<box marginBottom={1}>
<text fg={terminalColors.textMuted}>{props.subtitle}</text>
</box>
</Show>
<Show when={props.fields && props.fields.length > 0}>
<box flexDirection="column" marginBottom={1}>
<For each={props.fields}>
{(field) => (
<box flexDirection="column" marginBottom={1}>
<text fg={terminalColors.textMuted}>{field.label}</text>
<Show
when={Array.isArray(field.value)}
fallback={
<text fg={field.color || terminalColors.text}>
{field.value as string}
</text>
}
>
<For each={field.value as string[]}>
{(val) => (
<text fg={field.color || terminalColors.text}>• {val}</text>
)}
</For>
</Show>
</box>
)}
</For>
</box>
</Show>
<Show when={props.content}>
<box flexDirection="column" marginBottom={1}>
<text fg={terminalColors.text}>{props.content}</text>
</box>
</Show>
<Show when={props.children}>
<box flexDirection="column" marginBottom={1}>
{props.children}
</box>
</Show>
<Show when={props.actions && props.actions.length > 0}>
<text fg={terminalColors.textMuted}>─────</text>
<For each={props.actions}>
{(action) => (
<text fg={terminalColors.textMuted}>
<text fg={terminalColors.accent}>{action.key}</text> {action.label}
</text>
)}
</For>
</Show>
</box>
</Show>
);
}
+109
View File
@@ -0,0 +1,109 @@
/**
* EmptyState Component
* Consistent "no data" display
*/
import { Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
interface EmptyStateProps {
icon?: string;
title: string;
description?: string;
action?: {
label: string;
key?: string;
};
compact?: boolean;
}
export function EmptyState(props: EmptyStateProps) {
const compact = () => props.compact ?? false;
return (
<box flexDirection="column" alignItems="center" paddingY={compact() ? 1 : 3}>
<Show when={props.icon}>
<box marginBottom={1}>
<text fg={terminalColors.textMuted}>
{props.icon}
</text>
</box>
</Show>
<box marginBottom={1}>
<text fg={terminalColors.textSecondary}>
{props.title}
</text>
</box>
<Show when={props.description}>
<text fg={terminalColors.textMuted}>{props.description}</text>
</Show>
<Show when={props.action}>
<box marginTop={1}>
<text fg={terminalColors.textMuted}>
<Show when={props.action!.key}>
<text fg={terminalColors.accent}>{props.action!.key}</text>{' '}
</Show>
{props.action!.label}
</text>
</box>
</Show>
</box>
);
}
interface LoadingStateProps {
message?: string;
compact?: boolean;
}
export function LoadingState(props: LoadingStateProps) {
const compact = () => props.compact ?? false;
const message = () => props.message ?? 'Loading...';
return (
<box flexDirection="column" alignItems="center" paddingY={compact() ? 1 : 3}>
<text fg={terminalColors.accent}>⟳ {message()}</text>
</box>
);
}
interface ErrorStateProps {
title?: string;
message: string;
action?: {
label: string;
key?: string;
};
compact?: boolean;
}
export function ErrorState(props: ErrorStateProps) {
const compact = () => props.compact ?? false;
const title = () => props.title ?? 'Error';
return (
<box flexDirection="column" alignItems="center" paddingY={compact() ? 1 : 3}>
<box marginBottom={1}>
<text fg={terminalColors.error}>
✗ {title()}
</text>
</box>
<text fg={terminalColors.textMuted}>{props.message}</text>
<Show when={props.action}>
<box marginTop={1}>
<text fg={terminalColors.textMuted}>
<Show when={props.action!.key}>
<text fg={terminalColors.accent}>{props.action!.key}</text>{' '}
</Show>
{props.action!.label}
</text>
</box>
</Show>
</box>
);
}
@@ -0,0 +1,121 @@
/**
* ErrorBoundary Component
* Catch and display errors gracefully
*/
import { ErrorBoundary as SolidErrorBoundary, type JSX, Show } from 'solid-js';
import { useKeyboard } from '@opentui/solid';
import { terminalColors } from '../theme/colors.js';
interface ErrorBoundaryProps {
children: JSX.Element;
fallback?: JSX.Element | ((error: Error, reset: () => void) => JSX.Element);
onError?: (error: Error) => void;
}
function DefaultErrorFallback(props: { error: Error; reset: () => void }) {
const errorMessage = () => {
if (props.error instanceof Error) {
return props.error.message;
}
return String(props.error);
};
const errorStack = () => {
if (props.error instanceof Error && props.error.stack) {
const lines = props.error.stack.split('\n').slice(1, 4);
return lines.join('\n');
}
return '';
};
useKeyboard((key) => {
if (key.name === 'r') {
props.reset();
}
});
return (
<box flexDirection="column" paddingY={2} paddingX={1}>
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.error}>✗ Something went wrong</text>
</box>
<box
flexDirection="column"
borderStyle="round"
borderColor={terminalColors.error}
paddingX={1}
paddingY={1}
>
<text fg={terminalColors.text}>{errorMessage()}</text>
<Show when={errorStack()}>
<box marginTop={1}>
<text fg={terminalColors.textMuted}>
{errorStack()}
</text>
</box>
</Show>
</box>
<box marginTop={1}>
<text fg={terminalColors.textMuted}>
Press <text fg={terminalColors.accent}>r</text> to retry or{' '}
<text fg={terminalColors.accent}>Esc</text> to go back
</text>
</box>
</box>
);
}
export function ErrorBoundary(props: ErrorBoundaryProps) {
let handledErrorRef: Error | null = null;
const fallbackComponent = (error: Error, reset: () => void) => {
if (props.onError && handledErrorRef !== error) {
handledErrorRef = error;
props.onError(error);
}
const wrappedReset = () => {
handledErrorRef = null;
reset();
};
if (typeof props.fallback === 'function') {
return props.fallback(error, wrappedReset);
}
if (props.fallback) {
return props.fallback;
}
return <DefaultErrorFallback error={error} reset={wrappedReset} />;
};
return (
<SolidErrorBoundary fallback={fallbackComponent}>
{props.children}
</SolidErrorBoundary>
);
}
interface TryProps {
children: JSX.Element;
catch?: JSX.Element;
}
export function Try(props: TryProps) {
return (
<ErrorBoundary
fallback={
props.catch ?? (
<text fg={terminalColors.error}>Error loading component</text>
)
}
>
{props.children}
</ErrorBoundary>
);
}
+17 -14
View File
@@ -1,7 +1,4 @@
/**
* FeatureList Component
* Colored feature keywords with descriptions
*/
import { For } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
interface Feature {
@@ -24,19 +21,25 @@ interface FeatureListProps {
features?: Feature[];
}
export function FeatureList({ features = FEATURES }: FeatureListProps) {
export function FeatureList(props: FeatureListProps) {
const features = () => props.features ?? FEATURES;
return (
<box flexDirection="column">
<text fg={terminalColors.text}><b>Features</b></text>
<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>
))}
<For each={features()}>
{(feat) => (
<box flexDirection="row">
<text fg={terminalColors[feat.color]}>
<b>{' '}{feat.label.padEnd(12)}</b>
</text>
<text fg={terminalColors.textMuted}>{feat.description}</text>
</box>
)}
</For>
</box>
);
}
+204
View File
@@ -0,0 +1,204 @@
/**
* FormField Component
* Input with label and validation
*/
import { Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
interface FormFieldProps {
label: string;
value: string;
placeholder?: string;
error?: string;
hint?: string;
required?: boolean;
disabled?: boolean;
focused?: boolean;
type?: 'text' | 'password' | 'search';
width?: number;
}
export function FormField(props: FormFieldProps) {
const type = () => props.type ?? 'text';
const focused = () => props.focused ?? false;
const disabled = () => props.disabled ?? false;
const width = () => props.width ?? 30;
const displayValue = () => {
if (type() === 'password') {
return '•'.repeat(props.value.length);
}
return props.value;
};
const borderColor = () => {
if (props.error) return terminalColors.error;
if (focused()) return terminalColors.accent;
if (disabled()) return terminalColors.textMuted;
return terminalColors.border;
};
const labelColor = () => {
if (props.error) return terminalColors.error;
if (focused()) return terminalColors.accent;
return terminalColors.textSecondary;
};
return (
<box flexDirection="column" marginBottom={1}>
<box flexDirection="row">
<text fg={labelColor()}>
{props.label}
<Show when={props.required}>
<text fg={terminalColors.error}>*</text>
</Show>
</text>
</box>
<box
flexDirection="row"
width={width()}
borderStyle="round"
borderColor={borderColor()}
paddingX={1}
>
<Show when={type() === 'search'}>
<text fg={terminalColors.textMuted}>/ </text>
</Show>
<text fg={disabled() ? terminalColors.textMuted : terminalColors.text}>
{displayValue() || (
<text fg={terminalColors.textMuted}>{props.placeholder ?? ''}</text>
)}
</text>
<Show when={focused()}>
<text fg={terminalColors.accent}>▌</text>
</Show>
</box>
<Show when={props.error}>
<text fg={terminalColors.error}>✗ {props.error}</text>
</Show>
<Show when={props.hint && !props.error}>
<text fg={terminalColors.textMuted}>{props.hint}</text>
</Show>
</box>
);
}
interface TextAreaFieldProps {
label: string;
value: string;
placeholder?: string;
error?: string;
rows?: number;
width?: number;
focused?: boolean;
}
export function TextAreaField(props: TextAreaFieldProps) {
const rows = () => props.rows ?? 3;
const width = () => props.width ?? 40;
const focused = () => props.focused ?? false;
const lines = () => props.value.split('\n').slice(0, rows());
const hasContent = () => props.value !== '' && props.value !== undefined;
const borderColor = () => {
if (props.error) return terminalColors.error;
if (focused()) return terminalColors.accent;
return terminalColors.border;
};
return (
<box flexDirection="column" marginBottom={1}>
<text fg={terminalColors.textSecondary}>{props.label}</text>
<box
flexDirection="column"
width={width()}
height={rows() + 2}
borderStyle="round"
borderColor={borderColor()}
paddingX={1}
>
<Show
when={hasContent()}
fallback={<text fg={terminalColors.textMuted}>{props.placeholder ?? ''}</text>}
>
{lines().map((line) => (
<text fg={terminalColors.text}>{line}</text>
))}
</Show>
</box>
<Show when={props.error}>
<text fg={terminalColors.error}>✗ {props.error}</text>
</Show>
</box>
);
}
interface SelectFieldProps {
label: string;
value: string;
options: Array<{ value: string; label: string }>;
focused?: boolean;
expanded?: boolean;
selectedOptionIndex?: number;
}
export function SelectField(props: SelectFieldProps) {
const focused = () => props.focused ?? false;
const expanded = () => props.expanded ?? false;
const selectedLabel = () => {
const option = props.options.find((o) => o.value === props.value);
return option?.label ?? props.value ?? 'Select...';
};
return (
<box flexDirection="column" marginBottom={1}>
<text fg={terminalColors.textSecondary}>{props.label}</text>
<box
flexDirection="row"
borderStyle="round"
borderColor={focused() ? terminalColors.accent : terminalColors.border}
paddingX={1}
>
<text fg={terminalColors.text}>{selectedLabel()}</text>
<text fg={terminalColors.textMuted}> {expanded() ? '▲' : '▼'}</text>
</box>
<Show when={expanded()}>
<box
flexDirection="column"
borderStyle="round"
borderColor={terminalColors.border}
paddingX={1}
>
{props.options.map((option, index) => {
const isSelected = index === props.selectedOptionIndex;
return (
<text
fg={
option.value === props.value
? terminalColors.accent
: isSelected
? terminalColors.text
: terminalColors.textSecondary
}
>
{isSelected ? '▸ ' : ' '}
{option.label}
</text>
);
})}
</box>
</Show>
</box>
);
}
+15 -16
View File
@@ -1,9 +1,5 @@
/**
* Header Component
* Screen header with title and optional badge/count
*/
import { Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
interface HeaderProps {
title: string;
@@ -13,23 +9,26 @@ interface HeaderProps {
icon?: string;
}
export function Header({ title, subtitle, count, badge, icon }: HeaderProps) {
export function Header(props: HeaderProps) {
return (
<box flexDirection="column" marginBottom={1}>
<box flexDirection="row" gap={2}>
<text fg={terminalColors.text}>
<b>{icon && `${icon} `}{title}</b>
<b>
{props.icon && `${props.icon} `}
{props.title}
</b>
</text>
{count !== undefined && (
<text fg={terminalColors.textMuted}>({count})</text>
)}
{badge && (
<text fg={terminalColors.accent}>[{badge}]</text>
)}
<Show when={props.count !== undefined}>
<text fg={terminalColors.textMuted}>({props.count})</text>
</Show>
<Show when={props.badge}>
<text fg={terminalColors.accent}>[{props.badge}]</text>
</Show>
</box>
{subtitle && (
<text fg={terminalColors.textSecondary}>{subtitle}</text>
)}
<Show when={props.subtitle}>
<text fg={terminalColors.textSecondary}>{props.subtitle}</text>
</Show>
</box>
);
}
@@ -0,0 +1,92 @@
/**
* HoverHighlight Component
* Hover highlight effect for list items and buttons
* Note: Terminal background colors are limited, so we use text color changes for highlighting
*/
import { type JSX, Show, createSignal, createEffect } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
interface HoverHighlightProps {
children: JSX.Element;
isHovered?: boolean;
isSelected?: boolean;
isDisabled?: boolean;
highlightColor?: string;
selectedColor?: string;
transitionMs?: number;
}
export function HoverHighlight(props: HoverHighlightProps) {
return <box>{props.children}</box>;
}
interface HighlightableListItemProps {
children: JSX.Element;
index: number;
selectedIndex?: number;
hoveredIndex?: number | null;
showPrefix?: boolean;
prefixWidth?: number;
}
export function HighlightableListItem(props: HighlightableListItemProps) {
const showPrefix = () => props.showPrefix ?? true;
const prefixWidth = () => props.prefixWidth ?? 3;
const isSelected = () => props.index === props.selectedIndex;
const isHovered = () => props.index === props.hoveredIndex;
const prefix = () => {
if (!showPrefix()) return '';
if (isSelected()) return '▸ ';
if (isHovered()) return '▹ ';
return ' ';
};
const fg = () => {
if (isSelected()) return terminalColors.accent;
if (isHovered()) return terminalColors.text;
return terminalColors.textSecondary;
};
return (
<box flexDirection="row">
<Show when={showPrefix()}>
<text fg={fg()} width={prefixWidth()}>
{prefix()}
</text>
</Show>
{props.children}
</box>
);
}
interface FocusRingProps {
children: JSX.Element;
isFocused?: boolean;
ringColor?: string;
}
export function FocusRing(props: FocusRingProps) {
const ringColor = () => props.ringColor ?? terminalColors.accent;
return (
<box
borderStyle={props.isFocused ? 'round' : undefined}
borderColor={props.isFocused ? ringColor() : undefined}
>
{props.children}
</box>
);
}
interface PressEffectProps {
children: JSX.Element;
isPressed?: boolean;
pressColor?: string;
}
export function PressEffect(props: PressEffectProps) {
return <box>{props.children}</box>;
}
+18 -23
View File
@@ -1,41 +1,36 @@
/**
* ProgressBar Component
* Animated progress bar display
*/
import { Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
interface ProgressBarProps {
progress: number; // 0-100
progress: number;
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;
export function ProgressBar(props: ProgressBarProps) {
const width = () => Math.max(1, Math.round(props.width ?? 20));
const safeProgress = () => (Number.isFinite(props.progress) ? props.progress : 0);
const showPercentage = () => props.showPercentage ?? true;
const color = () => props.color ?? 'accent';
const filled = symbols.progressFilled.repeat(filledWidth);
const empty = symbols.progressEmpty.repeat(emptyWidth);
const clampedProgress = () => Math.max(0, Math.min(100, safeProgress()));
const filledWidth = () => Math.round((clampedProgress() / 100) * width());
const emptyWidth = () => Math.max(0, 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>
<span fg={terminalColors[color()]}>{filled()}</span>
<span fg={terminalColors.textMuted}>{empty()}</span>
</text>
{showPercentage && (
<text fg={terminalColors.textSecondary}>
{Math.round(clampedProgress)}%
</text>
)}
<Show when={showPercentage()}>
<text fg={terminalColors.textSecondary}>{Math.round(clampedProgress())}%</text>
</Show>
</box>
);
}
@@ -0,0 +1,69 @@
import { Show, For, createSignal } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
import { symbols, AGENT_LOGOS } from '../theme/symbols.js';
interface RightSidebarProps {
width: number;
rows: number;
}
const TOP_AGENTS = ['claude-code', 'cursor', 'codex'] as const;
export function RightSidebar(props: RightSidebarProps) {
const [sections] = createSignal({
context: true,
agents: true,
tasks: false,
});
return (
<box
flexDirection="column"
width={props.width}
borderLeft
borderColor={terminalColors.border}
paddingLeft={1}
>
<box flexDirection="column" marginBottom={1}>
<text fg={terminalColors.text}>
{sections().context ? '▼' : '▸'} Context
</text>
<Show when={sections().context}>
<text fg={terminalColors.textSecondary}> Skills: 127</text>
<text fg={terminalColors.textSecondary}> Agents: 32 (3{symbols.active})</text>
<text fg={terminalColors.textSecondary}> Workflows: 4</text>
</Show>
</box>
<box flexDirection="column" marginBottom={1}>
<text fg={terminalColors.text}>
{sections().agents ? '▼' : '▸'} Agents (3)
</text>
<Show when={sections().agents}>
<For each={[...TOP_AGENTS]}>
{(agent) => {
const logo = AGENT_LOGOS[agent];
return (
<text fg={terminalColors.text}>
{' '}{logo.icon} {logo.name} {symbols.active}
</text>
);
}}
</For>
<text fg={terminalColors.textMuted}> +29 more</text>
</Show>
</box>
<box flexDirection="column" marginBottom={1}>
<text fg={terminalColors.text}>
{sections().tasks ? '▼' : '▸'} Tasks (2)
</text>
<Show when={sections().tasks}>
<text fg={terminalColors.textSecondary}> {symbols.pending} Syncing...</text>
</Show>
</box>
<box flexGrow={1} />
</box>
);
}
+10 -13
View File
@@ -1,7 +1,4 @@
/**
* SearchInput Component
* Rounded search input with icon
*/
import { Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
interface SearchInputProps {
@@ -11,19 +8,19 @@ interface SearchInputProps {
onChange?: (value: string) => void;
}
export function SearchInput({
value,
placeholder = 'Search...',
focused = false,
}: SearchInputProps) {
const display = value || placeholder;
const textColor = value ? terminalColors.text : terminalColors.textMuted;
export function SearchInput(props: SearchInputProps) {
const placeholder = () => props.placeholder ?? 'Search...';
const focused = () => props.focused ?? false;
const display = () => props.value || placeholder();
const textColor = () => (props.value ? terminalColors.text : terminalColors.textMuted);
return (
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted}>&#x2315; </text>
<text fg={textColor}>{display}</text>
{focused && <text fg={terminalColors.accent}>&#x258F;</text>}
<text fg={textColor()}>{display()}</text>
<Show when={focused()}>
<text fg={terminalColors.accent}>&#x258F;</text>
</Show>
</box>
);
}
+139
View File
@@ -0,0 +1,139 @@
/**
* SelectList Component
* Reusable list with j/k + mouse navigation
*/
import { For, Show, createMemo } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
export interface SelectListItem {
id: string;
label: string;
description?: string;
icon?: string;
meta?: string;
disabled?: boolean;
}
interface SelectListProps {
items: SelectListItem[];
selectedIndex: number;
hoveredIndex?: number | null;
onSelect?: (item: SelectListItem, index: number) => void;
onHover?: (index: number) => void;
maxVisible?: number;
showIndex?: boolean;
emptyText?: string;
compact?: boolean;
}
export function SelectList(props: SelectListProps) {
const maxVisible = () => props.maxVisible ?? 10;
const showIndex = () => props.showIndex ?? false;
const compact = () => props.compact ?? false;
const scrollOffset = createMemo(() => {
const selected = props.selectedIndex;
const visible = maxVisible();
const total = props.items.length;
if (total <= visible) return 0;
if (selected < visible / 2) return 0;
if (selected > total - visible / 2) return total - visible;
return Math.floor(selected - visible / 2);
});
const visibleItems = createMemo(() => {
const offset = scrollOffset();
return props.items.slice(offset, offset + maxVisible()).map((item, i) => ({
item,
originalIndex: offset + i,
}));
});
const hasScrollUp = createMemo(() => scrollOffset() > 0);
const hasScrollDown = createMemo(
() => scrollOffset() + maxVisible() < props.items.length
);
const handleItemClick = (item: SelectListItem, index: number) => {
if (!item.disabled && props.onSelect) {
props.onSelect(item, index);
}
};
const handleItemHover = (index: number) => {
if (props.onHover) {
props.onHover(index);
}
};
return (
<box flexDirection="column">
<Show when={props.items.length === 0}>
<text fg={terminalColors.textMuted}>{props.emptyText || 'No items'}</text>
</Show>
<Show when={hasScrollUp()}>
<text fg={terminalColors.textMuted}> ▲ {scrollOffset()} more</text>
</Show>
<For each={visibleItems()}>
{({ item, originalIndex }) => {
const isSelected = () => originalIndex === props.selectedIndex;
const isHovered = () => originalIndex === props.hoveredIndex;
const isDisabled = () => item.disabled ?? false;
const fg = () => {
if (isDisabled()) return terminalColors.textMuted;
if (isSelected()) return terminalColors.accent;
if (isHovered()) return terminalColors.text;
return terminalColors.textSecondary;
};
const prefix = () => {
if (isSelected()) return '▸ ';
if (isHovered()) return '▹ ';
return ' ';
};
return (
<box
flexDirection={compact() ? 'row' : 'column'}
marginBottom={compact() ? 0 : 1}
onClick={() => handleItemClick(item, originalIndex)}
onMouseEnter={() => handleItemHover(originalIndex)}
>
<box flexDirection="row">
<text fg={fg()}>{prefix()}</text>
<Show when={showIndex()}>
<text fg={terminalColors.textMuted} width={4}>
{String(originalIndex + 1).padStart(2, ' ')}.{' '}
</text>
</Show>
<Show when={item.icon}>
<text fg={fg()}>{item.icon} </text>
</Show>
<text fg={fg()}>{item.label}</text>
<Show when={item.meta}>
<text fg={terminalColors.textMuted}> ({item.meta})</text>
</Show>
</box>
<Show when={item.description && !compact()}>
<box marginLeft={2}>
<text fg={terminalColors.textMuted}>{item.description}</text>
</box>
</Show>
</box>
);
}}
</For>
<Show when={hasScrollDown()}>
<text fg={terminalColors.textMuted}>
{' '}▼ {props.items.length - scrollOffset() - maxVisible()} more
</text>
</Show>
</box>
);
}
+32 -17
View File
@@ -1,3 +1,4 @@
import { For, Show } from 'solid-js';
import { type Screen, SIDEBAR_NAV } from '../state/types.js';
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
@@ -8,7 +9,7 @@ interface SidebarProps {
onNavigate: (screen: Screen) => void;
}
export function Sidebar({ screen }: SidebarProps) {
export function Sidebar(props: SidebarProps) {
const version = getVersion();
return (
@@ -19,22 +20,36 @@ export function Sidebar({ screen }: SidebarProps) {
<text fg={terminalColors.textMuted}>v{version}</text>
<text> </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>
))}
<For each={SIDEBAR_NAV}>
{(nav, idx) => (
<box flexDirection="column">
<Show when={idx() > 0}>
<text> </text>
</Show>
<text fg={terminalColors.textMuted}>
<i>{nav.section}</i>
</text>
<For each={nav.items}>
{(item) => {
const active = () => props.screen === item.screen;
return (
<text fg={active() ? terminalColors.accent : terminalColors.text}>
{active() ? (
<b>
{symbols.pointer} {item.label}
</b>
) : (
<>
{symbols.pointerInactive} {item.label}
</>
)}
</text>
);
}}
</For>
</box>
)}
</For>
<box flexGrow={1} />
<text fg={terminalColors.textMuted}>{symbols.horizontalLine.repeat(14)}</text>
+36 -51
View File
@@ -1,10 +1,7 @@
/**
* SkillList Component
* Paginated list of skills with selection
*/
import { Show, For } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
import { calculatePagination, type PaginationResult } from '../utils/list.js';
import { calculatePagination } from '../utils/list.js';
import type { SkillItem } from '../state/types.js';
interface SkillListProps {
@@ -14,56 +11,44 @@ interface SkillListProps {
onSelect?: (skill: SkillItem) => void;
}
export function SkillList({
skills,
selectedIndex,
maxVisible = 10,
onSelect,
}: SkillListProps) {
if (skills.length === 0) {
return (
<text fg={terminalColors.textMuted}>No skills found</text>
);
}
export function SkillList(props: SkillListProps) {
const maxVisible = () => props.maxVisible ?? 10;
const pagination = calculatePagination(skills.length, selectedIndex, maxVisible);
const visibleSkills = skills.slice(pagination.start, pagination.end);
const pagination = () => calculatePagination(props.skills.length, props.selectedIndex, maxVisible());
const visibleSkills = () => props.skills.slice(pagination().start, pagination().end);
return (
<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 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 (
<text key={skill.name} fg={fg}>
{isSelected ? <b>{line}</b> : line}
<Show when={props.skills.length > 0} fallback={<text fg={terminalColors.textMuted}>No skills found</text>}>
<box flexDirection="column">
<Show when={pagination().itemsAbove > 0}>
<text fg={terminalColors.textMuted}>
{symbols.arrowUp} {pagination().itemsAbove} more above
</text>
);
})}
</Show>
{/* Items below indicator */}
{pagination.itemsBelow > 0 && (
<text fg={terminalColors.textMuted}>
{symbols.arrowDown} {pagination.itemsBelow} more below
</text>
)}
</box>
<For each={visibleSkills()}>
{(skill, idx) => {
const actualIndex = () => pagination().start + idx();
const isSelected = () => actualIndex() === props.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 ? '...' : ''}`
: '';
const line = () => `${pointer()} ${skill.name} ${statusIcon()}${descPart()}`;
return <text fg={fg()}>{isSelected() ? <b>{line()}</b> : line()}</text>;
}}
</For>
<Show when={pagination().itemsBelow > 0}>
<text fg={terminalColors.textMuted}>
{symbols.arrowDown} {pagination().itemsBelow} more below
</text>
</Show>
</box>
</Show>
);
}
+12 -12
View File
@@ -1,8 +1,4 @@
/**
* Spinner Component
* Loading indicator with animated frames
*/
import { useState, useEffect } from 'react';
import { createSignal, createEffect, onCleanup, Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
import { symbols } from '../theme/symbols.js';
@@ -11,20 +7,24 @@ interface SpinnerProps {
color?: keyof typeof terminalColors;
}
export function Spinner({ label, color = 'accent' }: SpinnerProps) {
const [frame, setFrame] = useState(0);
export function Spinner(props: SpinnerProps) {
const [frame, setFrame] = createSignal(0);
useEffect(() => {
createEffect(() => {
const interval = setInterval(() => {
setFrame((f) => (f + 1) % symbols.spinner.length);
}, 80);
return () => clearInterval(interval);
}, []);
onCleanup(() => clearInterval(interval));
});
const color = () => props.color ?? 'accent';
return (
<box flexDirection="row" gap={1}>
<text fg={terminalColors[color]}>{symbols.spinner[frame]}</text>
{label && <text fg={terminalColors.text}>{label}</text>}
<text fg={terminalColors[color()]}>{symbols.spinner[frame()]}</text>
<Show when={props.label}>
<text fg={terminalColors.text}>{props.label}</text>
</Show>
</box>
);
}
+100 -122
View File
@@ -1,39 +1,28 @@
/**
* Splash Component
* Cinematic ASCII art intro with elegant animations
* Premium terminal experience
*/
import { useState, useEffect, useMemo, useCallback } from 'react';
import { createSignal, createEffect, onCleanup, createMemo, Show, For } from 'solid-js';
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
[
' ███████╗██╗ ██╗██╗██╗ ██╗ ██╗ ██╗██╗████████╗',
' ██╔════╝██║ ██╔╝██║██║ ██║ ██║ ██╔╝██║╚══██╔══╝',
@@ -44,24 +33,20 @@ const LOGO_FRAMES = [
],
];
// 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' },
@@ -75,48 +60,48 @@ interface SplashProps {
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[]>([]);
export function Splash(props: SplashProps) {
const [frame, setFrame] = createSignal(0);
const [progress, setProgress] = createSignal(0);
const [spinnerFrame, setSpinnerFrame] = createSignal(0);
const [phase, setPhase] = createSignal(0);
const [fadeIn, setFadeIn] = createSignal(0);
const [particles, setParticles] = createSignal<string[]>([]);
// Cache version to avoid repeated sync file I/O on every render
const version = useMemo(() => getVersion(), []);
const version = createMemo(() => 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 currentLogo = () => {
return useSmallLogo ? LOGO_SMALL : (LOGO_FRAMES[Math.min(frame(), 4)] || LOGO_FRAMES[4]);
};
const maxWidth = () => Math.max(...currentLogo().map((l) => l.length));
const generateParticles = () => {
const chars = ['·', '∙', '•', '○', '◦', '◌', '◍', '◎'];
return Array(cols).fill(0).map(() =>
Math.random() > 0.97 ? chars[Math.floor(Math.random() * chars.length)] : ' '
).join('');
}, [cols]);
return Array(cols)
.fill(0)
.map(() => (Math.random() > 0.97 ? chars[Math.floor(Math.random() * chars.length)] : ' '))
.join('');
};
// Logo reveal animation
useEffect(() => {
if (frame >= 4) return;
const timer = setTimeout(() => setFrame(f => f + 1), 200);
return () => clearTimeout(timer);
}, [frame]);
createEffect(() => {
if (frame() >= 4) return;
const timer = setTimeout(() => setFrame((f) => f + 1), 200);
onCleanup(() => clearTimeout(timer));
});
// Fade in effect
useEffect(() => {
if (fadeIn >= 10) return;
const timer = setTimeout(() => setFadeIn(f => f + 1), 50);
return () => clearTimeout(timer);
}, [fadeIn]);
createEffect(() => {
if (fadeIn() >= 10) return;
const timer = setTimeout(() => setFadeIn((f) => f + 1), 50);
onCleanup(() => clearTimeout(timer));
});
// Progress animation
useEffect(() => {
createEffect(() => {
const interval = setInterval(() => {
setProgress(p => {
setProgress((p) => {
const newProgress = p + (Math.random() * 3 + 1);
if (newProgress >= 100) {
clearInterval(interval);
@@ -125,137 +110,130 @@ export function Splash({ onComplete, duration = 3500 }: SplashProps) {
return newProgress;
});
}, 50);
return () => clearInterval(interval);
}, []);
onCleanup(() => clearInterval(interval));
});
// Phase progression
useEffect(() => {
const phaseProgress = progress / 20;
createEffect(() => {
const phaseProgress = progress() / 20;
setPhase(Math.min(Math.floor(phaseProgress), PHASES.length - 1));
}, [progress]);
});
// Spinner animation
useEffect(() => {
createEffect(() => {
const interval = setInterval(() => {
setSpinnerFrame(f => (f + 1) % SPINNER.length);
setSpinnerFrame((f) => (f + 1) % SPINNER.length);
}, 80);
return () => clearInterval(interval);
}, []);
onCleanup(() => clearInterval(interval));
});
// Particle animation
useEffect(() => {
createEffect(() => {
const interval = setInterval(() => {
setParticles(prev => {
setParticles((prev) => {
const newParticles = [...prev];
if (newParticles.length > 3) newParticles.shift();
newParticles.push(generateParticles());
return newParticles;
});
}, 150);
return () => clearInterval(interval);
}, [generateParticles]);
onCleanup(() => clearInterval(interval));
});
// Auto-complete
useEffect(() => {
const timer = setTimeout(onComplete, duration);
return () => clearTimeout(timer);
}, [onComplete, duration]);
createEffect(() => {
const timer = setTimeout(props.onComplete, props.duration ?? 3500);
onCleanup(() => clearTimeout(timer));
});
const pad = ' '.repeat(Math.max(0, Math.floor((cols - maxWidth) / 2)));
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 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];
const currentPhase = () => PHASES[phase()];
return (
<box flexDirection="column" height={rows}>
{/* Top ambient particles */}
<text fg={terminalColors.textMuted}>
{particles[0] || ''}
</text>
<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>
))}
<For each={currentLogo()}>
{(line, idx) => (
<text fg={frame() >= 4 ? terminalColors.accent : terminalColors.textMuted}>
{frame() >= 4 ? (
<b>
{pad()}
{line}
</b>
) : (
<>
{pad()}
{line}
</>
)}
</text>
)}
</For>
</box>
{/* Tagline with fade-in */}
<text> </text>
{fadeIn > 3 && (
<Show when={fadeIn() > 3}>
<text fg={terminalColors.textSecondary}>
{pad}{' '}universal skills for ai coding agents
{pad()}
{' '}universal skills for ai coding agents
</text>
)}
</Show>
{/* Version badge */}
{fadeIn > 5 && (
<>
<text> </text>
<text fg={terminalColors.textMuted}>
{pad}{' '}v{version}
</text>
</>
)}
<Show when={fadeIn() > 5}>
<text> </text>
<text fg={terminalColors.textMuted}>
{pad()}
{' '}v{version()}
</text>
</Show>
{/* Spacer */}
<text> </text>
<text> </text>
{/* Progress section */}
{fadeIn > 7 && (
<Show when={fadeIn() > 7}>
<box flexDirection="column" alignItems="center">
{/* Status line */}
<box flexDirection="row">
<text fg={terminalColors.accent}>
{progressPad}{SPINNER[spinnerFrame]}{' '}
{progressPad}
{SPINNER[spinnerFrame()]}{' '}
</text>
<text fg={terminalColors.text}>
<b>{currentPhase.message}</b>
<b>{currentPhase().message}</b>
</text>
{currentPhase.detail && (
<text fg={terminalColors.textMuted}>
{' '}{currentPhase.detail}
</text>
)}
<Show when={currentPhase().detail}>
<text fg={terminalColors.textMuted}> {currentPhase().detail}</text>
</Show>
</box>
{/* Progress bar */}
<text> </text>
<box flexDirection="row">
<text fg={terminalColors.textMuted}>{progressPad}[</text>
<text fg={terminalColors.accent}>{progressBar}</text>
<text fg={terminalColors.accent}>{progressBar()}</text>
<text fg={terminalColors.textMuted}>]</text>
<text fg={terminalColors.textSecondary}>{' '}{Math.floor(progress)}%</text>
<text fg={terminalColors.textSecondary}> {Math.floor(progress())}%</text>
</box>
</box>
)}
</Show>
{/* Spacer */}
<box flexGrow={1} />
{/* Bottom hint */}
<box flexDirection="column" alignItems="center">
<text fg={terminalColors.textMuted}>
{progressPad}{' '}press any key to skip
{progressPad}
{' '}press any key to skip
</text>
<text> </text>
{/* Bottom particles */}
<text fg={terminalColors.textMuted}>
{particles[1] || ''}
</text>
<text fg={terminalColors.textMuted}>{particles()[1] || ''}</text>
</box>
</box>
);
+123
View File
@@ -0,0 +1,123 @@
/**
* SplitPane Component
* Horizontal/vertical split layout
*/
import { Show, type JSX } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
interface SplitPaneProps {
direction?: 'horizontal' | 'vertical';
primarySize?: number | string;
secondarySize?: number | string;
showDivider?: boolean;
dividerChar?: string;
primary: JSX.Element;
secondary?: JSX.Element;
gap?: number;
}
export function SplitPane(props: SplitPaneProps) {
const direction = () => props.direction ?? 'horizontal';
const showDivider = () => props.showDivider ?? true;
const dividerChar = () => props.dividerChar ?? (direction() === 'horizontal' ? '│' : '─');
const gap = () => props.gap ?? 1;
const flexDir = () => (direction() === 'horizontal' ? 'row' : 'column');
const primaryWidth = () => {
if (direction() === 'vertical') return undefined;
if (props.primarySize !== undefined) return props.primarySize;
return undefined;
};
const primaryHeight = () => {
if (direction() === 'horizontal') return undefined;
if (props.primarySize !== undefined) return props.primarySize;
return undefined;
};
const secondaryWidth = () => {
if (direction() === 'vertical') return undefined;
if (props.secondarySize !== undefined) return props.secondarySize;
return undefined;
};
const secondaryHeight = () => {
if (direction() === 'horizontal') return undefined;
if (props.secondarySize !== undefined) return props.secondarySize;
return undefined;
};
return (
<box flexDirection={flexDir()}>
<box
width={primaryWidth()}
height={primaryHeight()}
flexGrow={primaryWidth() === undefined && primaryHeight() === undefined ? 1 : undefined}
>
{props.primary}
</box>
<Show when={props.secondary && showDivider()}>
<box
width={direction() === 'horizontal' ? gap() : undefined}
height={direction() === 'vertical' ? gap() : undefined}
justifyContent="center"
alignItems="center"
>
<text fg={terminalColors.border}>{dividerChar()}</text>
</box>
</Show>
<Show when={props.secondary}>
<box
width={secondaryWidth()}
height={secondaryHeight()}
flexGrow={secondaryWidth() === undefined && secondaryHeight() === undefined ? 1 : undefined}
>
{props.secondary}
</box>
</Show>
</box>
);
}
interface ThreePaneLayoutProps {
left?: JSX.Element;
center: JSX.Element;
right?: JSX.Element;
leftWidth?: number;
rightWidth?: number;
showLeftDivider?: boolean;
showRightDivider?: boolean;
}
export function ThreePaneLayout(props: ThreePaneLayoutProps) {
const leftWidth = () => props.leftWidth ?? 20;
const rightWidth = () => props.rightWidth ?? 30;
return (
<box flexDirection="row" flexGrow={1}>
<Show when={props.left}>
<box width={leftWidth()}>{props.left}</box>
<Show when={props.showLeftDivider !== false}>
<box width={1}>
<text fg={terminalColors.border}>│</text>
</box>
</Show>
</Show>
<box flexGrow={1}>{props.center}</box>
<Show when={props.right}>
<Show when={props.showRightDivider !== false}>
<box width={1}>
<text fg={terminalColors.border}>│</text>
</box>
</Show>
<box width={rightWidth()}>{props.right}</box>
</Show>
</box>
);
}
+37 -46
View File
@@ -1,8 +1,4 @@
/**
* StatsCard Component
* OpenSync-style stats display with optional animations
*/
import { useState, useEffect } from 'react';
import { createSignal, createEffect, onCleanup, For } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
import { animations } from '../theme/animations.js';
@@ -17,27 +13,26 @@ interface StatsCardProps {
animated?: boolean;
}
export function StatsCard({ items, animated = true }: StatsCardProps) {
const [displayValues, setDisplayValues] = useState<number[]>(() =>
animated ? items.map(() => 0) : items.map((item) => item.value)
export function StatsCard(props: StatsCardProps) {
const animated = () => props.animated ?? true;
const [displayValues, setDisplayValues] = createSignal<number[]>(
animated() ? props.items.map(() => 0) : props.items.map((item) => item.value)
);
const [animComplete, setAnimComplete] = useState(!animated);
const [prevItemsLength, setPrevItemsLength] = useState(items.length);
const [animComplete, setAnimComplete] = createSignal(!animated());
useEffect(() => {
if (items.length !== prevItemsLength) {
setPrevItemsLength(items.length);
setDisplayValues(animated ? items.map(() => 0) : items.map((item) => item.value));
setAnimComplete(!animated);
}
}, [items, prevItemsLength, animated]);
createEffect(() => {
const newValues = animated() ? props.items.map(() => 0) : props.items.map((item) => item.value);
setDisplayValues(newValues);
setAnimComplete(!animated());
});
useEffect(() => {
if (!animated || animComplete) return;
createEffect(() => {
if (!animated() || animComplete()) return;
const duration = animations.countUp.duration;
const startTime = Date.now();
const targetValues = items.map((item) => item.value);
const targetValues = props.items.map((item) => item.value);
const frameInterval = 16;
const intervalId = setInterval(() => {
@@ -45,10 +40,7 @@ export function StatsCard({ items, animated = true }: StatsCardProps) {
const progress = Math.min(elapsed / duration, 1);
const eased = 1 - Math.pow(1 - progress, 4);
const newValues = targetValues.map((target) =>
Math.round(target * eased)
);
const newValues = targetValues.map((target) => Math.round(target * eased));
setDisplayValues(newValues);
if (progress >= 1) {
@@ -57,32 +49,31 @@ export function StatsCard({ items, animated = true }: StatsCardProps) {
}
}, frameInterval);
return () => clearInterval(intervalId);
}, [animated, animComplete, items]);
onCleanup(() => clearInterval(intervalId));
});
return (
<box flexDirection="row" gap={2}>
{items.map((item, index) => {
const fg = item.color
? terminalColors[item.color]
: terminalColors.text;
<For each={props.items}>
{(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>
);
})}
return (
<box
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>
);
}}
</For>
</box>
);
}
+9 -17
View File
@@ -1,7 +1,4 @@
/**
* StatusBar Component
* Bottom status bar with keyboard shortcuts
*/
import { Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
import { STATUS_BAR_SHORTCUTS } from '../state/types.js';
@@ -11,11 +8,10 @@ interface StatusBarProps {
shortcuts?: string;
}
export function StatusBar({
message,
messageType = 'info',
shortcuts = STATUS_BAR_SHORTCUTS,
}: StatusBarProps) {
export function StatusBar(props: StatusBarProps) {
const messageType = () => props.messageType ?? 'info';
const shortcuts = () => props.shortcuts ?? STATUS_BAR_SHORTCUTS;
const messageColors = {
info: terminalColors.info,
success: terminalColors.success,
@@ -25,14 +21,10 @@ export function StatusBar({
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>
)}
<text fg={terminalColors.textMuted}>{'\u2500'.repeat(70)}</text>
<Show when={props.message} fallback={<text fg={terminalColors.textMuted}>{shortcuts()}</text>}>
<text fg={messageColors[messageType()]}>{props.message}</text>
</Show>
</box>
);
}
@@ -0,0 +1,118 @@
/**
* StatusIndicator Component
* Loading/success/error/warning indicator
*/
import { Show, createSignal, createEffect, onCleanup } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
export type StatusType = 'loading' | 'success' | 'error' | 'warning' | 'info' | 'pending';
interface StatusIndicatorProps {
status: StatusType;
label?: string;
showLabel?: boolean;
size?: 'sm' | 'md' | 'lg';
animated?: boolean;
}
const STATUS_ICONS: Record<StatusType, string> = {
loading: '⟳',
success: '✓',
error: '✗',
warning: '⚠',
info: 'ℹ',
pending: '○',
};
const STATUS_COLORS: Record<StatusType, string> = {
loading: terminalColors.accent,
success: terminalColors.success,
error: terminalColors.error,
warning: terminalColors.warning,
info: terminalColors.info,
pending: terminalColors.textMuted,
};
const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
export function StatusIndicator(props: StatusIndicatorProps) {
const [spinnerFrame, setSpinnerFrame] = createSignal(0);
const showLabel = () => props.showLabel ?? true;
const animated = () => props.animated ?? true;
createEffect(() => {
if (props.status === 'loading' && animated()) {
const interval = setInterval(() => {
setSpinnerFrame((f) => (f + 1) % SPINNER_FRAMES.length);
}, 80);
onCleanup(() => clearInterval(interval));
}
});
const icon = () => {
if (props.status === 'loading' && animated()) {
return SPINNER_FRAMES[spinnerFrame()];
}
return STATUS_ICONS[props.status];
};
const color = () => STATUS_COLORS[props.status];
const defaultLabel = () => {
switch (props.status) {
case 'loading':
return 'Loading...';
case 'success':
return 'Success';
case 'error':
return 'Error';
case 'warning':
return 'Warning';
case 'info':
return 'Info';
case 'pending':
return 'Pending';
}
};
return (
<box flexDirection="row">
<text fg={color()}>{icon()}</text>
<Show when={showLabel()}>
<text fg={color()}> {props.label ?? defaultLabel()}</text>
</Show>
</box>
);
}
interface InlineStatusProps {
status: StatusType;
compact?: boolean;
}
export function InlineStatus(props: InlineStatusProps) {
const icon = () => {
if (props.status === 'loading' || props.status === 'pending') {
return '○';
}
return '●';
};
return <text fg={STATUS_COLORS[props.status]}>{icon()}</text>;
}
interface StatusBadgeProps {
status: StatusType;
label: string;
}
export function StatusBadge(props: StatusBadgeProps) {
return (
<box flexDirection="row">
<text fg={terminalColors.textMuted}>[</text>
<text fg={STATUS_COLORS[props.status]}>{props.label}</text>
<text fg={terminalColors.textMuted}>]</text>
</box>
);
}
+169
View File
@@ -0,0 +1,169 @@
/**
* TabBar Component
* Clickable tab navigation
*/
import { For, Show } from 'solid-js';
import { terminalColors } from '../theme/colors.js';
export interface Tab {
id: string;
label: string;
icon?: string;
badge?: string | number;
disabled?: boolean;
}
interface TabBarProps {
tabs: Tab[];
activeId: string;
hoveredId?: string | null;
onSelect?: (id: string) => void;
variant?: 'default' | 'pills' | 'underline';
size?: 'sm' | 'md' | 'lg';
showShortcuts?: boolean;
}
export function TabBar(props: TabBarProps) {
const variant = () => props.variant ?? 'default';
const size = () => props.size ?? 'md';
const showShortcuts = () => props.showShortcuts ?? false;
const gap = () => {
switch (size()) {
case 'sm':
return 1;
case 'lg':
return 3;
default:
return 2;
}
};
return (
<box flexDirection="row">
<For each={props.tabs}>
{(tab, index) => {
const isActive = () => tab.id === props.activeId;
const isHovered = () => tab.id === props.hoveredId;
const isDisabled = () => tab.disabled ?? false;
const fg = () => {
if (isDisabled()) return terminalColors.textMuted;
if (isActive()) return terminalColors.accent;
if (isHovered()) return terminalColors.text;
return terminalColors.textSecondary;
};
const decoration = () => {
if (variant() === 'underline' && isActive()) {
return '─';
}
return '';
};
const brackets = () => {
if (variant() === 'pills') {
if (isActive()) return { left: '[', right: ']' };
return { left: ' ', right: ' ' };
}
return { left: '', right: '' };
};
const handleClick = () => {
if (!isDisabled() && props.onSelect) {
props.onSelect(tab.id);
}
};
return (
<box flexDirection="column" marginRight={index() < props.tabs.length - 1 ? gap() : 0} onClick={handleClick}>
<box flexDirection="row">
<text fg={terminalColors.border}>{brackets().left}</text>
<Show when={tab.icon}>
<text fg={fg()}>{tab.icon} </text>
</Show>
<text fg={fg()}>{tab.label}</text>
<Show when={tab.badge !== undefined}>
<text fg={terminalColors.textMuted}> ({tab.badge})</text>
</Show>
<Show when={showShortcuts()}>
<text fg={terminalColors.textMuted}>
{' '}
{String(index() + 1)}
</text>
</Show>
<text fg={terminalColors.border}>{brackets().right}</text>
</box>
<Show when={variant() === 'underline'}>
<text fg={isActive() ? terminalColors.accent : 'transparent'}>
{decoration().repeat(tab.label.length + (tab.icon ? 2 : 0))}
</text>
</Show>
</box>
);
}}
</For>
</box>
);
}
interface VerticalTabBarProps {
tabs: Tab[];
activeId: string;
hoveredId?: string | null;
onSelect?: (id: string) => void;
width?: number;
}
export function VerticalTabBar(props: VerticalTabBarProps) {
const width = () => props.width ?? 20;
return (
<box flexDirection="column" width={width()}>
<For each={props.tabs}>
{(tab) => {
const isActive = () => tab.id === props.activeId;
const isHovered = () => tab.id === props.hoveredId;
const isDisabled = () => tab.disabled ?? false;
const fg = () => {
if (isDisabled()) return terminalColors.textMuted;
if (isActive()) return terminalColors.accent;
if (isHovered()) return terminalColors.text;
return terminalColors.textSecondary;
};
const prefix = () => {
if (isActive()) return '▸ ';
if (isHovered()) return '▹ ';
return ' ';
};
const handleClick = () => {
if (!isDisabled() && props.onSelect) {
props.onSelect(tab.id);
}
};
return (
<box
flexDirection="row"
marginBottom={1}
onClick={handleClick}
>
<text fg={fg()}>{prefix()}</text>
<Show when={tab.icon}>
<text fg={fg()}>{tab.icon} </text>
</Show>
<text fg={fg()}>{tab.label}</text>
<Show when={tab.badge !== undefined}>
<text fg={terminalColors.textMuted}> ({tab.badge})</text>
</Show>
</box>
);
}}
</For>
</box>
);
}
+50
View File
@@ -2,10 +2,13 @@
* Components module for SkillKit TUI
*/
// Existing components
export { AgentGrid } from './AgentGrid.js';
export { StatsCard } from './StatsCard.js';
export { Header } from './Header.js';
export { Sidebar } from './Sidebar.js';
export { RightSidebar } from './RightSidebar.js';
export { BottomStatusBar } from './BottomStatusBar.js';
export { StatusBar } from './StatusBar.js';
export { SkillList } from './SkillList.js';
export { SearchInput } from './SearchInput.js';
@@ -13,3 +16,50 @@ export { Spinner } from './Spinner.js';
export { ProgressBar } from './ProgressBar.js';
export { FeatureList, FEATURES, type Feature } from './FeatureList.js';
export { Splash } from './Splash.js';
// New components (Phase 1.3)
export { SelectList, type SelectListItem } from './SelectList.js';
export { DetailPane, type DetailField } from './DetailPane.js';
export { SplitPane, ThreePaneLayout } from './SplitPane.js';
export { EmptyState, LoadingState, ErrorState } from './EmptyState.js';
export {
StatusIndicator,
InlineStatus,
StatusBadge,
type StatusType,
} from './StatusIndicator.js';
export { CodeBlock, InlineCode } from './CodeBlock.js';
export { FormField, TextAreaField, SelectField } from './FormField.js';
export { ErrorBoundary, Try } from './ErrorBoundary.js';
export {
Button,
ButtonGroup,
IconButton,
type ButtonVariant,
type ButtonSize,
} from './Button.js';
export {
Clickable,
ClickableText,
ClickableRow,
InteractiveArea,
} from './Clickable.js';
export {
HoverHighlight,
HighlightableListItem,
FocusRing,
PressEffect,
} from './HoverHighlight.js';
export {
AnimatedText,
CountUpText,
BlinkingText,
PulsingText,
} from './AnimatedText.js';
export { TabBar, VerticalTabBar, type Tab } from './TabBar.js';
export {
Breadcrumb,
PathBreadcrumb,
NavigationTrail,
type BreadcrumbItem,
} from './Breadcrumb.js';
+34 -22
View File
@@ -1,40 +1,52 @@
import { createCliRenderer } from '@opentui/core';
import { createRoot } from '@opentui/react';
import { render } from '@opentui/solid';
import { App } from './App.js';
let rootInstance: ReturnType<typeof createRoot> | null = null;
let isRunning = true;
let renderer: Awaited<ReturnType<typeof createCliRenderer>> | null = null;
export function exitTUI(code = 0): void {
if (!isRunning) return;
isRunning = false;
try {
// Unmount React tree first
if (rootInstance) {
try {
rootInstance.unmount();
} catch {
// Ignore unmount errors
}
rootInstance = null;
if (renderer && 'dispose' in renderer) {
(renderer as { dispose?: () => void }).dispose?.();
}
} catch {}
// Restore terminal state: exit alt screen, show cursor, reset attributes, clear
try {
process.stdout.write('\x1b[?1049l\x1b[?25h\x1b[0m\x1b[H\x1b[2J');
} catch {
// Ignore write errors
}
} catch {}
// Use setImmediate to allow any pending operations to complete
setImmediate(() => process.exit(code));
}
export async function startTUI(): Promise<never> {
// Setup signal handlers for clean exit
const handleSignal = () => exitTUI(0);
process.on('SIGINT', handleSignal);
process.on('SIGTERM', handleSignal);
process.on('SIGINT', () => exitTUI(0));
process.on('SIGTERM', () => exitTUI(0));
process.on('uncaughtException', (err) => {
console.error('TUI Error:', err.message);
exitTUI(1);
});
process.on('unhandledRejection', (err) => {
console.error('TUI Error:', err);
exitTUI(1);
});
renderer = await createCliRenderer({
exitOnCtrlC: false,
useMouse: true,
enableMouseMovement: true,
});
try {
await render(() => <App onExit={exitTUI} />, renderer);
} catch (err) {
console.error('Render failed:', err);
exitTUI(1);
}
const renderer = await createCliRenderer({ exitOnCtrlC: false });
rootInstance = createRoot(renderer);
rootInstance.render(<App onExit={exitTUI} />);
return new Promise(() => {});
}
-55
View File
@@ -1,55 +0,0 @@
/**
* Type declarations for OpenTUI React JSX elements
* Overrides React's JSX namespace to include OpenTUI elements
*/
import * as React from 'react';
declare global {
namespace JSX {
interface IntrinsicElements {
box: React.PropsWithChildren<{
flexDirection?: 'row' | 'column';
flexGrow?: number;
alignItems?: 'flex-start' | 'flex-end' | 'center' | 'stretch';
justifyContent?: 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around';
width?: number | string;
height?: number | string;
padding?: number;
paddingLeft?: number;
paddingRight?: number;
paddingTop?: number;
paddingBottom?: number;
paddingX?: number;
paddingY?: number;
margin?: number;
marginLeft?: number;
marginRight?: number;
marginTop?: number;
marginBottom?: number;
marginX?: number;
marginY?: number;
gap?: number;
border?: boolean;
borderStyle?: 'single' | 'double' | 'rounded';
borderColor?: string;
backgroundColor?: string;
color?: string;
bold?: boolean;
dim?: boolean;
title?: string;
style?: Record<string, unknown>;
key?: React.Key;
}>;
text: React.PropsWithChildren<{
color?: string;
bold?: boolean;
dim?: boolean;
attributes?: number;
width?: number;
key?: React.Key;
}>;
}
}
}
export {};
+302 -131
View File
@@ -1,7 +1,19 @@
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useKeyboard } from '@opentui/react';
import { type Screen, DEFAULT_REPOS } from '../state/index.js';
import { createSignal, createEffect, createMemo, Show, For } from 'solid-js';
import { useKeyboard } from '@opentui/solid';
import {
type Screen,
DEFAULT_REPOS,
getMarketplaceRepos,
fetchRepoSkills,
type FetchedSkill,
type RepoInfo,
} from '../state/index.js';
import { terminalColors } from '../theme/colors.js';
import { Header } from '../components/Header.js';
import { Spinner } from '../components/Spinner.js';
import { EmptyState, ErrorState } from '../components/EmptyState.js';
import { DetailPane } from '../components/DetailPane.js';
import { StatusIndicator } from '../components/StatusIndicator.js';
interface BrowseProps {
onNavigate: (screen: Screen) => void;
@@ -9,55 +21,139 @@ interface BrowseProps {
rows?: number;
}
export function Browse({ onNavigate, cols = 80, rows = 24 }: BrowseProps) {
const [selectedIndex, setSelectedIndex] = useState(0);
const [searchQuery, setSearchQuery] = useState('');
const [searchMode, setSearchMode] = useState(false);
const [animPhase, setAnimPhase] = useState(0);
interface RepoWithSkills extends RepoInfo {
skills: FetchedSkill[];
loading: boolean;
error: string | null;
}
const isCompact = cols < 60;
const contentWidth = Math.max(1, Math.min(cols - 4, 60));
export function Browse(props: BrowseProps) {
const [repos, setRepos] = createSignal<RepoWithSkills[]>([]);
const [selectedIndex, setSelectedIndex] = createSignal(0);
const [searchQuery, setSearchQuery] = createSignal('');
const [searchMode, setSearchMode] = createSignal(false);
const [showSkills, setShowSkills] = createSignal(false);
const [loading, setLoading] = createSignal(true);
const [error, setError] = createSignal<string | null>(null);
// Entrance animation
useEffect(() => {
if (animPhase >= 2) return;
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
return () => clearTimeout(timer);
}, [animPhase]);
const rows = () => props.rows ?? 24;
const repos = useMemo(() =>
DEFAULT_REPOS.map((r) => ({
name: r.name,
source: r.source,
})),
[]
);
createEffect(() => {
loadData();
});
const filteredRepos = useMemo(() =>
searchQuery
? repos.filter(
(r) =>
r.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
r.source.toLowerCase().includes(searchQuery.toLowerCase())
const loadData = async () => {
setLoading(true);
setError(null);
try {
const marketplaceRepos = getMarketplaceRepos();
const reposWithState: RepoWithSkills[] = marketplaceRepos.map((repo) => ({
...repo,
skills: [],
loading: false,
error: null,
}));
setRepos(reposWithState);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load repos');
}
setLoading(false);
};
const loadRepoSkills = async (index: number) => {
const repo = repos()[index];
if (!repo || repo.skills.length > 0 || repo.loading) return;
setRepos((prev) =>
prev.map((r, i) => (i === index ? { ...r, loading: true, error: null } : r))
);
try {
const result = await fetchRepoSkills(repo.source, DEFAULT_REPOS);
setRepos((prev) =>
prev.map((r, i) =>
i === index
? {
...r,
skills: result.skills,
loading: false,
error: result.error || null,
}
: r
)
: repos,
[repos, searchQuery]
);
);
} catch (err) {
setRepos((prev) =>
prev.map((r, i) =>
i === index
? {
...r,
loading: false,
error: err instanceof Error ? err.message : 'Failed to fetch',
}
: r
)
);
}
};
const handleKeyNav = useCallback((delta: number) => {
setSelectedIndex(prev => Math.max(0, Math.min(prev + delta, filteredRepos.length - 1)));
}, [filteredRepos.length]);
const filteredRepos = createMemo(() => {
if (!searchQuery()) return repos();
const query = searchQuery().toLowerCase();
return repos().filter(
(r) =>
r.name.toLowerCase().includes(query) ||
r.source.toLowerCase().includes(query)
);
});
const maxVisible = () => Math.max(5, rows() - 12);
const startIdx = () =>
Math.max(
0,
Math.min(
selectedIndex() - Math.floor(maxVisible() / 2),
filteredRepos().length - maxVisible()
)
);
const visibleRepos = () =>
filteredRepos().slice(startIdx(), startIdx() + maxVisible());
const handleKeyNav = (delta: number) => {
const max = filteredRepos().length - 1;
setSelectedIndex((prev) => Math.max(0, Math.min(prev + delta, max)));
};
const handleOpenRepo = () => {
const repo = filteredRepos()[selectedIndex()];
if (repo) {
const actualIndex = repos().findIndex(
(r) => r.source === repo.source && r.name === repo.name
);
if (actualIndex !== -1) {
loadRepoSkills(actualIndex);
}
setShowSkills(true);
}
};
useKeyboard((key: { name?: string; sequence?: string }) => {
if (searchMode) {
if (searchMode()) {
if (key.name === 'escape') {
setSearchMode(false);
} else if (key.name === 'backspace') {
setSearchQuery(prev => prev.slice(0, -1));
setSearchQuery((prev) => prev.slice(0, -1));
} else if (key.name === 'return') {
setSearchMode(false);
} else if (key.sequence && key.sequence.length === 1 && /[a-zA-Z0-9\-_.]/.test(key.sequence)) {
setSearchQuery(prev => prev + key.sequence);
} else if (
key.sequence &&
key.sequence.length === 1 &&
/[a-zA-Z0-9\-_.]/.test(key.sequence)
) {
setSearchQuery((prev) => prev + key.sequence);
setSelectedIndex(0);
}
return;
@@ -66,114 +162,189 @@ export function Browse({ onNavigate, cols = 80, rows = 24 }: BrowseProps) {
if (key.name === 'j' || key.name === 'down') handleKeyNav(1);
else if (key.name === 'k' || key.name === 'up') handleKeyNav(-1);
else if (key.sequence === '/') setSearchMode(true);
else if (key.name === 'return') {
const repo = filteredRepos[selectedIndex];
if (repo) {
// Open/view the selected repo (navigate to installed to see skills from this repo)
onNavigate('installed');
}
else if (key.name === 'return') handleOpenRepo();
else if (key.name === 'r') loadData();
else if (key.name === 'escape') {
if (showSkills()) setShowSkills(false);
else if (searchQuery()) setSearchQuery('');
else props.onNavigate('home');
}
else if (key.name === 'escape') onNavigate('home');
});
useEffect(() => {
if (selectedIndex >= filteredRepos.length && filteredRepos.length > 0) {
setSelectedIndex(filteredRepos.length - 1);
createEffect(() => {
if (selectedIndex() >= filteredRepos().length && filteredRepos().length > 0) {
setSelectedIndex(filteredRepos().length - 1);
}
}, [filteredRepos.length, selectedIndex]);
});
// Calculate visible repos
const maxVisible = Math.max(5, rows - 10);
const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(maxVisible / 2), filteredRepos.length - maxVisible));
const visibleRepos = filteredRepos.slice(startIdx, startIdx + maxVisible);
const selectedRepo = () => {
const repoList = filteredRepos();
if (repoList.length === 0) return null;
return repoList[selectedIndex()];
};
const divider = useMemo(() =>
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
[contentWidth]
);
const repoDetailFields = () => {
const repo = selectedRepo();
if (!repo) return [];
const shortcuts = isCompact
? 'j/k nav enter open / search esc back'
: 'j/k navigate enter open / search esc back';
return [
{ label: 'Name', value: repo.name },
{ label: 'Source', value: repo.source },
{ label: 'Skills', value: String(repo.skills.length) },
{
label: 'Status',
value: repo.loading ? 'Loading...' : repo.error ? 'Error' : 'Ready',
},
];
};
return (
<box flexDirection="column" padding={1}>
{/* Header */}
{animPhase >= 1 && (
<box flexDirection="column">
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
<text fg={terminalColors.browse}>⌕ Browse</text>
<text fg={terminalColors.textMuted}>{filteredRepos.length} repos</text>
</box>
<text fg={terminalColors.textMuted}>explore skill repositories</text>
<text> </text>
<box flexDirection="column" paddingLeft={1}>
<Header
title="Browse"
subtitle="Explore skill repositories"
icon="⌕"
count={repos().length}
/>
<Show when={error()}>
<ErrorState
message={error()!}
action={{ label: 'Retry', key: 'r' }}
compact
/>
</Show>
<Show when={loading()}>
<Spinner label="Loading repositories..." />
</Show>
<Show when={!loading() && !error()}>
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted}>/ </text>
<text
fg={
searchQuery() || searchMode()
? terminalColors.text
: terminalColors.textMuted
}
>
{searchQuery() || (searchMode() ? '|' : 'type to filter...')}
</text>
</box>
)}
{/* Search */}
{animPhase >= 2 && (
<box flexDirection="column">
{divider}
<text> </text>
<box flexDirection="row">
<text fg={terminalColors.textMuted}>/ </text>
<text fg={searchQuery ? terminalColors.text : terminalColors.textMuted}>
{searchQuery || 'type to filter...'}
</text>
<text fg={terminalColors.textMuted}>─────────────────────────────────────────────</text>
<text> </text>
<box flexDirection="row">
<box flexDirection="column" flexGrow={1}>
<Show
when={filteredRepos().length > 0}
fallback={
<EmptyState
icon="⌕"
title="No repositories found"
description={
searchQuery()
? 'Try a different search term'
: 'No repositories configured'
}
/>
}
>
<text fg={terminalColors.text}>
<b>Repositories</b>{' '}
<text fg={terminalColors.textMuted}>
({filteredRepos().length})
</text>
</text>
<text> </text>
<For each={visibleRepos()}>
{(repo, idx) => {
const actualIdx = () => startIdx() + idx();
const selected = () => actualIdx() === selectedIndex();
return (
<box flexDirection="row" marginBottom={1}>
<text
fg={selected() ? terminalColors.accent : terminalColors.text}
width={3}
>
{selected() ? '▸ ' : ' '}
</text>
<text
fg={selected() ? terminalColors.accent : terminalColors.text}
width={25}
>
{repo.name}
</text>
<text fg={terminalColors.textMuted} width={10}>
{repo.skills.length > 0
? `${repo.skills.length} skills`
: repo.loading
? 'loading...'
: ''}
</text>
<Show when={repo.error}>
<text fg={terminalColors.error}>✗</text>
</Show>
</box>
);
}}
</For>
<Show when={filteredRepos().length > maxVisible()}>
<text fg={terminalColors.textMuted}>
showing {startIdx() + 1}-
{Math.min(startIdx() + maxVisible(), filteredRepos().length)} of{' '}
{filteredRepos().length}
</text>
</Show>
</Show>
</box>
<text> </text>
{divider}
<text> </text>
</box>
)}
{/* Repository list */}
{animPhase >= 2 && (
<box flexDirection="column">
<text fg={terminalColors.text}>Repositories</text>
<text> </text>
{filteredRepos.length === 0 ? (
<text fg={terminalColors.textMuted}>No repositories match your search</text>
) : (
<box flexDirection="column">
{visibleRepos.map((repo, idx) => {
const actualIdx = startIdx + idx;
const selected = actualIdx === selectedIndex;
const indicator = selected ? '▸' : ' ';
// Truncate source if needed - clamp to avoid negative slicing
const maxSourceLen = Math.max(0, contentWidth - repo.name.length - 6);
const displaySource = maxSourceLen > 3 && repo.source.length > maxSourceLen
? repo.source.slice(0, maxSourceLen - 3) + '...'
: repo.source;
// Use single text element to avoid rendering overlap issues
const line = `${indicator}${repo.name} · ${displaySource}`;
return (
<text key={repo.source} fg={selected ? terminalColors.accent : terminalColors.text}>
{line}
<Show when={showSkills() && selectedRepo()}>
<DetailPane
title={selectedRepo()!.name}
subtitle={`${selectedRepo()!.skills.length} skills`}
icon="⌕"
fields={repoDetailFields()}
actions={[
{ key: 'Enter', label: 'Install' },
{ key: 'Esc', label: 'Close' },
]}
width={35}
visible={showSkills()}
onClose={() => setShowSkills(false)}
>
<Show when={selectedRepo()!.loading}>
<StatusIndicator status="loading" label="Loading skills..." />
</Show>
<Show when={selectedRepo()!.skills.length > 0}>
<text fg={terminalColors.text}>
<b>Skills:</b>
</text>
<For each={selectedRepo()!.skills.slice(0, 5)}>
{(skill) => (
<text fg={terminalColors.textSecondary}>• {skill.name}</text>
)}
</For>
<Show when={selectedRepo()!.skills.length > 5}>
<text fg={terminalColors.textMuted}>
+{selectedRepo()!.skills.length - 5} more
</text>
);
})}
</box>
)}
{/* Scroll indicator */}
{filteredRepos.length > maxVisible && (
<text fg={terminalColors.textMuted}>
{'\n'}showing {startIdx + 1}-{Math.min(startIdx + maxVisible, filteredRepos.length)} of {filteredRepos.length}
</text>
)}
<text> </text>
</Show>
</Show>
</DetailPane>
</Show>
</box>
)}
{/* Footer */}
{animPhase >= 2 && (
<box flexDirection="column">
{divider}
<text fg={terminalColors.textMuted}>{shortcuts}</text>
</box>
)}
<text> </text>
<text fg={terminalColors.textMuted}>─────────────────────────────────────────────</text>
<text fg={terminalColors.textMuted}>
j/k navigate Enter open / search r refresh Esc back
</text>
</Show>
</box>
);
}
+272 -29
View File
@@ -1,12 +1,19 @@
/**
* Context Screen
* Project context analysis
*/
import { useState, useEffect } from 'react';
import { createSignal, createEffect, Show, For } from 'solid-js';
import { useKeyboard } from '@opentui/solid';
import { type Screen } from '../state/index.js';
import { terminalColors } from '../theme/colors.js';
import { Header } from '../components/Header.js';
import { Spinner } from '../components/Spinner.js';
import { EmptyState, ErrorState } from '../components/EmptyState.js';
import { StatusIndicator } from '../components/StatusIndicator.js';
import {
loadProjectContext,
analyzeProjectContext,
refreshContext,
exportContext,
getStackTags,
type ContextServiceState,
} from '../services/context.service.js';
interface ContextProps {
onNavigate: (screen: Screen) => void;
@@ -14,43 +21,279 @@ interface ContextProps {
rows?: number;
}
export function Context({ onNavigate, cols = 80, rows = 24 }: ContextProps) {
const [loading, setLoading] = useState(true);
export function Context(props: ContextProps) {
const [state, setState] = createSignal<ContextServiceState>({
context: null,
stack: null,
loading: true,
analyzing: false,
error: null,
});
const [tags, setTags] = createSignal<string[]>([]);
const [selectedSection, setSelectedSection] = createSignal(0);
useEffect(() => {
const timer = setTimeout(() => setLoading(false), 500);
return () => clearTimeout(timer);
}, []);
const sections = ['Overview', 'Languages', 'Frameworks', 'Libraries', 'Patterns'];
const contextInfo = [
{ label: 'Working Directory', value: process.cwd() },
{ label: 'Node Version', value: process.version },
{ label: 'Platform', value: process.platform },
{ label: 'Architecture', value: process.arch },
];
const moveSection = (delta: number) => {
setSelectedSection((i) =>
Math.max(0, Math.min(sections.length - 1, i + delta))
);
};
useKeyboard((key: { name?: string }) => {
if (key.name === 'h' || key.name === 'left') moveSection(-1);
else if (key.name === 'l' || key.name === 'right') moveSection(1);
else if (key.name === 'r') handleRefresh();
else if (key.name === 'e') handleExport();
else if (key.name === 'escape') props.onNavigate('home');
});
createEffect(() => {
loadData();
});
const loadData = async () => {
setState((s) => ({ ...s, loading: true, error: null }));
try {
let result = await loadProjectContext();
if (!result.context) {
result = await analyzeProjectContext();
}
setState(result);
setTags(await getStackTags());
} catch (err) {
setState((s) => ({
...s,
loading: false,
analyzing: false,
error: err instanceof Error ? err.message : 'Failed to load context',
}));
}
};
const handleRefresh = async () => {
setState((s) => ({ ...s, analyzing: true, error: null }));
try {
const result = await refreshContext();
setState(result);
setTags(await getStackTags());
} catch (err) {
setState((s) => ({
...s,
analyzing: false,
error: err instanceof Error ? err.message : 'Failed to refresh context',
}));
}
};
const handleExport = async () => {
try {
await exportContext(undefined, 'json');
} catch (err) {
setState((s) => ({
...s,
error: err instanceof Error ? err.message : 'Failed to export context',
}));
}
};
const currentSection = () => sections[selectedSection()];
const ctx = () => state().context;
return (
<box flexDirection="column" paddingLeft={1}>
<Header
title="Project Context"
subtitle="Analyze your project environment"
icon="&#x25C9;"
icon="◉"
count={tags().length}
/>
{loading ? (
<Spinner label="Analyzing project context..." />
) : (
<Show when={state().error}>
<ErrorState
message={state().error!}
action={{ label: 'Retry', key: 'r' }}
compact
/>
</Show>
<Show when={state().loading || state().analyzing}>
<Spinner
label={state().analyzing ? 'Analyzing project...' : 'Loading context...'}
/>
</Show>
<Show when={!state().loading && !state().error && ctx()}>
<box flexDirection="column">
{contextInfo.map((info) => (
<box key={info.label} flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted} width={20}>
{info.label}:
</text>
<text fg={terminalColors.text}>{info.value}</text>
<box flexDirection="row" marginBottom={1}>
<For each={sections}>
{(section, idx) => (
<box marginRight={2}>
<text
fg={
idx() === selectedSection()
? terminalColors.accent
: terminalColors.textMuted
}
>
{idx() === selectedSection() ? '▸ ' : ' '}
{section}
</text>
</box>
)}
</For>
</box>
<text fg={terminalColors.textMuted}>─────────────────────────────</text>
<text> </text>
<Show when={currentSection() === 'Overview'}>
<box flexDirection="column">
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted} width={18}>Project:</text>
<text fg={terminalColors.text}>{ctx()!.projectName}</text>
</box>
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted} width={18}>Path:</text>
<text fg={terminalColors.textSecondary}>{ctx()!.rootPath}</text>
</box>
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted} width={18}>Languages:</text>
<text fg={terminalColors.accent}>{ctx()!.languages.length}</text>
</box>
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted} width={18}>Frameworks:</text>
<text fg={terminalColors.accent}>{ctx()!.frameworks.length}</text>
</box>
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted} width={18}>Libraries:</text>
<text fg={terminalColors.accent}>{ctx()!.libraries.length}</text>
</box>
<Show when={ctx()!.lastUpdated}>
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted} width={18}>Last Updated:</text>
<text fg={terminalColors.textSecondary}>{ctx()!.lastUpdated}</text>
</box>
</Show>
</box>
))}
</Show>
<Show when={currentSection() === 'Languages'}>
<box flexDirection="column">
<Show
when={ctx()!.languages.length > 0}
fallback={<EmptyState title="No languages detected" compact />}
>
<For each={ctx()!.languages}>
{(lang) => (
<box marginBottom={1}>
<text fg={terminalColors.text}>
• {lang}
</text>
</box>
)}
</For>
</Show>
</box>
</Show>
<Show when={currentSection() === 'Frameworks'}>
<box flexDirection="column">
<Show
when={ctx()!.frameworks.length > 0}
fallback={<EmptyState title="No frameworks detected" compact />}
>
<For each={ctx()!.frameworks}>
{(fw) => (
<box marginBottom={1}>
<text fg={terminalColors.text}>
• {fw}
</text>
</box>
)}
</For>
</Show>
</box>
</Show>
<Show when={currentSection() === 'Libraries'}>
<box flexDirection="column">
<Show
when={ctx()!.libraries.length > 0}
fallback={<EmptyState title="No libraries detected" compact />}
>
<For each={ctx()!.libraries.slice(0, 15)}>
{(lib) => (
<box marginBottom={1}>
<text fg={terminalColors.text}>
• {lib}
</text>
</box>
)}
</For>
<Show when={ctx()!.libraries.length > 15}>
<text fg={terminalColors.textMuted}>
+{ctx()!.libraries.length - 15} more
</text>
</Show>
</Show>
</box>
</Show>
<Show when={currentSection() === 'Patterns'}>
<box flexDirection="column">
<Show
when={Object.keys(ctx()!.patterns).length > 0}
fallback={<EmptyState title="No patterns detected" compact />}
>
<For each={Object.entries(ctx()!.patterns)}>
{([key, value]) => (
<box flexDirection="row" marginBottom={1}>
<text fg={terminalColors.textMuted} width={18}>{key}:</text>
<text fg={terminalColors.text}>{String(value)}</text>
</box>
)}
</For>
</Show>
</box>
</Show>
<text> </text>
<text fg={terminalColors.textMuted}>─────────────────────────────</text>
<text> </text>
<Show when={tags().length > 0}>
<box flexDirection="row" flexWrap="wrap">
<text fg={terminalColors.textMuted}>Tags: </text>
<For each={tags().slice(0, 8)}>
{(tag, idx) => (
<text fg={terminalColors.textSecondary}>
{tag}
{idx() < Math.min(tags().length, 8) - 1 ? ', ' : ''}
</text>
)}
</For>
<Show when={tags().length > 8}>
<text fg={terminalColors.textMuted}> +{tags().length - 8}</text>
</Show>
</box>
</Show>
</box>
)}
</Show>
<Show when={!state().loading && !state().error && !ctx()}>
<EmptyState
icon="◉"
title="No context found"
description="Run analysis to detect project context"
action={{ label: 'Analyze', key: 'r' }}
/>
</Show>
<text> </text>
<text fg={terminalColors.textMuted}>
←/→ sections r refresh e export Esc back
</text>
</box>
);
}
+328 -28
View File
@@ -1,13 +1,19 @@
/**
* Execute Screen
* Live skill execution
*/
import { useState } from 'react';
import { type Screen } from '../state/index.js';
import { createSignal, createEffect, createMemo, Show, For } from 'solid-js';
import { useKeyboard } from '@opentui/solid';
import { type Screen, loadSkillsWithDetails, type SkillWithDetails } from '../state/index.js';
import { terminalColors } from '../theme/colors.js';
import { Header } from '../components/Header.js';
import { Spinner } from '../components/Spinner.js';
import { ProgressBar } from '../components/ProgressBar.js';
import { EmptyState, ErrorState } from '../components/EmptyState.js';
import { StatusIndicator } from '../components/StatusIndicator.js';
import {
getAgentAvailability,
executeSkillWithAgent,
listAvailableAgents,
type AgentAvailability,
} from '../services/executor.service.js';
import type { AgentType } from '@skillkit/core';
interface ExecuteProps {
onNavigate: (screen: Screen) => void;
@@ -15,39 +21,333 @@ interface ExecuteProps {
rows?: number;
}
export function Execute({ onNavigate, cols = 80, rows = 24 }: ExecuteProps) {
const [executing, setExecuting] = useState(false);
const [progress, setProgress] = useState(0);
export function Execute(props: ExecuteProps) {
const [skills, setSkills] = createSignal<SkillWithDetails[]>([]);
const [agents, setAgents] = createSignal<AgentAvailability[]>([]);
const [selectedSkillIndex, setSelectedSkillIndex] = createSignal(0);
const [selectedAgentIndex, setSelectedAgentIndex] = createSignal(0);
const [focusedPane, setFocusedPane] = createSignal<'skills' | 'agents'>('skills');
const [executing, setExecuting] = createSignal(false);
const [executionResult, setExecutionResult] = createSignal<{
success: boolean;
output: string;
error?: string;
} | null>(null);
const [loading, setLoading] = createSignal(true);
const [loadError, setLoadError] = createSignal<string | null>(null);
createEffect(() => {
loadData();
});
const loadData = async () => {
setLoading(true);
setLoadError(null);
try {
const skillsWithDetails = loadSkillsWithDetails();
setSkills(skillsWithDetails);
const agentAvailability = await getAgentAvailability();
setAgents(agentAvailability);
} catch (err) {
setLoadError(err instanceof Error ? err.message : 'Failed to load');
} finally {
setLoading(false);
}
};
const handleExecute = async () => {
if (executing()) return;
const skillList = skills();
const agentList = agents();
if (skillList.length === 0 || agentList.length === 0) return;
const skill = skillList[selectedSkillIndex()];
const agent = agentList[selectedAgentIndex()];
if (!skill || !agent || !agent.available) return;
setExecuting(true);
setExecutionResult(null);
try {
const result = await executeSkillWithAgent(
skill.path,
agent.agent,
{ timeout: 60000 }
);
setExecutionResult({
success: result.success,
output: result.output || '',
error: result.error,
});
} catch (err) {
setExecutionResult({
success: false,
output: '',
error: err instanceof Error ? err.message : 'Execution failed',
});
} finally {
setExecuting(false);
}
};
const handleKeyNav = (delta: number) => {
if (focusedPane() === 'skills') {
const max = skills().length - 1;
setSelectedSkillIndex((prev) => Math.max(0, Math.min(prev + delta, max)));
} else {
const max = agents().length - 1;
setSelectedAgentIndex((prev) => Math.max(0, Math.min(prev + delta, max)));
}
};
useKeyboard((key: { name?: string }) => {
if (key.name === 'j' || key.name === 'down') handleKeyNav(1);
else if (key.name === 'k' || key.name === 'up') handleKeyNav(-1);
else if (key.name === 'tab' || key.name === 'l' || key.name === 'right') {
setFocusedPane((p) => (p === 'skills' ? 'agents' : 'skills'));
}
else if (key.name === 'h' || key.name === 'left') {
setFocusedPane((p) => (p === 'agents' ? 'skills' : 'agents'));
}
else if (key.name === 'return' || key.name === 'x') handleExecute();
else if (key.name === 'r') loadData();
else if (key.name === 'escape') {
if (executionResult()) setExecutionResult(null);
else props.onNavigate('home');
}
});
const selectedSkill = () => {
const list = skills();
if (list.length === 0) return null;
return list[selectedSkillIndex()];
};
const selectedAgent = () => {
const list = agents();
if (list.length === 0) return null;
return list[selectedAgentIndex()];
};
const MAX_VISIBLE = 8;
const skillsWindow = createMemo(() => {
const list = skills();
const selected = selectedSkillIndex();
const total = list.length;
if (total <= MAX_VISIBLE) return { start: 0, items: list };
let start = Math.max(0, selected - Math.floor(MAX_VISIBLE / 2));
start = Math.min(start, total - MAX_VISIBLE);
return { start, items: list.slice(start, start + MAX_VISIBLE) };
});
const agentsWindow = createMemo(() => {
const list = agents();
const selected = selectedAgentIndex();
const total = list.length;
if (total <= MAX_VISIBLE) return { start: 0, items: list };
let start = Math.max(0, selected - Math.floor(MAX_VISIBLE / 2));
start = Math.min(start, total - MAX_VISIBLE);
return { start, items: list.slice(start, start + MAX_VISIBLE) };
});
return (
<box flexDirection="column" paddingLeft={1}>
<Header
title="Execute"
subtitle="Run skills in real-time"
icon="&#x25B6;"
subtitle="Run skills with AI agents"
icon="▶"
/>
{executing ? (
<box flexDirection="column">
<Spinner label="Executing skill..." />
<text> </text>
<ProgressBar progress={progress} width={40} />
<text> </text>
<text fg={terminalColors.textMuted}>Press Esc to cancel</text>
<Show when={loading()}>
<Spinner label="Loading..." />
</Show>
<Show when={loadError()}>
<ErrorState
message={loadError()!}
action={{ label: 'Retry', key: 'r' }}
compact
/>
</Show>
<Show when={!loading() && !loadError()}>
<box flexDirection="row">
<box flexDirection="column" width={30}>
<text
fg={
focusedPane() === 'skills'
? terminalColors.accent
: terminalColors.text
}
>
<b>Skills</b>
</text>
<text> </text>
<Show
when={skills().length > 0}
fallback={
<EmptyState
title="No skills installed"
description="Browse to install"
action={{ label: 'Browse', key: 'b' }}
compact
/>
}
>
<Show when={skillsWindow().start > 0}>
<text fg={terminalColors.textMuted}> ▲ {skillsWindow().start} more</text>
</Show>
<For each={skillsWindow().items}>
{(skill, idx) => {
const originalIndex = () => skillsWindow().start + idx();
const isSelected = () =>
focusedPane() === 'skills' && originalIndex() === selectedSkillIndex();
return (
<box marginBottom={1}>
<text
fg={isSelected() ? terminalColors.accent : terminalColors.textSecondary}
>
{isSelected() ? '▸ ' : ' '}
{skill.name}
</text>
</box>
);
}}
</For>
<Show when={skillsWindow().start + MAX_VISIBLE < skills().length}>
<text fg={terminalColors.textMuted}> ▼ {skills().length - skillsWindow().start - MAX_VISIBLE} more</text>
</Show>
</Show>
</box>
<box width={2}>
<text fg={terminalColors.border}>│</text>
</box>
<box flexDirection="column" width={25}>
<text
fg={
focusedPane() === 'agents'
? terminalColors.accent
: terminalColors.text
}
>
<b>Agents</b>
</text>
<text> </text>
<Show
when={agents().length > 0}
fallback={
<EmptyState
title="No agents found"
compact
/>
}
>
<Show when={agentsWindow().start > 0}>
<text fg={terminalColors.textMuted}> ▲ {agentsWindow().start} more</text>
</Show>
<For each={agentsWindow().items}>
{(agent, idx) => {
const originalIndex = () => agentsWindow().start + idx();
const isSelected = () =>
focusedPane() === 'agents' && originalIndex() === selectedAgentIndex();
const available = agent.available;
return (
<box flexDirection="row" marginBottom={1}>
<text
fg={
isSelected()
? terminalColors.accent
: available
? terminalColors.textSecondary
: terminalColors.textMuted
}
>
{isSelected() ? '▸ ' : ' '}
{agent.agent}
</text>
<text fg={available ? terminalColors.success : terminalColors.error}>
{' '}
{available ? '●' : '○'}
</text>
</box>
);
}}
</For>
<Show when={agentsWindow().start + MAX_VISIBLE < agents().length}>
<text fg={terminalColors.textMuted}> ▼ {agents().length - agentsWindow().start - MAX_VISIBLE} more</text>
</Show>
</Show>
</box>
</box>
) : (
<box flexDirection="column">
<text fg={terminalColors.text}>Select a skill to execute:</text>
<text> </text>
<text fg={terminalColors.textMuted}>─────────────────────────────────────────────</text>
<text> </text>
<Show when={selectedSkill() && selectedAgent()}>
<box flexDirection="row">
<text fg={terminalColors.textMuted}>Selected: </text>
<text fg={terminalColors.accent}>{selectedSkill()!.name}</text>
<text fg={terminalColors.textMuted}> → </text>
<text
fg={
selectedAgent()!.available
? terminalColors.accent
: terminalColors.textMuted
}
>
{selectedAgent()!.agent}
</text>
<Show when={!selectedAgent()!.available}>
<text fg={terminalColors.warning}> (unavailable)</text>
</Show>
</box>
</Show>
<Show when={executing()}>
<text> </text>
<text fg={terminalColors.textMuted}>
No skills available. Install skills first using 'b' (browse) or 'm' (marketplace).
</text>
<StatusIndicator status="loading" label="Executing skill..." />
</Show>
<Show when={executionResult() && !executing()}>
<text> </text>
<text fg={terminalColors.textMuted}>
Press Enter to execute, 'i' to view installed skills
<text fg={terminalColors.textMuted}>─────────────────────────────────────────────</text>
<text
fg={
executionResult()!.success
? terminalColors.success
: terminalColors.error
}
>
{executionResult()!.success ? '✓ Execution completed' : '✗ Execution failed'}
</text>
</box>
)}
<Show when={executionResult()!.error}>
<text fg={terminalColors.error}>{executionResult()!.error}</text>
</Show>
<Show when={executionResult()!.output}>
<text fg={terminalColors.textMuted}>
{executionResult()!.output.slice(0, 200)}
{executionResult()!.output.length > 200 ? '...' : ''}
</text>
</Show>
</Show>
<text> </text>
<text fg={terminalColors.textMuted}>
Tab/←/→ switch pane j/k navigate Enter execute r refresh Esc back
</text>
</Show>
</box>
);
}
+61 -45
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useMemo } from 'react';
import { createSignal, createEffect, onCleanup, createMemo, Show, For } from 'solid-js';
import { type Screen } from '../state/index.js';
import { terminalColors } from '../theme/colors.js';
import { getVersion } from '../utils/helpers.js';
@@ -44,84 +44,100 @@ const SHORTCUTS = [
]},
];
function ShortcutSection({ section, items, isLast }: { section: string; items: { key: string; desc: string }[]; isLast: boolean }) {
interface ShortcutSectionProps {
section: string;
items: { key: string; desc: string }[];
isLast: boolean;
}
function ShortcutSection(props: ShortcutSectionProps) {
return (
<box flexDirection="column">
<text fg={terminalColors.text}>{section}</text>
{items.map((item) => (
<box key={item.key} flexDirection="row">
<text fg={terminalColors.accent} width={8}> {item.key}</text>
<text fg={terminalColors.textMuted}>{item.desc}</text>
</box>
))}
{!isLast && <text> </text>}
<text fg={terminalColors.text}>{props.section}</text>
<For each={props.items}>
{(item) => (
<box flexDirection="row">
<text fg={terminalColors.accent} width={8}> {item.key}</text>
<text fg={terminalColors.textMuted}>{item.desc}</text>
</box>
)}
</For>
<Show when={!props.isLast}>
<text> </text>
</Show>
</box>
);
}
export function Help({ cols = 80 }: HelpProps) {
const [animPhase, setAnimPhase] = useState(0);
const isCompact = cols < 60;
const rawWidth = cols - 4;
const contentWidth = Math.max(1, Math.min(rawWidth, 60));
export function Help(props: HelpProps) {
const [animPhase, setAnimPhase] = createSignal(0);
const cols = () => props.cols ?? 80;
const isCompact = () => cols() < 60;
const rawWidth = () => cols() - 4;
const contentWidth = () => Math.max(1, Math.min(rawWidth(), 60));
const version = getVersion();
useEffect(() => {
if (animPhase >= 2) return;
createEffect(() => {
if (animPhase() >= 2) return;
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
return () => clearTimeout(timer);
}, [animPhase]);
onCleanup(() => clearTimeout(timer));
});
const divider = useMemo(() =>
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
[contentWidth]
const divider = createMemo(() =>
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth())}</text>
);
return (
<box flexDirection="column" padding={1}>
{animPhase >= 1 && (
<Show when={animPhase() >= 1}>
<box flexDirection="column">
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
<box flexDirection="row" justifyContent="space-between" width={contentWidth()}>
<text fg={terminalColors.text}>/ Help</text>
<text fg={terminalColors.textMuted}>skillkit v{version}</text>
</box>
<text fg={terminalColors.textMuted}>keyboard shortcuts and navigation</text>
<text> </text>
</box>
)}
</Show>
{animPhase >= 2 && (
<Show when={animPhase() >= 2}>
<box flexDirection="column">
{divider}
{divider()}
<text> </text>
{isCompact ? (
SHORTCUTS.map((s, idx) => (
<ShortcutSection key={s.section} section={s.section} items={s.items} isLast={idx === SHORTCUTS.length - 1} />
))
) : (
<Show when={isCompact()} fallback={
<box flexDirection="row">
<box flexDirection="column" width={Math.floor(contentWidth / 2)}>
{SHORTCUTS.slice(0, 2).map((s, idx) => (
<ShortcutSection key={s.section} section={s.section} items={s.items} isLast={idx === 1} />
))}
<box flexDirection="column" width={Math.floor(contentWidth() / 2)}>
<For each={SHORTCUTS.slice(0, 2)}>
{(s, idx) => (
<ShortcutSection section={s.section} items={s.items} isLast={idx() === 1} />
)}
</For>
</box>
<box flexDirection="column" width={Math.floor(contentWidth / 2)}>
{SHORTCUTS.slice(2).map((s, idx) => (
<ShortcutSection key={s.section} section={s.section} items={s.items} isLast={idx === 1} />
))}
<box flexDirection="column" width={Math.floor(contentWidth() / 2)}>
<For each={SHORTCUTS.slice(2)}>
{(s, idx) => (
<ShortcutSection section={s.section} items={s.items} isLast={idx() === 1} />
)}
</For>
</box>
</box>
)}
}>
<For each={SHORTCUTS}>
{(s, idx) => (
<ShortcutSection section={s.section} items={s.items} isLast={idx() === SHORTCUTS.length - 1} />
)}
</For>
</Show>
<text> </text>
</box>
)}
</Show>
{animPhase >= 2 && (
<Show when={animPhase() >= 2}>
<box flexDirection="column">
{divider}
{divider()}
<text fg={terminalColors.textMuted}>esc back h home q quit</text>
</box>
)}
</Show>
</box>
);
}
+21 -22
View File
@@ -1,7 +1,4 @@
/**
* History Screen
* Execution history
*/
import { For } from 'solid-js';
import { type Screen } from '../state/index.js';
import { terminalColors } from '../theme/colors.js';
import { Header } from '../components/Header.js';
@@ -12,7 +9,7 @@ interface HistoryProps {
rows?: number;
}
export function History({ onNavigate, cols = 80, rows = 24 }: HistoryProps) {
export function History(props: HistoryProps) {
const history = [
{ skill: 'tdd-workflow', time: '10:32 AM', duration: '2.3s', status: 'success' },
{ skill: 'code-review', time: '10:15 AM', duration: '5.1s', status: 'success' },
@@ -32,23 +29,25 @@ export function History({ onNavigate, cols = 80, rows = 24 }: HistoryProps) {
<text fg={terminalColors.text}><b>Recent Executions</b></text>
<text> </text>
{history.map((item, idx) => (
<box key={`${item.skill}-${item.time}`} flexDirection="row" marginBottom={1}>
<text
fg={idx === 0 ? terminalColors.accent : terminalColors.text}
width={18}
>
{idx === 0 ? '\u25B8 ' : ' '}{item.skill}
</text>
<text fg={terminalColors.textMuted} width={12}>{item.time}</text>
<text fg={terminalColors.textMuted} width={10}>{item.duration}</text>
<text
fg={item.status === 'success' ? terminalColors.success : terminalColors.error}
>
{item.status === 'success' ? '\u2713 success' : '\u2717 failed'}
</text>
</box>
))}
<For each={history}>
{(item, idx) => (
<box flexDirection="row" marginBottom={1}>
<text
fg={idx() === 0 ? terminalColors.accent : terminalColors.text}
width={18}
>
{idx() === 0 ? '\u25B8 ' : ' '}{item.skill}
</text>
<text fg={terminalColors.textMuted} width={12}>{item.time}</text>
<text fg={terminalColors.textMuted} width={10}>{item.duration}</text>
<text
fg={item.status === 'success' ? terminalColors.success : terminalColors.error}
>
{item.status === 'success' ? '\u2713 success' : '\u2717 failed'}
</text>
</box>
)}
</For>
<text> </text>
<text fg={terminalColors.textMuted}>
+100 -67
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useMemo } from 'react';
import { createSignal, createEffect, onCleanup, createMemo, Show, For } from 'solid-js';
import { type Screen, loadSkills, TOTAL_AGENTS } from '../state/index.js';
import { terminalColors } from '../theme/colors.js';
import { symbols, AGENT_LOGOS } from '../theme/symbols.js';
@@ -19,24 +19,25 @@ const FEATURES = [
{ key: 'Team', color: terminalColors.text, desc: 'collaborate' },
];
export function Home({ cols = 80 }: HomeProps) {
const [animPhase, setAnimPhase] = useState(0);
const [stats, setStats] = useState({ skills: 0, agents: TOTAL_AGENTS, synced: 0 });
const [detectedAgents, setDetectedAgents] = useState<string[]>([]);
export function Home(props: HomeProps) {
const [animPhase, setAnimPhase] = createSignal(0);
const [stats, setStats] = createSignal({ skills: 0, agents: TOTAL_AGENTS, synced: 0 });
const [detectedAgents, setDetectedAgents] = createSignal<string[]>([]);
const cols = () => props.cols ?? 80;
const version = getVersion();
const isCompact = cols < 70;
const isNarrow = cols < 50;
const contentWidth = Math.min(cols - 4, 55);
const line = '─'.repeat(contentWidth);
const isCompact = () => cols() < 70;
const isNarrow = () => cols() < 50;
const contentWidth = () => Math.min(cols() - 4, 55);
const line = () => '─'.repeat(contentWidth());
useEffect(() => {
if (animPhase >= 5) return;
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
return () => clearTimeout(timer);
}, [animPhase]);
createEffect(() => {
if (animPhase() >= 5) return;
const timer = setTimeout(() => setAnimPhase((p) => p + 1), 100);
onCleanup(() => clearTimeout(timer));
});
useEffect(() => {
createEffect(() => {
const skillsData = loadSkills();
setStats({
skills: skillsData.skills.length,
@@ -44,112 +45,144 @@ export function Home({ cols = 80 }: HomeProps) {
synced: Math.min(skillsData.skills.length, 3),
});
setDetectedAgents(['claude-code', 'cursor', 'github-copilot']);
}, []);
});
const visibleAgents = useMemo(() => {
const visibleAgents = createMemo(() => {
const allAgents = Object.entries(AGENT_LOGOS);
const perRow = isNarrow || isCompact ? 2 : 3;
const maxAgents = isNarrow ? 4 : isCompact ? 6 : 9;
const perRow = isNarrow() || isCompact() ? 2 : 3;
const maxAgents = isNarrow() ? 4 : isCompact() ? 6 : 9;
return {
agents: allAgents.slice(0, maxAgents),
perRow,
remaining: allAgents.length - maxAgents,
};
}, [isCompact, isNarrow]);
});
const getAgentWidth = () => {
if (isNarrow) return 22;
if (isCompact) return 26;
if (isNarrow()) return 22;
if (isCompact()) return 26;
return 18;
};
const agentRows = createMemo(() => {
const { agents, perRow } = visibleAgents();
const rows: typeof agents[] = [];
for (let i = 0; i < agents.length; i += perRow) {
rows.push(agents.slice(i, i + perRow));
}
return rows;
});
return (
<box flexDirection="column" padding={1}>
{animPhase >= 1 && (
<Show when={animPhase() >= 1}>
<box flexDirection="column">
<box flexDirection="row">
<text fg={terminalColors.text}>{symbols.brandIcon} skillkit</text>
<text fg={terminalColors.text}>
{symbols.brandIcon} skillkit
</text>
<text fg={terminalColors.textMuted}> v{version}</text>
</box>
<text fg={terminalColors.textMuted}>universal skills for ai coding agents</text>
<text> </text>
</box>
)}
</Show>
{animPhase >= 2 && (
<Show when={animPhase() >= 2}>
<box flexDirection="column">
<text fg={terminalColors.textMuted}>{line}</text>
<text fg={terminalColors.textMuted}>{line()}</text>
<text> </text>
<box flexDirection="row">
<box width={14}><text fg={terminalColors.accent}>{stats.skills}</text></box>
<box width={14}><text fg={terminalColors.text}>{stats.agents}</text></box>
<box width={14}><text fg={terminalColors.text}>{stats.synced}</text></box>
<box width={14}>
<text fg={terminalColors.accent}>{stats().skills}</text>
</box>
<box width={14}>
<text fg={terminalColors.text}>{stats().agents}</text>
</box>
<box width={14}>
<text fg={terminalColors.text}>{stats().synced}</text>
</box>
</box>
<box flexDirection="row">
<text fg={terminalColors.textMuted} width={14}>skills</text>
<text fg={terminalColors.textMuted} width={14}>agents</text>
<text fg={terminalColors.textMuted} width={14}>synced</text>
<text fg={terminalColors.textMuted} width={14}>
skills
</text>
<text fg={terminalColors.textMuted} width={14}>
agents
</text>
<text fg={terminalColors.textMuted} width={14}>
synced
</text>
</box>
<text> </text>
<text fg={terminalColors.textMuted}>{line}</text>
<text fg={terminalColors.textMuted}>{line()}</text>
<text> </text>
</box>
)}
</Show>
{animPhase >= 3 && (
<Show when={animPhase() >= 3}>
<box flexDirection="column">
<text fg={terminalColors.text}>Works with</text>
<text> </text>
{Array(Math.ceil(visibleAgents.agents.length / visibleAgents.perRow))
.fill(0)
.map((_, rowIdx) => (
<box key={rowIdx} flexDirection="row">
{visibleAgents.agents
.slice(rowIdx * visibleAgents.perRow, (rowIdx + 1) * visibleAgents.perRow)
.map(([type, agent]) => {
const isDetected = detectedAgents.includes(type);
<For each={agentRows()}>
{(row) => (
<box flexDirection="row">
<For each={row}>
{([type, agent]) => {
const isDetected = () => detectedAgents().includes(type);
return (
<box key={type} width={getAgentWidth()} flexDirection="row">
<text fg={terminalColors.text}>{agent.icon} {agent.name} </text>
<text fg={isDetected ? terminalColors.accent : terminalColors.textMuted}>
{isDetected ? '●' : '○'}
<box width={getAgentWidth()} flexDirection="row">
<text fg={terminalColors.text}>
{agent.icon} {agent.name}{' '}
</text>
<text fg={isDetected() ? terminalColors.accent : terminalColors.textMuted}>
{isDetected() ? '●' : '○'}
</text>
</box>
);
})}
}}
</For>
</box>
))}
{visibleAgents.remaining > 0 && (
<text fg={terminalColors.textMuted}>+{visibleAgents.remaining} more</text>
)}
)}
</For>
<Show when={visibleAgents().remaining > 0}>
<text fg={terminalColors.textMuted}>+{visibleAgents().remaining} more</text>
</Show>
<text> </text>
<text fg={terminalColors.textMuted}>{line}</text>
<text fg={terminalColors.textMuted}>{line()}</text>
<text> </text>
</box>
)}
</Show>
{animPhase >= 4 && (
<Show when={animPhase() >= 4}>
<box flexDirection="column">
<text fg={terminalColors.text}>Features</text>
<text> </text>
{FEATURES.map((feat) => (
<box key={feat.key} flexDirection="row">
<text fg={feat.color} width={12}> {feat.key}</text>
<text fg={terminalColors.textMuted}>{feat.desc}</text>
</box>
))}
<For each={FEATURES}>
{(feat) => (
<box flexDirection="row">
<text fg={feat.color} width={12}>
{' '}
{feat.key}
</text>
<text fg={terminalColors.textMuted}>{feat.desc}</text>
</box>
)}
</For>
<text> </text>
</box>
)}
</Show>
{animPhase >= 5 && (
<Show when={animPhase() >= 5}>
<box flexDirection="column">
<text fg={terminalColors.textMuted}>{line}</text>
<text fg={terminalColors.textMuted}>{line()}</text>
<text fg={terminalColors.textMuted}>
{isCompact ? 'b browse m market / help q quit' : 'b browse m market i installed / help q quit'}
{isCompact()
? 'b browse m market / help q quit'
: 'b browse m market i installed / help q quit'}
</text>
</box>
)}
</Show>
</box>
);
}
+139 -141
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useMemo, useCallback } from 'react';
import { useKeyboard } from '@opentui/react';
import { createSignal, createEffect, onCleanup, createMemo, Show, For } from 'solid-js';
import { useKeyboard } from '@opentui/solid';
import { type Screen, loadSkills, filterSkills } from '../state/index.js';
import { terminalColors } from '../theme/colors.js';
@@ -11,75 +11,69 @@ interface InstalledProps {
const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
export function Installed({ onNavigate, cols = 80, rows = 24 }: InstalledProps) {
const [selectedIndex, setSelectedIndex] = useState(0);
const [searchQuery, setSearchQuery] = useState('');
const [searchMode, setSearchMode] = useState(false);
const [animPhase, setAnimPhase] = useState(0);
const [spinnerFrame, setSpinnerFrame] = useState(0);
const [skills, setSkills] = useState<ReturnType<typeof loadSkills>>({
export function Installed(props: InstalledProps) {
const [selectedIndex, setSelectedIndex] = createSignal(0);
const [searchQuery, setSearchQuery] = createSignal('');
const [searchMode, setSearchMode] = createSignal(false);
const [animPhase, setAnimPhase] = createSignal(0);
const [spinnerFrame, setSpinnerFrame] = createSignal(0);
const [skills, setSkills] = createSignal<ReturnType<typeof loadSkills>>({
skills: [],
loading: true,
error: null,
});
const isCompact = cols < 60;
const contentWidth = Math.max(1, Math.min(cols - 4, 60));
const cols = () => props.cols ?? 80;
const rows = () => props.rows ?? 24;
const isCompact = () => cols() < 60;
const contentWidth = () => Math.max(1, Math.min(cols() - 4, 60));
// Entrance animation
useEffect(() => {
if (animPhase >= 2) return;
const timer = setTimeout(() => setAnimPhase(p => p + 1), 100);
return () => clearTimeout(timer);
}, [animPhase]);
createEffect(() => {
if (animPhase() >= 2) return;
const timer = setTimeout(() => setAnimPhase((p) => p + 1), 100);
onCleanup(() => clearTimeout(timer));
});
// Loading spinner
useEffect(() => {
if (!skills.loading) return;
createEffect(() => {
if (!skills().loading) return;
const interval = setInterval(() => {
setSpinnerFrame(f => (f + 1) % SPINNER.length);
setSpinnerFrame((f) => (f + 1) % SPINNER.length);
}, 80);
return () => clearInterval(interval);
}, [skills.loading]);
onCleanup(() => clearInterval(interval));
});
// Load skills
useEffect(() => {
createEffect(() => {
const data = loadSkills();
setSkills(data);
}, []);
});
const filteredSkills = useMemo(() =>
filterSkills(skills.skills, searchQuery),
[skills.skills, searchQuery]
);
const filteredSkills = createMemo(() => filterSkills(skills().skills, searchQuery()));
const handleKeyNav = useCallback((delta: number) => {
setSelectedIndex(prev => Math.max(0, Math.min(prev + delta, filteredSkills.length - 1)));
}, [filteredSkills.length]);
const handleKeyNav = (delta: number) => {
setSelectedIndex((prev) => Math.max(0, Math.min(prev + delta, filteredSkills().length - 1)));
};
const handleToggle = useCallback(() => {
if (filteredSkills.length === 0) return;
const skill = filteredSkills[selectedIndex];
const handleToggle = () => {
if (filteredSkills().length === 0) return;
const skill = filteredSkills()[selectedIndex()];
if (skill) {
setSkills(prev => ({
setSkills((prev) => ({
...prev,
skills: prev.skills.map(s =>
s.name === skill.name ? { ...s, enabled: s.enabled === false } : s
),
skills: prev.skills.map((s) => (s.name === skill.name ? { ...s, enabled: s.enabled === false } : s)),
}));
}
}, [filteredSkills, selectedIndex]);
};
const handleKeyboard = useCallback((key: { name?: string; sequence?: string }) => {
if (searchMode) {
useKeyboard((key: { name?: string; sequence?: string }) => {
if (searchMode()) {
if (key.name === 'escape') {
setSearchMode(false);
} else if (key.name === 'backspace') {
setSearchQuery(prev => prev.slice(0, -1));
setSearchQuery((prev) => prev.slice(0, -1));
} else if (key.name === 'return') {
setSearchMode(false);
} else if (key.sequence && key.sequence.length === 1 && /[a-zA-Z0-9\-_.]/.test(key.sequence)) {
setSearchQuery(prev => prev + key.sequence);
setSearchQuery((prev) => prev + key.sequence);
setSelectedIndex(0);
}
return;
@@ -90,136 +84,140 @@ export function Installed({ onNavigate, cols = 80, rows = 24 }: InstalledProps)
else if (key.sequence === '/') setSearchMode(true);
else if (key.name === 'return') handleToggle();
else if (key.name === 'd') handleToggle();
else if (key.name === 'escape') onNavigate('home');
}, [searchMode, handleKeyNav, handleToggle, onNavigate]);
else if (key.name === 'escape') props.onNavigate('home');
});
useKeyboard(handleKeyboard);
useEffect(() => {
if (selectedIndex >= filteredSkills.length && filteredSkills.length > 0) {
setSelectedIndex(filteredSkills.length - 1);
createEffect(() => {
if (selectedIndex() >= filteredSkills().length && filteredSkills().length > 0) {
setSelectedIndex(filteredSkills().length - 1);
}
}, [filteredSkills.length, selectedIndex]);
});
// Calculate visible items
const maxVisible = Math.max(5, rows - 10);
const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(maxVisible / 2), filteredSkills.length - maxVisible));
const visibleSkills = filteredSkills.slice(startIdx, startIdx + maxVisible);
const maxVisible = () => Math.max(5, rows() - 10);
const startIdx = () =>
Math.max(0, Math.min(selectedIndex() - Math.floor(maxVisible() / 2), filteredSkills().length - maxVisible()));
const visibleSkills = () => filteredSkills().slice(startIdx(), startIdx() + maxVisible());
const divider = useMemo(() =>
<text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth)}</text>,
[contentWidth]
);
const divider = () => <text fg={terminalColors.textMuted}>{'─'.repeat(contentWidth())}</text>;
// Stats
const enabledCount = skills.skills.filter(s => s.enabled !== false).length;
const totalCount = skills.skills.length;
const enabledCount = () => skills().skills.filter((s) => s.enabled !== false).length;
const totalCount = () => skills().skills.length;
const shortcuts = isCompact
? 'j/k nav enter toggle d disable esc back'
: 'j/k navigate enter toggle d disable esc back';
const shortcuts = () =>
isCompact()
? 'j/k nav enter toggle d disable esc back'
: 'j/k navigate enter toggle d disable esc back';
return (
<box flexDirection="column" padding={1}>
{/* Header */}
{animPhase >= 1 && (
<Show when={animPhase() >= 1}>
<box flexDirection="column">
<box flexDirection="row" justifyContent="space-between" width={contentWidth}>
<box flexDirection="row" justifyContent="space-between" width={contentWidth()}>
<text fg={terminalColors.success}>✓ Installed</text>
<text fg={terminalColors.textMuted}>{enabledCount}/{totalCount} active</text>
<text fg={terminalColors.textMuted}>
{enabledCount()}/{totalCount()} active
</text>
</box>
<text fg={terminalColors.textMuted}>manage your skills</text>
<text> </text>
</box>
)}
</Show>
{/* Search */}
{animPhase >= 2 && (
<Show when={animPhase() >= 2}>
<box flexDirection="column">
{divider}
{divider()}
<text> </text>
<box flexDirection="row">
<text fg={terminalColors.textMuted}>/ </text>
<text fg={searchQuery ? terminalColors.text : terminalColors.textMuted}>
{searchQuery || 'type to filter...'}
<text fg={searchQuery() ? terminalColors.text : terminalColors.textMuted}>
{searchQuery() || 'type to filter...'}
</text>
</box>
<text> </text>
{divider}
{divider()}
<text> </text>
</box>
)}
</Show>
{/* Skills list */}
{animPhase >= 2 && (
<Show when={animPhase() >= 2}>
<box flexDirection="column">
{skills.loading ? (
<box flexDirection="row">
<text fg={terminalColors.accent}>{SPINNER[spinnerFrame]} </text>
<text fg={terminalColors.text}>Loading skills...</text>
</box>
) : skills.error ? (
<box flexDirection="column">
<text fg={terminalColors.error}>✗ Error loading skills</text>
<text fg={terminalColors.textMuted}>{skills.error}</text>
</box>
) : filteredSkills.length === 0 ? (
<box flexDirection="column">
<text fg={terminalColors.textMuted}>
{skills.skills.length === 0
? 'No skills installed yet'
: 'No skills match your search'}
</text>
{skills.skills.length === 0 && (
<>
<Show
when={!skills().loading}
fallback={
<box flexDirection="row">
<text fg={terminalColors.accent}>{SPINNER[spinnerFrame()]} </text>
<text fg={terminalColors.text}>Loading skills...</text>
</box>
}
>
<Show
when={!skills().error}
fallback={
<box flexDirection="column">
<text fg={terminalColors.error}>✗ Error loading skills</text>
<text fg={terminalColors.textMuted}>{skills().error}</text>
</box>
}
>
<Show
when={filteredSkills().length > 0}
fallback={
<box flexDirection="column">
<text fg={terminalColors.textMuted}>
{skills().skills.length === 0 ? 'No skills installed yet' : 'No skills match your search'}
</text>
<Show when={skills().skills.length === 0}>
<text> </text>
<text fg={terminalColors.textMuted}>Press 'b' to browse or 'm' for marketplace</text>
</Show>
</box>
}
>
<box flexDirection="column">
<text fg={terminalColors.text}>Skills</text>
<text> </text>
<text fg={terminalColors.textMuted}>
Press 'b' to browse or 'm' for marketplace
</text>
</>
)}
</box>
) : (
<box flexDirection="column">
<text fg={terminalColors.text}>Skills</text>
<text> </text>
{visibleSkills.map((skill, idx) => {
const actualIdx = startIdx + idx;
const selected = actualIdx === selectedIndex;
const indicator = selected ? '▸' : ' ';
const statusIcon = skill.enabled !== false ? '●' : '○';
const qualityBadge = skill.grade ? ` [${skill.grade}]` : '';
const warningIndicator = skill.warnings && skill.warnings > 2 ? ' ⚠' : '';
const line = `${indicator}${statusIcon} ${skill.name}${qualityBadge}${warningIndicator}`;
const badgeColor = skill.quality !== undefined
? (skill.quality >= 80 ? terminalColors.success : skill.quality >= 60 ? terminalColors.warning : terminalColors.error)
: terminalColors.text;
return (
<text key={skill.name} fg={selected ? terminalColors.accent : badgeColor}>
{line}
</text>
);
})}
<For each={visibleSkills()}>
{(skill, idx) => {
const actualIdx = () => startIdx() + idx();
const selected = () => actualIdx() === selectedIndex();
const indicator = () => (selected() ? '▸' : ' ');
const statusIcon = () => (skill.enabled !== false ? '●' : '○');
const qualityBadge = () => (skill.grade ? ` [${skill.grade}]` : '');
const warningIndicator = () => (skill.warnings && skill.warnings > 2 ? ' ⚠' : '');
const line = () =>
`${indicator()}${statusIcon()} ${skill.name}${qualityBadge()}${warningIndicator()}`;
const badgeColor = () =>
skill.quality !== undefined
? skill.quality >= 80
? terminalColors.success
: skill.quality >= 60
? terminalColors.warning
: terminalColors.error
: terminalColors.text;
return <text fg={selected() ? terminalColors.accent : badgeColor()}>{line()}</text>;
}}
</For>
{/* Scroll indicator */}
{filteredSkills.length > maxVisible && (
<text fg={terminalColors.textMuted}>
{'\n'}showing {startIdx + 1}-{Math.min(startIdx + maxVisible, filteredSkills.length)} of {filteredSkills.length}
</text>
)}
</box>
)}
<Show when={filteredSkills().length > maxVisible()}>
<text fg={terminalColors.textMuted}>
{'\n'}showing {startIdx() + 1}-{Math.min(startIdx() + maxVisible(), filteredSkills().length)} of{' '}
{filteredSkills().length}
</text>
</Show>
</box>
</Show>
</Show>
</Show>
<text> </text>
</box>
)}
</Show>
{/* Footer */}
{animPhase >= 2 && (
<Show when={animPhase() >= 2}>
<box flexDirection="column">
{divider}
<text fg={terminalColors.textMuted}>{shortcuts}</text>
{divider()}
<text fg={terminalColors.textMuted}>{shortcuts()}</text>
</box>
)}
</Show>
</box>
);
}

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