Compare commits

..
Author SHA1 Message Date
Rohit Ghumare b1f11cf847 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:44:39 +00:00
Rohit Ghumare 801ae1a15f 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
2026-01-30 22:43:24 +00:00
Rohit Ghumare 812d29c51b fix: address CodeRabbit review suggestions
- Add missing fs import to api-reference.mdx code examples
- Clarify that host comes from MeshHost in messaging example
- Remove broken /docs/registries link from teams.mdx
- Fix ARIA tab/panel linkage in AdvancedFeatures.tsx
2026-01-30 22:14:29 +00:00
Rohit Ghumare 95c2007a13 feat(docs): comprehensive documentation and website improvements
Website improvements:
- Add AdvancedFeatures component for Memory, Primer, Mesh, Messaging
- Add UseCases component with real-world scenarios
- Add TeamEnterprise component for collaboration features
- Update Hero section with better value proposition
- Make all components mobile responsive
- Pre-populate StackBuilder with default skills
- Add ARIA attributes for accessibility
- Add prefers-reduced-motion for smooth scrolling

Documentation updates:
- Create primer.mdx for auto-generate instructions feature
- Create teams.mdx for team collaboration documentation
- Enhance index.mdx with comprehensive feature overview
- Update quickstart.mdx with advanced features section
- Expand api-reference.mdx with Mesh, Messaging, Workflow APIs
- Update configuration.mdx with Memory, Mesh, Primer settings
- Simplify fumadocs homepage for cleaner presentation
- Fix markdown formatting issues
2026-01-30 21:51:03 +00:00
204 changed files with 2126 additions and 24362 deletions
+7 -82
View File
@@ -14,13 +14,10 @@
[![Website](https://img.shields.io/badge/Website-agenstskills.com-black)](https://agenstskills.com)
[![Docs](https://img.shields.io/badge/Docs-agenstskills.com/docs-blue)](https://agenstskills.com/docs)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![SKILL.md](https://img.shields.io/badge/SKILL.md-compatible-black?style=flat-square)](https://agenstskills.com)
## One Skill. Every Agent.
## Supercharge Every AI Coding Agent
**The package manager for AI agent skills. Install, translate, and share skills across 32 coding agents.**
> Think npm, but for AI agent skills. Write once, deploy to Claude Code, Cursor, Codex, Windsurf, Copilot, and 27 more.
**Give your AI agents new abilities with portable, reusable skills.** Install from a curated marketplace, create your own, and use them across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 27 more agents (32 total).
> **What are AI Agent Skills?** Skills are instruction files that teach AI coding agents how to handle specific tasks - like processing PDFs, following React best practices, or enforcing security patterns. Think of them as plugins for your AI assistant.
@@ -145,25 +142,8 @@ 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:
@@ -210,7 +190,7 @@ skillkit ui
skillkit
```
**Navigation:** `h` Home | `m` Marketplace | `b` Browse | `v` Tree View | `r` Recommend | `t` Translate | `c` Context | `l` List | `s` Sync | `q` Quit
**Navigation:** `h` Home | `b` Browse | `r` Recommend | `t` Translate | `c` Context | `l` List | `s` Sync | `q` Quit
### Skill Testing Framework
@@ -318,10 +298,6 @@ 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
@@ -452,31 +428,11 @@ skillkit methodology load # Load a methodology
### Publishing & Sharing
```bash
skillkit publish # Generate well-known hosting structure
skillkit publish submit # Submit to SkillKit marketplace
skillkit publish # Publish skill to 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
@@ -535,29 +491,8 @@ 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,
@@ -581,20 +516,10 @@ import {
const skill = await translateSkill(skillContent, 'cursor');
console.log(skill.content);
// Example: Get recommendations with reasoning
const engine = new ReasoningRecommendationEngine();
await engine.initReasoning();
// Example: Get recommendations
const engine = new RecommendationEngine();
const profile = await analyzeProject('./my-project');
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
const recs = engine.recommend(profile);
```
## Skill Sources & Attribution
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "skillkit",
"version": "1.12.0",
"version": "1.8.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": {
@@ -53,7 +53,6 @@
"node": ">=18.0.0"
},
"dependencies": {
"@skillkit/api": "workspace:*",
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"@skillkit/cli": "workspace:*",
-19
View File
@@ -48,12 +48,10 @@ import {
AICommand,
AuditCommand,
PublishCommand,
PublishSubmitCommand,
AgentCommand,
AgentListCommand,
AgentShowCommand,
AgentCreateCommand,
AgentFromSkillCommand,
AgentTranslateCommand,
AgentSyncCommand,
AgentValidateCommand,
@@ -97,12 +95,6 @@ import {
GuidelineDisableCommand,
GuidelineCreateCommand,
GuidelineRemoveCommand,
TreeCommand,
QuickCommand,
SkillMdValidateCommand,
SkillMdInitCommand,
SkillMdCheckCommand,
ServeCommand,
} from '@skillkit/cli';
const __filename = fileURLToPath(import.meta.url);
@@ -157,12 +149,10 @@ 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);
@@ -223,13 +213,4 @@ cli.register(GuidelineDisableCommand);
cli.register(GuidelineCreateCommand);
cli.register(GuidelineRemoveCommand);
cli.register(TreeCommand);
cli.register(QuickCommand);
cli.register(SkillMdValidateCommand);
cli.register(SkillMdInitCommand);
cli.register(SkillMdCheckCommand);
cli.register(ServeCommand);
cli.runExit(process.argv.slice(2));
-42
View File
@@ -1,42 +0,0 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "skillkit-client"
version = "0.1.0"
description = "Python client for the SkillKit REST API"
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.9"
authors = [
{ name = "Rohit Ghumare", email = "ghumare64@gmail.com" },
]
keywords = ["skillkit", "ai", "agents", "skills", "discovery"]
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Topic :: Software Development :: Libraries",
]
dependencies = [
"httpx>=0.27",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0",
"pytest-asyncio>=0.23",
"respx>=0.21",
]
[project.urls]
Homepage = "https://github.com/rohitg00/skillkit"
Documentation = "https://agenstskills.com"
Repository = "https://github.com/rohitg00/skillkit"
-12
View File
@@ -1,12 +0,0 @@
from skillkit.client import SkillKitClient
from skillkit.models import Skill, SearchResponse, HealthResponse, CacheStats, Category
__all__ = [
"SkillKitClient",
"Skill",
"SearchResponse",
"HealthResponse",
"CacheStats",
"Category",
]
__version__ = "0.1.0"
-140
View File
@@ -1,140 +0,0 @@
from __future__ import annotations
from typing import Optional
from urllib.parse import quote
import httpx
from skillkit.models import (
CacheStats,
CategoriesResponse,
Category,
HealthResponse,
SearchResponse,
Skill,
TrendingResponse,
)
class SkillKitClient:
def __init__(self, base_url: str = "http://localhost:3737", timeout: float = 30.0):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self._client: Optional[httpx.AsyncClient] = None
async def __aenter__(self) -> "SkillKitClient":
self._client = httpx.AsyncClient(base_url=self.base_url, timeout=self.timeout)
return self
async def __aexit__(self, *args: object) -> None:
if self._client:
await self._client.aclose()
self._client = None
def _get_client(self) -> httpx.AsyncClient:
if self._client is None:
self._client = httpx.AsyncClient(base_url=self.base_url, timeout=self.timeout)
return self._client
async def health(self) -> HealthResponse:
client = self._get_client()
response = await client.get("/health")
response.raise_for_status()
data = response.json()
return HealthResponse(
status=data["status"],
version=data["version"],
skill_count=data.get("skillCount", 0),
uptime=data.get("uptime", 0),
)
async def search(
self,
query: str,
limit: int = 20,
include_content: bool = False,
) -> SearchResponse:
client = self._get_client()
params = {"q": query, "limit": str(limit)}
if include_content:
params["include_content"] = "true"
response = await client.get("/search", params=params)
response.raise_for_status()
data = response.json()
return SearchResponse(
skills=[Skill(**s) for s in data["skills"]],
total=data["total"],
query=data["query"],
limit=data["limit"],
)
async def search_with_filters(
self,
query: str,
limit: int = 20,
include_content: bool = False,
tags: Optional[list[str]] = None,
category: Optional[str] = None,
source: Optional[str] = None,
) -> SearchResponse:
client = self._get_client()
body: dict = {"query": query, "limit": limit, "include_content": include_content}
filters: dict = {}
if tags:
filters["tags"] = tags
if category:
filters["category"] = category
if source:
filters["source"] = source
if filters:
body["filters"] = filters
response = await client.post("/search", json=body)
response.raise_for_status()
data = response.json()
return SearchResponse(
skills=[Skill(**s) for s in data["skills"]],
total=data["total"],
query=data["query"],
limit=data["limit"],
)
async def get_skill(self, source: str, skill_id: str) -> Skill:
client = self._get_client()
parts = source.split("/", 1)
owner = quote(parts[0], safe="")
repo = quote(parts[1], safe="") if len(parts) > 1 else owner
response = await client.get(f"/skills/{owner}/{repo}/{quote(skill_id, safe='')}")
response.raise_for_status()
return Skill(**response.json())
async def trending(self, limit: int = 20) -> list[Skill]:
client = self._get_client()
response = await client.get("/trending", params={"limit": str(limit)})
response.raise_for_status()
data = response.json()
return [Skill(**s) for s in data["skills"]]
async def categories(self) -> list[Category]:
client = self._get_client()
response = await client.get("/categories")
response.raise_for_status()
data = response.json()
return [Category(**c) for c in data["categories"]]
async def cache_stats(self) -> CacheStats:
client = self._get_client()
response = await client.get("/cache/stats")
response.raise_for_status()
data = response.json()
return CacheStats(
hits=data["hits"],
misses=data["misses"],
size=data["size"],
max_size=data.get("maxSize", 0),
hit_rate=data.get("hitRate", 0.0),
)
async def close(self) -> None:
if self._client:
await self._client.aclose()
self._client = None
-51
View File
@@ -1,51 +0,0 @@
from typing import Optional
from pydantic import BaseModel
class Skill(BaseModel):
name: str
description: Optional[str] = None
source: str
repo: Optional[str] = None
tags: Optional[list[str]] = None
category: Optional[str] = None
content: Optional[str] = None
stars: Optional[int] = None
installs: Optional[int] = None
class SearchResponse(BaseModel):
skills: list[Skill]
total: int
query: str
limit: int
class HealthResponse(BaseModel):
status: str
version: str
skill_count: int = 0
uptime: int = 0
class CacheStats(BaseModel):
hits: int
misses: int
size: int
max_size: int = 0
hit_rate: float = 0.0
class Category(BaseModel):
name: str
count: int
class CategoriesResponse(BaseModel):
categories: list[Category]
total: int
class TrendingResponse(BaseModel):
skills: list[Skill]
limit: int
View File
-99
View File
@@ -1,99 +0,0 @@
import pytest
import httpx
import respx
from skillkit import SkillKitClient
BASE_URL = "http://localhost:3737"
@pytest.fixture
def mock_api():
with respx.mock(base_url=BASE_URL) as respx_mock:
yield respx_mock
@pytest.mark.asyncio
async def test_health(mock_api):
mock_api.get("/health").respond(
json={"status": "ok", "version": "1.11.0", "skillCount": 100, "uptime": 60}
)
async with SkillKitClient(BASE_URL) as client:
health = await client.health()
assert health.status == "ok"
assert health.version == "1.11.0"
assert health.skill_count == 100
@pytest.mark.asyncio
async def test_search(mock_api):
mock_api.get("/search").respond(
json={
"skills": [{"name": "react-perf", "source": "owner/repo"}],
"total": 1,
"query": "react",
"limit": 20,
}
)
async with SkillKitClient(BASE_URL) as client:
result = await client.search("react")
assert result.total == 1
assert result.skills[0].name == "react-perf"
@pytest.mark.asyncio
async def test_search_with_filters(mock_api):
mock_api.post("/search").respond(
json={
"skills": [{"name": "nextjs-auth", "source": "other/repo"}],
"total": 1,
"query": "auth",
"limit": 20,
}
)
async with SkillKitClient(BASE_URL) as client:
result = await client.search_with_filters("auth", tags=["nextjs"])
assert result.total == 1
@pytest.mark.asyncio
async def test_get_skill(mock_api):
mock_api.get("/skills/owner/repo/react-perf").respond(
json={"name": "react-perf", "description": "React performance", "source": "owner/repo"}
)
async with SkillKitClient(BASE_URL) as client:
skill = await client.get_skill("owner/repo", "react-perf")
assert skill.name == "react-perf"
@pytest.mark.asyncio
async def test_trending(mock_api):
mock_api.get("/trending").respond(
json={"skills": [{"name": "a", "source": "x/y"}], "limit": 20}
)
async with SkillKitClient(BASE_URL) as client:
trending = await client.trending()
assert len(trending) == 1
@pytest.mark.asyncio
async def test_categories(mock_api):
mock_api.get("/categories").respond(
json={"categories": [{"name": "react", "count": 5}], "total": 1}
)
async with SkillKitClient(BASE_URL) as client:
cats = await client.categories()
assert len(cats) == 1
assert cats[0].name == "react"
@pytest.mark.asyncio
async def test_cache_stats(mock_api):
mock_api.get("/cache/stats").respond(
json={"hits": 10, "misses": 5, "size": 8, "maxSize": 500, "hitRate": 0.667}
)
async with SkillKitClient(BASE_URL) as client:
stats = await client.cache_stats()
assert stats.hits == 10
assert stats.size == 8
+1 -9
View File
@@ -233,18 +233,10 @@ 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
+1 -32
View File
@@ -48,39 +48,8 @@ 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
# Generate hosting structure
skillkit publish ./my-skill --output ./public
skillkit publish
```
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,7 +9,6 @@
"agents",
"translation",
"marketplace",
"tree",
"recommendations",
"primer",
"memory",
+1 -41
View File
@@ -32,33 +32,6 @@ 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:
@@ -77,22 +50,9 @@ Scores based on:
## Programmatic API
```typescript
import {
RecommendationEngine,
ReasoningRecommendationEngine,
analyzeProject
} from '@skillkit/core'
import { RecommendationEngine, 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
})
```
+2 -18
View File
@@ -94,22 +94,6 @@ Or manually create a `SKILL.md` file following the format above.
# Test locally
skillkit validate ./my-skill
# Generate well-known hosting structure for self-hosting
skillkit publish ./my-skill --output ./public
# Or submit to SkillKit marketplace
skillkit publish submit
# Publish to marketplace
skillkit publish
```
### 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
@@ -1,144 +0,0 @@
---
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)
```
+9 -41
View File
@@ -18,12 +18,10 @@ skillkit
## Framework
Built on modern technologies:
- **@opentui/solid** - Terminal rendering with Solid.js
- **Solid.js 1.9.0** - Reactive component architecture
- **@opentui/react** - Terminal rendering
- **React 19.0.0** - 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 |
@@ -105,20 +103,6 @@ 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
@@ -175,10 +159,8 @@ loadSkills()
### Performance Optimizations
- `createMemo` for filtered lists and computed values
- `createSignal` for reactive state management
- `createEffect` for side effects and subscriptions
- Windowed list rendering for large datasets
- `useMemo` for filtered lists
- `useCallback` for event handlers
- Pagination limits rendered items
- Progressive animation with phases
@@ -192,32 +174,18 @@ loadSkills()
## Integration
The TUI integrates with @skillkit/core using Solid.js reactive patterns:
The TUI integrates with @skillkit/core:
```typescript
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()))
);
findAllSkills(searchDirs) // Returns skill metadata
evaluateSkillDirectory(path) // Quality metrics
getQualityGrade(score) // 0-100 to A-F
```
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. Runs Solid.js cleanup functions (`onCleanup`)
1. Unmounts React components
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.12.0",
"version": "1.8.0",
"private": true,
"scripts": {
"build": "next build",
+4 -33
View File
@@ -12,9 +12,6 @@ import { Attribution } from './components/Attribution';
import { AdvancedFeatures } from './components/AdvancedFeatures';
import { UseCases } from './components/UseCases';
import { TeamEnterprise } from './components/TeamEnterprise';
import { BadgeGenerator } from './components/BadgeGenerator';
import { CompatibilityMatrix } from './components/CompatibilityMatrix';
import { useStats } from './hooks/useStats';
const GITHUB_ICON = (
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
@@ -37,8 +34,6 @@ function scrollToSection(e: React.MouseEvent, sectionId: string): void {
}
export default function App(): React.ReactElement {
const stats = useStats();
return (
<div className="min-h-screen text-zinc-100 font-sans selection:bg-white selection:text-black" style={{ backgroundColor: '#000000' }}>
<nav className="fixed top-0 left-0 right-0 z-50 border-b border-zinc-800 backdrop-blur-md" style={{ backgroundColor: 'rgba(0,0,0,0.9)' }}>
@@ -63,20 +58,6 @@ export default function App(): React.ReactElement {
>
Stack
</a>
<a
href="#matrix"
onClick={(e) => scrollToSection(e, 'matrix')}
className="text-zinc-500 hover:text-white transition-colors"
>
Matrix
</a>
<a
href="#badge"
onClick={(e) => scrollToSection(e, 'badge')}
className="text-zinc-500 hover:text-white transition-colors"
>
Badge
</a>
<a
href="#advanced"
onClick={(e) => scrollToSection(e, 'advanced')}
@@ -121,7 +102,7 @@ export default function App(): React.ReactElement {
</nav>
<main className="pt-14">
<Hero version={stats.version} />
<Hero />
<div className="border-b border-zinc-800/50 py-2.5" style={{ background: 'linear-gradient(to bottom, rgba(9,9,11,0.95), rgba(0,0,0,1))' }}>
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
@@ -133,7 +114,7 @@ export default function App(): React.ReactElement {
className="flex items-center gap-1.5 text-zinc-500 hover:text-white transition-colors group"
>
<span className="text-zinc-600 group-hover:text-zinc-400">v</span>
<span className="text-white font-medium">{stats.version}</span>
<span className="text-white font-medium">1.8.0</span>
</a>
<span className="text-zinc-800">·</span>
<a
@@ -145,7 +126,7 @@ export default function App(): React.ReactElement {
<svg className="w-3 h-3 text-zinc-600 group-hover:text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<span className="text-white font-medium">{stats.downloads}</span>
<span className="text-white font-medium">2.4k</span>
</a>
<span className="text-zinc-800">·</span>
<a
@@ -157,7 +138,7 @@ export default function App(): React.ReactElement {
<svg className="w-3 h-3 text-zinc-600 group-hover:text-yellow-500" fill="currentColor" viewBox="0 0 24 24">
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
</svg>
<span className="text-white font-medium">{stats.stars}</span>
<span className="text-white font-medium">66</span>
</a>
<span className="text-zinc-800 hidden sm:inline">·</span>
<a
@@ -188,16 +169,6 @@ export default function App(): React.ReactElement {
<StackBuilder />
</section>
{/* Compatibility Matrix */}
<section id="matrix" style={{ scrollMarginTop: '4rem' }}>
<CompatibilityMatrix />
</section>
{/* Badge Generator */}
<section id="badge" style={{ scrollMarginTop: '4rem' }}>
<BadgeGenerator />
</section>
{/* Advanced Capabilities: Memory, Primer, Mesh, Messaging */}
<section id="advanced" style={{ scrollMarginTop: '4rem' }}>
<AdvancedFeatures />
-201
View File
@@ -1,201 +0,0 @@
import React, { useState, useMemo } from 'react';
const SKILLKIT_LOGO_SVG_BASE64 =
'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0id2hpdGUiPjxyZWN0IHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHg9IjEiIHk9IjEiLz48cmVjdCB3aWR0aD0iNiIgaGVpZ2h0PSI2IiB4PSI5IiB5PSIxIi8+PHJlY3Qgd2lkdGg9IjYiIGhlaWdodD0iNiIgeD0iMSIgeT0iOSIvPjxyZWN0IHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHg9IjkiIHk9IjkiLz48L3N2Zz4=';
const SUGGESTED_SKILLS = [
'react', 'typescript', 'nextjs', 'python', 'docker',
'kubernetes', 'tailwind', 'graphql', 'prisma', 'langchain',
'openai', 'rust', 'go', 'vue', 'svelte',
'security', 'testing', 'cicd', 'aws', 'terraform',
];
function encodeBadgeSegment(text: string): string {
return encodeURIComponent(text).replace(/-/g, '--');
}
function buildBadgeUrl(skills: string[]): string {
if (skills.length === 0) {
return `https://img.shields.io/badge/SkillKit-No%20Skills-555555?style=flat-square&logo=data:image/svg+xml;base64,${SKILLKIT_LOGO_SVG_BASE64}`;
}
const maxDisplay = 5;
const displayNames = skills.slice(0, maxDisplay);
const suffix = skills.length > maxDisplay ? ` +${skills.length - maxDisplay} more` : '';
const label = `SkillKit ${skills.length} skills`;
const message = displayNames.join(' | ') + suffix;
return `https://img.shields.io/badge/${encodeBadgeSegment(label)}-${encodeBadgeSegment(message)}-black?style=flat-square&logo=data:image/svg+xml;base64,${SKILLKIT_LOGO_SVG_BASE64}`;
}
export function BadgeGenerator(): React.ReactElement {
const [skills, setSkills] = useState<string[]>(['react', 'typescript', 'nextjs']);
const [inputValue, setInputValue] = useState('');
const [copiedType, setCopiedType] = useState<string | null>(null);
const badgeUrl = useMemo(() => buildBadgeUrl(skills), [skills]);
const markdown = `[![SkillKit Stack](${badgeUrl})](https://agenstskills.com)`;
const html = `<a href="https://agenstskills.com"><img src="${badgeUrl}" alt="SkillKit Stack" /></a>`;
function addSkill(skill: string): void {
const trimmed = skill.trim().toLowerCase();
if (trimmed && !skills.includes(trimmed)) {
setSkills([...skills, trimmed]);
}
setInputValue('');
}
function removeSkill(skill: string): void {
setSkills(skills.filter(s => s !== skill));
}
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>): void {
if (e.key === 'Enter' && inputValue.trim()) {
e.preventDefault();
addSkill(inputValue);
}
}
async function copyToClipboard(text: string, type: string): Promise<void> {
try {
await navigator.clipboard.writeText(text);
setCopiedType(type);
setTimeout(() => setCopiedType(null), 2000);
} catch {
// silently ignore
}
}
const availableSuggestions = SUGGESTED_SKILLS.filter(s => !skills.includes(s));
return (
<section className="py-12 border-b border-zinc-800">
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
<div className="mb-6">
<h2 className="text-xl font-bold text-white mb-1 font-mono">Badge Generator</h2>
<p className="text-zinc-500 font-mono text-xs">
Create a shareable badge for your skill stack. Add it to your README.
</p>
</div>
<div className="flex flex-col lg:flex-row gap-6">
<div className="flex-1 space-y-4">
<div className="relative">
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Type a skill name and press Enter..."
className="w-full bg-zinc-900 border border-zinc-700 text-white px-4 py-3 focus:ring-2 focus:ring-white focus:border-transparent outline-none font-mono text-sm placeholder-zinc-600"
/>
</div>
<div className="space-y-2">
<span className="text-zinc-500 text-xs font-mono block">Quick add:</span>
<div className="flex flex-wrap gap-1.5">
{availableSuggestions.slice(0, 12).map(skill => (
<button
key={skill}
onClick={() => addSkill(skill)}
className="text-[10px] sm:text-xs bg-zinc-900 text-zinc-400 px-2 sm:px-3 py-1 sm:py-1.5 border border-zinc-700 hover:border-zinc-500 hover:text-white transition-colors font-mono"
>
+ {skill}
</button>
))}
</div>
</div>
{skills.length > 0 && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="text-xs font-mono text-zinc-500 uppercase tracking-wider">
Skills in Badge ({skills.length})
</div>
<button
onClick={() => setSkills([])}
className="text-zinc-500 hover:text-red-400 font-mono text-xs transition-colors"
>
Clear All
</button>
</div>
<div className="flex flex-wrap gap-2">
{skills.map(skill => (
<div
key={skill}
className="flex items-center gap-1.5 bg-zinc-900/50 border border-zinc-800 px-3 py-1.5 group"
>
<span className="font-mono text-sm text-white">{skill}</span>
<button
onClick={() => removeSkill(skill)}
aria-label={`Remove ${skill}`}
className="text-zinc-600 hover:text-red-400 transition-colors opacity-0 group-hover:opacity-100 focus-visible:opacity-100"
>
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
))}
</div>
</div>
)}
</div>
<div className="lg:w-80 lg:flex-shrink-0">
<div className="lg:sticky lg:top-20 bg-zinc-900/30 border border-zinc-800 p-4 space-y-4">
<div className="text-xs font-mono text-zinc-500 uppercase tracking-wider">Preview</div>
<div className="flex justify-center py-3 bg-black/50 border border-zinc-800">
{skills.length > 0 ? (
<img
src={badgeUrl}
alt="SkillKit Stack Badge"
className="h-5"
/>
) : (
<span className="text-zinc-600 text-xs font-mono">Add skills to preview</span>
)}
</div>
<div className="space-y-2">
<div className="text-xs font-mono text-zinc-500">Markdown</div>
<pre className="bg-black/50 p-2 overflow-x-auto text-[10px] border border-zinc-800">
<code className="font-mono text-zinc-300 whitespace-pre-wrap break-all">
{markdown}
</code>
</pre>
<button
onClick={() => copyToClipboard(markdown, 'markdown')}
className="w-full bg-zinc-800 text-zinc-300 py-1.5 font-mono text-xs hover:bg-zinc-700 hover:text-white transition-colors flex items-center justify-center gap-1.5 border border-zinc-700"
>
{copiedType === 'markdown' ? 'Copied!' : 'Copy Markdown'}
</button>
</div>
<div className="space-y-2">
<div className="text-xs font-mono text-zinc-500">HTML</div>
<pre className="bg-black/50 p-2 overflow-x-auto text-[10px] border border-zinc-800">
<code className="font-mono text-zinc-300 whitespace-pre-wrap break-all">
{html}
</code>
</pre>
<button
onClick={() => copyToClipboard(html, 'html')}
className="w-full bg-zinc-800 text-zinc-300 py-1.5 font-mono text-xs hover:bg-zinc-700 hover:text-white transition-colors flex items-center justify-center gap-1.5 border border-zinc-700"
>
{copiedType === 'html' ? 'Copied!' : 'Copy HTML'}
</button>
</div>
<div className="text-[10px] font-mono text-zinc-600 text-center pt-2 border-t border-zinc-800">
Powered by shields.io
</div>
</div>
</div>
</div>
</div>
</section>
);
}
+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: 'tree', desc: 'Browse skill taxonomy' },
{ cmd: 'find <query>', desc: 'Search 15K+ skills' },
{ cmd: 'marketplace', desc: 'Browse skills' },
],
},
@@ -1,351 +0,0 @@
import React, { useState, useMemo } from 'react';
type Support = 'full' | 'partial' | 'none';
interface AgentDef {
id: string;
name: string;
icon: string;
group: string;
}
interface CategoryDef {
id: string;
name: string;
icon: string;
}
const AGENTS: AgentDef[] = [
{ id: 'claude-code', name: 'Claude Code', icon: '\u27C1', group: 'Tier 1' },
{ id: 'cursor', name: 'Cursor', icon: '\u25EB', group: 'Tier 1' },
{ id: 'codex', name: 'Codex', icon: '\u25CE', group: 'Tier 1' },
{ id: 'gemini-cli', name: 'Gemini CLI', icon: '\u2726', group: 'Tier 1' },
{ id: 'opencode', name: 'OpenCode', icon: '\u2B21', group: 'Tier 1' },
{ id: 'windsurf', name: 'Windsurf', icon: '\u25C7', group: 'Tier 1' },
{ id: 'github-copilot', name: 'Copilot', icon: '\u2318', group: 'Tier 1' },
{ id: 'goose', name: 'Goose', icon: '\u25CA', group: 'Tier 2' },
{ id: 'kilo', name: 'Kilo', icon: '\u25B3', group: 'Tier 2' },
{ id: 'kiro-cli', name: 'Kiro CLI', icon: '\u25BD', group: 'Tier 2' },
{ id: 'roo', name: 'Roo', icon: '\u25C6', group: 'Tier 2' },
{ id: 'trae', name: 'Trae', icon: '\u25A0', group: 'Tier 2' },
{ id: 'amp', name: 'AMP', icon: '\u26A1', group: 'Tier 2' },
{ id: 'cline', name: 'Cline', icon: '\u25CF', group: 'Tier 3' },
{ id: 'continue', name: 'Continue', icon: '\u25B6', group: 'Tier 3' },
{ id: 'antigravity', name: 'Antigravity', icon: '\u2191', group: 'Tier 3' },
];
const CATEGORIES: CategoryDef[] = [
{ id: 'security', name: 'Security', icon: '\u25D0' },
{ id: 'testing', name: 'Testing', icon: '\u25D2' },
{ id: 'react-frontend', name: 'React/Frontend', icon: '\u269B' },
{ id: 'backend', name: 'Backend', icon: '\u2393' },
{ id: 'devops', name: 'DevOps', icon: '\u25D1' },
{ id: 'python', name: 'Python', icon: '\u25C9' },
{ id: 'go', name: 'Go', icon: '\u25C8' },
{ id: 'typescript', name: 'TypeScript', icon: '\u25C8' },
{ id: 'database', name: 'Database', icon: '\u25A3' },
{ id: 'performance', name: 'Performance', icon: '\u25CE' },
{ id: 'documentation', name: 'Documentation', icon: '\u25A1' },
{ id: 'ai-ml', name: 'AI/ML', icon: '\u25CE' },
];
const MATRIX: Record<string, Record<string, Support>> = {
'security': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'full', 'windsurf': 'full', 'github-copilot': 'full', 'goose': 'partial',
'kilo': 'partial', 'kiro-cli': 'partial', 'roo': 'full', 'trae': 'partial',
'amp': 'full', 'cline': 'full', 'continue': 'partial', 'antigravity': 'partial',
},
'testing': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'full', 'windsurf': 'full', 'github-copilot': 'full', 'goose': 'full',
'kilo': 'partial', 'kiro-cli': 'partial', 'roo': 'full', 'trae': 'partial',
'amp': 'full', 'cline': 'full', 'continue': 'full', 'antigravity': 'partial',
},
'react-frontend': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'partial', 'windsurf': 'full', 'github-copilot': 'full', 'goose': 'partial',
'kilo': 'partial', 'kiro-cli': 'partial', 'roo': 'full', 'trae': 'full',
'amp': 'full', 'cline': 'full', 'continue': 'full', 'antigravity': 'none',
},
'backend': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'full', 'windsurf': 'full', 'github-copilot': 'full', 'goose': 'full',
'kilo': 'partial', 'kiro-cli': 'partial', 'roo': 'full', 'trae': 'partial',
'amp': 'full', 'cline': 'full', 'continue': 'full', 'antigravity': 'partial',
},
'devops': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'full', 'windsurf': 'partial', 'github-copilot': 'full', 'goose': 'partial',
'kilo': 'partial', 'kiro-cli': 'none', 'roo': 'partial', 'trae': 'partial',
'amp': 'full', 'cline': 'partial', 'continue': 'partial', 'antigravity': 'none',
},
'python': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'full', 'windsurf': 'full', 'github-copilot': 'full', 'goose': 'full',
'kilo': 'partial', 'kiro-cli': 'partial', 'roo': 'full', 'trae': 'partial',
'amp': 'full', 'cline': 'full', 'continue': 'full', 'antigravity': 'partial',
},
'go': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'full', 'windsurf': 'partial', 'github-copilot': 'full', 'goose': 'partial',
'kilo': 'none', 'kiro-cli': 'none', 'roo': 'partial', 'trae': 'partial',
'amp': 'partial', 'cline': 'partial', 'continue': 'partial', 'antigravity': 'none',
},
'typescript': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'full', 'windsurf': 'full', 'github-copilot': 'full', 'goose': 'full',
'kilo': 'partial', 'kiro-cli': 'partial', 'roo': 'full', 'trae': 'full',
'amp': 'full', 'cline': 'full', 'continue': 'full', 'antigravity': 'partial',
},
'database': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'partial', 'windsurf': 'partial', 'github-copilot': 'full', 'goose': 'partial',
'kilo': 'none', 'kiro-cli': 'none', 'roo': 'partial', 'trae': 'partial',
'amp': 'partial', 'cline': 'partial', 'continue': 'partial', 'antigravity': 'none',
},
'performance': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'partial', 'windsurf': 'partial', 'github-copilot': 'partial', 'goose': 'partial',
'kilo': 'none', 'kiro-cli': 'none', 'roo': 'partial', 'trae': 'partial',
'amp': 'partial', 'cline': 'partial', 'continue': 'partial', 'antigravity': 'none',
},
'documentation': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'full', 'windsurf': 'full', 'github-copilot': 'full', 'goose': 'full',
'kilo': 'partial', 'kiro-cli': 'partial', 'roo': 'full', 'trae': 'full',
'amp': 'full', 'cline': 'full', 'continue': 'full', 'antigravity': 'partial',
},
'ai-ml': {
'claude-code': 'full', 'cursor': 'full', 'codex': 'full', 'gemini-cli': 'full',
'opencode': 'partial', 'windsurf': 'partial', 'github-copilot': 'partial', 'goose': 'partial',
'kilo': 'none', 'kiro-cli': 'none', 'roo': 'partial', 'trae': 'partial',
'amp': 'partial', 'cline': 'partial', 'continue': 'partial', 'antigravity': 'none',
},
};
const SUPPORT_CONFIG: Record<Support, { color: string; bg: string; label: string }> = {
full: { color: 'text-green-400', bg: 'bg-green-400/10', label: 'Full' },
partial: { color: 'text-yellow-400', bg: 'bg-yellow-400/10', label: 'Partial' },
none: { color: 'text-red-400', bg: 'bg-red-400/10', label: 'None' },
};
const SUPPORT_SCORE: Record<Support, number> = { full: 2, partial: 1, none: 0 };
function SupportCell({ support }: { support: Support }): React.ReactElement {
const config = SUPPORT_CONFIG[support];
return (
<td className="px-1 py-2 text-center">
<div className={`inline-flex items-center justify-center w-5 h-5 rounded-full ${config.bg}`}>
<span className={`text-[10px] font-bold ${config.color}`}>
{support === 'full' ? '\u2713' : support === 'partial' ? '\u25CB' : '\u2715'}
</span>
</div>
</td>
);
}
function getAgentScore(agentId: string): number {
return Object.values(MATRIX).reduce((sum, row) => sum + SUPPORT_SCORE[row[agentId] || 'none'], 0);
}
function getMaxScore(): number {
return CATEGORIES.length * 2;
}
export function CompatibilityMatrix(): React.ReactElement {
const [filter, setFilter] = useState('');
const [groupFilter, setGroupFilter] = useState<string | null>(null);
const groups = useMemo(() => {
const seen = new Set<string>();
return AGENTS.reduce<string[]>((acc, a) => {
if (!seen.has(a.group)) {
seen.add(a.group);
acc.push(a.group);
}
return acc;
}, []);
}, []);
const { filteredAgents, filteredCategories } = useMemo(() => {
let agents = AGENTS;
if (groupFilter) {
agents = agents.filter(a => a.group === groupFilter);
}
if (!filter.trim()) {
return { filteredAgents: agents, filteredCategories: CATEGORIES };
}
const q = filter.toLowerCase();
const matchedAgents = agents.filter(a =>
a.name.toLowerCase().includes(q) || a.id.toLowerCase().includes(q)
);
const matchedCategories = CATEGORIES.filter(c =>
c.name.toLowerCase().includes(q) || c.id.toLowerCase().includes(q)
);
return {
filteredAgents: matchedAgents.length > 0 ? matchedAgents : (matchedCategories.length > 0 ? agents : []),
filteredCategories: matchedCategories.length > 0 ? matchedCategories : (matchedAgents.length > 0 ? CATEGORIES : []),
};
}, [filter, groupFilter]);
const maxScore = getMaxScore();
return (
<section className="py-12 border-b border-zinc-800" style={{ backgroundColor: '#09090b' }}>
<div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 mb-6">
<div>
<h2 className="text-lg sm:text-xl font-bold text-white mb-1 font-mono">Compatibility Matrix</h2>
<p className="text-zinc-500 font-mono text-[10px] sm:text-xs">
Skill support across 16 agents and 12 categories.
</p>
</div>
<div className="flex items-center gap-2">
<span className="w-2 h-2 bg-green-500 rounded-full"></span>
<span className="text-[10px] sm:text-xs font-mono text-zinc-500">Updated Feb 2026</span>
</div>
</div>
<div className="flex flex-col sm:flex-row gap-2 sm:gap-3 mb-6">
<div className="relative flex-1">
<svg className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-zinc-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<input
type="text"
value={filter}
onChange={(e) => setFilter(e.target.value)}
placeholder="Filter agents or categories..."
className="w-full bg-black border border-zinc-800 text-zinc-300 placeholder-zinc-700 font-mono text-xs px-8 py-2 focus:outline-none focus:border-zinc-600 transition-colors"
/>
{filter && (
<button
onClick={() => setFilter('')}
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-zinc-600 hover:text-zinc-400 transition-colors"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
<div className="flex gap-1.5">
<button
onClick={() => setGroupFilter(null)}
className={`px-2.5 py-1.5 font-mono text-[10px] sm:text-xs transition-all ${
groupFilter === null
? 'bg-white text-black'
: 'bg-zinc-900 text-zinc-400 border border-zinc-800 hover:border-zinc-600 hover:text-white'
}`}
>
All
</button>
{groups.map(g => (
<button
key={g}
onClick={() => setGroupFilter(groupFilter === g ? null : g)}
className={`px-2.5 py-1.5 font-mono text-[10px] sm:text-xs transition-all ${
groupFilter === g
? 'bg-white text-black'
: 'bg-zinc-900 text-zinc-400 border border-zinc-800 hover:border-zinc-600 hover:text-white'
}`}
>
{g}
</button>
))}
</div>
</div>
<div className="flex items-center gap-4 mb-4">
{Object.entries(SUPPORT_CONFIG).map(([key, config]) => (
<div key={key} className="flex items-center gap-1.5">
<div className={`w-3 h-3 rounded-full ${config.bg} flex items-center justify-center`}>
<span className={`text-[8px] font-bold ${config.color}`}>
{key === 'full' ? '\u2713' : key === 'partial' ? '\u25CB' : '\u2715'}
</span>
</div>
<span className="text-[10px] font-mono text-zinc-500">{config.label}</span>
</div>
))}
</div>
<div className="overflow-x-auto -mx-4 px-4 sm:mx-0 sm:px-0">
<div className="min-w-[700px]">
<table className="w-full border-collapse font-mono text-[10px]">
<thead>
<tr className="border-b border-zinc-800">
<th className="text-left text-zinc-500 uppercase tracking-wider py-2 pr-3 sticky left-0 bg-[#09090b] z-10 min-w-[120px]">
Category
</th>
{filteredAgents.map(agent => (
<th key={agent.id} className="px-1 py-2 text-center">
<div className="flex flex-col items-center gap-0.5">
<span className="text-sm">{agent.icon}</span>
<span className="text-zinc-400 whitespace-nowrap max-w-[50px] truncate" title={agent.name}>
{agent.name.length > 7 ? agent.name.slice(0, 7) : agent.name}
</span>
</div>
</th>
))}
</tr>
</thead>
<tbody>
{filteredCategories.map(category => (
<tr key={category.id} className="border-b border-zinc-800/50 hover:bg-zinc-900/50 transition-colors">
<td className="py-2 pr-3 sticky left-0 bg-[#09090b] z-10">
<div className="flex items-center gap-1.5">
<span className="text-zinc-600">{category.icon}</span>
<span className="text-zinc-300 whitespace-nowrap">{category.name}</span>
</div>
</td>
{filteredAgents.map(agent => (
<SupportCell
key={agent.id}
support={MATRIX[category.id]?.[agent.id] || 'none'}
/>
))}
</tr>
))}
</tbody>
<tfoot>
<tr className="border-t border-zinc-700">
<td className="py-3 pr-3 sticky left-0 bg-[#09090b] z-10">
<span className="text-zinc-400 font-bold uppercase tracking-wider">Score</span>
</td>
{filteredAgents.map(agent => {
const score = getAgentScore(agent.id);
const pct = Math.round((score / maxScore) * 100);
const color = pct >= 80 ? 'text-green-400' : pct >= 50 ? 'text-yellow-400' : 'text-red-400';
return (
<td key={agent.id} className="px-1 py-3 text-center">
<div className={`font-bold text-xs ${color}`}>{pct}%</div>
<div className="text-zinc-600 text-[9px]">{score}/{maxScore}</div>
</td>
);
})}
</tr>
</tfoot>
</table>
</div>
</div>
{filteredAgents.length === 0 && (
<div className="text-center py-8 text-zinc-600 font-mono text-sm">
No agents match your filter.
</div>
)}
{filteredCategories.length === 0 && filteredAgents.length > 0 && (
<div className="text-center py-8 text-zinc-600 font-mono text-sm">
No categories match your filter.
</div>
)}
</div>
</section>
);
}
+2 -11
View File
@@ -9,7 +9,7 @@ interface Feature {
const FEATURES: Feature[] = [
{
title: 'Smart Recommendations',
description: 'AI analyzes your codebase and recommends from 15,000+ skills.',
description: 'AI analyzes your codebase and suggests perfect skills.',
icon: (
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
@@ -18,7 +18,7 @@ const FEATURES: Feature[] = [
},
{
title: 'Auto Translation',
description: 'The npm for agent skills. Write once, auto-translate to 32 formats.',
description: 'Write once, deploy to 32 agents. Zero manual conversion.',
icon: (
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
@@ -43,15 +43,6 @@ 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.',
+7 -11
View File
@@ -1,10 +1,6 @@
import React, { useState, useEffect } from 'react';
import { Button } from './Button';
interface HeroProps {
version: string;
}
const ASCII_LOGO = `
███████╗██╗ ██╗██╗██╗ ██╗ ██╗ ██╗██╗████████╗
██╔════╝██║ ██╔╝██║██║ ██║ ██║ ██╔╝██║╚══██╔══╝
@@ -59,7 +55,7 @@ const COPY_ICON = (
</svg>
);
export function Hero({ version }: HeroProps): React.ReactElement {
export function Hero(): React.ReactElement {
const [copied, setCopied] = useState(false);
const [visibleLines, setVisibleLines] = useState(0);
const [typingIndex, setTypingIndex] = useState(0);
@@ -130,18 +126,18 @@ export function Hero({ version }: HeroProps): React.ReactElement {
<div className="animate-fade-in">
<div className="inline-flex items-center space-x-2 border border-zinc-800 bg-zinc-900/50 px-2 py-0.5 mb-3 backdrop-blur-sm">
<span className="flex h-1.5 w-1.5 bg-white rounded-full"></span>
<span className="text-xs font-mono text-zinc-400">v{version}</span>
<span className="text-xs font-mono text-zinc-400">v1.8.0</span>
</div>
<h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold tracking-tight text-white mb-3 font-mono">
One Skill.<br />
<span className="text-zinc-500">32 Agents. Zero Rewrites.</span>
Write Once.<br />
<span className="text-zinc-500">Deploy to 32 Agents.</span>
</h1>
<p className="text-sm text-zinc-400 mb-5 max-w-lg font-mono leading-relaxed">
The package manager for AI agent skills. Install from 15,000+ skills,
auto-translate between formats, persist learnings with Memory.
Works with Claude, Cursor, Windsurf, Copilot, and 28 more.
The universal skill platform for AI coding agents. Auto-generate instructions
with Primer, persist learnings with Memory, distribute across Mesh networks.
One CLI for Claude, Cursor, Windsurf, Copilot, and 28 more.
</p>
<div className="flex flex-wrap items-center gap-3 mb-4">
-119
View File
@@ -1,119 +0,0 @@
import { useState, useEffect } from 'react';
interface Stats {
version: string;
downloads: string;
stars: number;
loading: boolean;
}
const CACHE_KEY = 'skillkit_stats_cache';
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
interface CachedStats {
data: Omit<Stats, 'loading'>;
timestamp: number;
}
function formatDownloads(count: number): string {
if (count >= 1000000) {
return `${(count / 1000000).toFixed(1)}M`;
}
if (count >= 1000) {
return `${(count / 1000).toFixed(1)}k`;
}
return count.toString();
}
function getCachedStats(): CachedStats | null {
try {
const cached = localStorage.getItem(CACHE_KEY);
if (cached) {
const parsed: CachedStats = JSON.parse(cached);
if (Date.now() - parsed.timestamp < CACHE_TTL) {
return parsed;
}
}
} catch {
// Ignore localStorage errors
}
return null;
}
function setCachedStats(data: Omit<Stats, 'loading'>): void {
try {
const cached: CachedStats = {
data,
timestamp: Date.now(),
};
localStorage.setItem(CACHE_KEY, JSON.stringify(cached));
} catch {
// Ignore localStorage errors
}
}
export function useStats(): Stats {
const [stats, setStats] = useState<Stats>({
version: '1.9.0',
downloads: '2.4k',
stars: 66,
loading: true,
});
useEffect(() => {
const cached = getCachedStats();
if (cached) {
setStats({ ...cached.data, loading: false });
return;
}
async function fetchStats(): Promise<void> {
try {
const [npmResponse, githubResponse] = await Promise.allSettled([
fetch('https://api.npmjs.org/downloads/point/last-month/skillkit'),
fetch('https://api.github.com/repos/rohitg00/skillkit'),
]);
let downloads = '2.4k';
let stars = 66;
let version = '1.9.0';
if (npmResponse.status === 'fulfilled' && npmResponse.value.ok) {
const npmData = await npmResponse.value.json();
if (typeof npmData.downloads === 'number' && Number.isFinite(npmData.downloads)) {
downloads = formatDownloads(npmData.downloads);
}
}
if (githubResponse.status === 'fulfilled' && githubResponse.value.ok) {
const githubData = await githubResponse.value.json();
if (typeof githubData.stargazers_count === 'number' && Number.isFinite(githubData.stargazers_count)) {
stars = githubData.stargazers_count;
}
}
try {
const registryResponse = await fetch('https://registry.npmjs.org/skillkit/latest');
if (registryResponse.ok) {
const registryData = await registryResponse.json();
if (registryData.version) {
version = registryData.version;
}
}
} catch {
// Use default version
}
const newStats = { version, downloads, stars };
setCachedStats(newStats);
setStats({ ...newStats, loading: false });
} catch {
setStats((prev) => ({ ...prev, loading: false }));
}
}
fetchStats();
}, []);
return stats;
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "skillkit",
"private": true,
"version": "1.12.0",
"version": "1.8.0",
"type": "module",
"scripts": {
"dev": "vite",
+2 -19
View File
@@ -1,8 +1,8 @@
{
"$schema": "./schema.json",
"version": 1,
"updatedAt": "2026-02-02",
"totalSkills": 15065,
"updatedAt": "2026-01-26",
"totalSkills": 15064,
"curatedCollections": 31,
"skills": [
{
@@ -33112,23 +33112,6 @@
"k8s"
]
},
{
"id": "rohitg00/beautiful-mermaid/beautiful-mermaid",
"name": "Beautiful Mermaid",
"description": "Render Mermaid diagrams as beautiful SVGs or ASCII art. 5 diagram types, 15 themes, Shiki integration, zero DOM dependencies.",
"source": "rohitg00/beautiful-mermaid",
"tags": [
"mermaid",
"diagrams",
"visualization",
"flowchart",
"sequence",
"uml",
"ascii",
"svg",
"themes"
]
},
{
"id": "itsmostafa/aws-agent-skills/cognito",
"name": "Cognito",
+3 -9
View File
@@ -1,8 +1,8 @@
{
"name": "skillkit-monorepo",
"version": "1.12.0",
"version": "1.8.0",
"private": true,
"description": "The package manager for AI agent skills — install, translate, share across 32 coding agents",
"description": "Universal skills loader for AI coding agents - Monorepo",
"type": "module",
"scripts": {
"build": "turbo run build",
@@ -31,13 +31,7 @@
"coding-assistant",
"skill-loader",
"cli",
"monorepo",
"skill-md",
"package-manager",
"plugin",
"workflow",
"automation",
"SKILL.md"
"monorepo"
],
"author": "Rohit Ghumare",
"license": "Apache-2.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/agents",
"version": "1.12.0",
"version": "1.8.0",
"description": "Agent adapters for SkillKit - supports 32 AI coding agents",
"type": "module",
"main": "./dist/index.js",
-52
View File
@@ -1,52 +0,0 @@
{
"name": "@skillkit/api",
"version": "1.12.0",
"description": "REST API server for SkillKit skill discovery",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"bin": {
"skillkit-api": "./dist/index.js"
},
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"start": "node dist/index.js"
},
"dependencies": {
"hono": "^4.0.0",
"@hono/node-server": "^1.0.0",
"@skillkit/core": "workspace:*",
"zod": "^3.24.0"
},
"devDependencies": {
"@types/node": "^22.10.5",
"tsup": "^8.3.5",
"typescript": "^5.7.2",
"vitest": "^2.1.8"
},
"engines": {
"node": ">=18.0.0"
},
"license": "Apache-2.0",
"keywords": [
"skillkit",
"api",
"rest",
"skills",
"discovery",
"ai",
"agents"
]
}
-27
View File
@@ -1,27 +0,0 @@
import { describe, it, expect } from 'vitest';
import { createApp } from '../server.js';
describe('Health Routes', () => {
const { app } = createApp({ skills: [{ name: 'test', source: 'a/b' }], rateLimitMax: 1000 });
it('GET /health returns status ok', async () => {
const res = await app.request('/health');
expect(res.status).toBe(200);
const body = await res.json();
expect(body.status).toBe('ok');
expect(body.skillCount).toBe(1);
expect(typeof body.uptime).toBe('number');
expect(body.version).toBeDefined();
});
it('GET /cache/stats returns cache statistics', async () => {
const res = await app.request('/cache/stats');
expect(res.status).toBe(200);
const body = await res.json();
expect(typeof body.hits).toBe('number');
expect(typeof body.misses).toBe('number');
expect(typeof body.size).toBe('number');
expect(typeof body.maxSize).toBe('number');
expect(typeof body.hitRate).toBe('number');
});
});
-56
View File
@@ -1,56 +0,0 @@
import { describe, it, expect } from 'vitest';
import { createApp } from '../server.js';
const testSkills = [
{ name: 'react-perf', description: 'React performance tips', source: 'owner/repo', tags: ['react', 'performance'] },
{ name: 'testing-guide', description: 'Unit testing guide', source: 'owner/repo2', tags: ['testing'] },
{ name: 'nextjs-auth', description: 'Next.js authentication', source: 'other/repo', tags: ['nextjs', 'auth'], category: 'framework' },
];
describe('Search Routes', () => {
const { app } = createApp({ skills: testSkills, rateLimitMax: 1000 });
it('GET /search returns results for query', async () => {
const res = await app.request('/search?q=react');
expect(res.status).toBe(200);
const body = await res.json();
expect(body.query).toBe('react');
expect(body.skills.length).toBeGreaterThan(0);
expect(body.total).toBeGreaterThan(0);
});
it('GET /search returns 400 without query', async () => {
const res = await app.request('/search');
expect(res.status).toBe(400);
});
it('GET /search respects limit parameter', async () => {
const res = await app.request('/search?q=test&limit=1');
const body = await res.json();
expect(body.skills.length).toBeLessThanOrEqual(1);
expect(body.limit).toBe(1);
});
it('POST /search with filters', async () => {
const res = await app.request('/search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: 'auth',
filters: { tags: ['nextjs'] },
}),
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.skills.length).toBeGreaterThan(0);
});
it('POST /search returns 400 without query', async () => {
const res = await app.request('/search', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
expect(res.status).toBe(400);
});
});
-53
View File
@@ -1,53 +0,0 @@
import { describe, it, expect } from 'vitest';
import { createApp } from '../server.js';
const testSkills = [
{ name: 'my-skill', description: 'A test skill', source: 'owner/repo' },
];
describe('Skill Routes', () => {
const { app } = createApp({ skills: testSkills, rateLimitMax: 1000 });
it('GET /skills/:source/:id returns a skill', async () => {
const res = await app.request('/skills/owner/repo/my-skill');
expect(res.status).toBe(200);
const body = await res.json();
expect(body.name).toBe('my-skill');
expect(body.source).toBe('owner/repo');
});
it('GET /skills/:owner/:repo/:id returns 404 for missing skill', async () => {
const res = await app.request('/skills/owner/repo/nonexistent');
expect(res.status).toBe(404);
});
});
describe('Trending Routes', () => {
const { app } = createApp({ skills: testSkills, rateLimitMax: 1000 });
it('GET /trending returns skills', async () => {
const res = await app.request('/trending');
expect(res.status).toBe(200);
const body = await res.json();
expect(body.skills).toBeInstanceOf(Array);
expect(body.limit).toBeDefined();
});
});
describe('Category Routes', () => {
const skills = [
{ name: 'a', source: 'x/y', tags: ['react', 'ui'] },
{ name: 'b', source: 'x/z', tags: ['react'], category: 'framework' },
];
const { app } = createApp({ skills, rateLimitMax: 1000 });
it('GET /categories returns tag counts', async () => {
const res = await app.request('/categories');
expect(res.status).toBe(200);
const body = await res.json();
expect(body.categories).toBeInstanceOf(Array);
expect(body.total).toBeGreaterThan(0);
const react = body.categories.find((c: { name: string }) => c.name === 'react');
expect(react?.count).toBe(2);
});
});
-11
View File
@@ -1,11 +0,0 @@
export { createApp, startServer } from './server.js';
export type { ServerOptions } from './server.js';
export type {
ApiSkill,
SearchResponse,
HealthResponse,
CacheStatsResponse,
TrendingResponse,
CategoriesResponse,
CategoryCount,
} from './types.js';
-43
View File
@@ -1,43 +0,0 @@
import type { Context, Next } from 'hono';
interface RateLimitEntry {
count: number;
resetAt: number;
}
export function rateLimiter(maxRequests = 60, windowMs = 60_000) {
const windows = new Map<string, RateLimitEntry>();
setInterval(() => {
const now = Date.now();
for (const [key, entry] of windows) {
if (now > entry.resetAt) {
windows.delete(key);
}
}
}, windowMs).unref();
return async (c: Context, next: Next): Promise<Response | void> => {
const forwardedFor = c.req.header('x-forwarded-for');
const ip = (forwardedFor?.split(',')[0]?.trim()) || c.req.header('x-real-ip') || 'unknown';
const now = Date.now();
let entry = windows.get(ip);
if (!entry || now > entry.resetAt) {
entry = { count: 0, resetAt: now + windowMs };
windows.set(ip, entry);
}
entry.count++;
c.header('X-RateLimit-Limit', String(maxRequests));
c.header('X-RateLimit-Remaining', String(Math.max(0, maxRequests - entry.count)));
c.header('X-RateLimit-Reset', String(Math.ceil(entry.resetAt / 1000)));
if (entry.count > maxRequests) {
return c.json({ error: 'Too many requests', retryAfter: Math.ceil((entry.resetAt - now) / 1000) }, 429);
}
await next();
};
}
-34
View File
@@ -1,34 +0,0 @@
import { Hono } from 'hono';
import type { ApiSkill, CategoriesResponse } from '../types.js';
export function categoryRoutes(skills: ApiSkill[]) {
const app = new Hono();
app.get('/categories', (c) => {
const tagCounts = new Map<string, number>();
for (const skill of skills) {
if (skill.tags) {
for (const tag of skill.tags) {
tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);
}
}
if (skill.category) {
const key = `category:${skill.category}`;
tagCounts.set(key, (tagCounts.get(key) || 0) + 1);
}
}
const categories = Array.from(tagCounts.entries())
.map(([name, count]) => ({ name, count }))
.sort((a, b) => b.count - a.count);
const response: CategoriesResponse = {
categories,
total: categories.length,
};
return c.json(response);
});
return app;
}
-33
View File
@@ -1,33 +0,0 @@
import { Hono } from 'hono';
import type { HealthResponse, CacheStatsResponse } from '../types.js';
import type { CacheBackend } from '@skillkit/core';
const startTime = Date.now();
export function healthRoutes(skillCount: number, cache: CacheBackend) {
const app = new Hono();
app.get('/health', (c) => {
const response: HealthResponse = {
status: 'ok',
version: '1.11.0',
skillCount,
uptime: Math.floor((Date.now() - startTime) / 1000),
};
return c.json(response);
});
app.get('/cache/stats', (c) => {
const stats = cache.stats();
const response: CacheStatsResponse = {
hits: stats.hits,
misses: stats.misses,
size: stats.size,
maxSize: stats.maxSize,
hitRate: stats.hitRate,
};
return c.json(response);
});
return app;
}
-128
View File
@@ -1,128 +0,0 @@
import { Hono } from 'hono';
import type { ApiSkill, SearchResponse } from '../types.js';
import { RelevanceRanker } from '@skillkit/core';
import type { MemoryCache } from '@skillkit/core';
export function searchRoutes(skills: ApiSkill[], cache: MemoryCache<SearchResponse>) {
const app = new Hono();
const ranker = new RelevanceRanker();
app.get('/search', (c) => {
const query = c.req.query('q') || '';
const parsedLimit = parseInt(c.req.query('limit') || '20', 10);
const limit = Math.min(Number.isNaN(parsedLimit) ? 20 : parsedLimit, 100);
const includeContent = c.req.query('include_content') === 'true';
if (!query) {
return c.json({ error: 'Query parameter "q" is required' }, 400);
}
const cacheKey = `search:${query}:${limit}:${includeContent}`;
const cached = cache.get(cacheKey);
if (cached) return c.json(cached);
const skillMap = new Map(skills.map((s) => [`${s.source}:${s.name}`, s]));
const ranked = ranker.rank(
skills.map((s) => ({
name: s.name,
description: s.description,
content: s.content,
stars: s.stars,
installs: s.installs,
source: s.source,
})),
query,
);
const results: ApiSkill[] = ranked.slice(0, limit).map((r) => {
const key = `${(r.skill as Record<string, unknown>).source}:${r.skill.name}`;
const original = skillMap.get(key) ?? skills.find((s) => s.name === r.skill.name)!;
if (!includeContent) {
const { content: _, ...rest } = original;
return rest;
}
return original;
});
const response: SearchResponse = {
skills: results,
total: ranked.length,
query,
limit,
};
cache.set(cacheKey, response);
return c.json(response);
});
app.post('/search', async (c) => {
let body: {
query: string;
limit?: number;
include_content?: boolean;
filters?: { tags?: string[]; category?: string; source?: string };
};
try {
body = await c.req.json();
} catch {
return c.json({ error: 'Invalid JSON body' }, 400);
}
if (!body.query) {
return c.json({ error: 'Field "query" is required' }, 400);
}
const limit = Math.min(body.limit ?? 20, 100);
let filtered = skills;
if (body.filters) {
if (body.filters.tags?.length) {
filtered = filtered.filter((s) =>
body.filters!.tags!.some((t) => s.tags?.includes(t)),
);
}
if (body.filters.category) {
filtered = filtered.filter((s) => s.category === body.filters!.category);
}
if (body.filters.source) {
filtered = filtered.filter((s) => s.source.includes(body.filters!.source!));
}
}
const filteredMap = new Map(filtered.map((s) => [`${s.source}:${s.name}`, s]));
const ranked = ranker.rank(
filtered.map((s) => ({
name: s.name,
description: s.description,
content: s.content,
stars: s.stars,
installs: s.installs,
source: s.source,
})),
body.query,
);
const results: ApiSkill[] = ranked.slice(0, limit).map((r) => {
const key = `${(r.skill as Record<string, unknown>).source}:${r.skill.name}`;
const original = filteredMap.get(key) ?? filtered.find((s) => s.name === r.skill.name)!;
if (!body.include_content) {
const { content: _, ...rest } = original;
return rest;
}
return original;
});
const response: SearchResponse = {
skills: results,
total: ranked.length,
query: body.query,
limit,
};
return c.json(response);
});
return app;
}
-23
View File
@@ -1,23 +0,0 @@
import { Hono } from 'hono';
import type { ApiSkill } from '../types.js';
export function skillRoutes(skills: ApiSkill[]) {
const app = new Hono();
app.get('/skills/:owner/:repo/:id', (c) => {
const source = `${c.req.param('owner')}/${c.req.param('repo')}`;
const id = c.req.param('id');
const skill = skills.find(
(s) => s.source === source && s.name === id,
);
if (!skill) {
return c.json({ error: `Skill not found: ${source}/${id}` }, 404);
}
return c.json(skill);
});
return app;
}
-39
View File
@@ -1,39 +0,0 @@
import { Hono } from 'hono';
import type { ApiSkill, TrendingResponse } from '../types.js';
import { RelevanceRanker } from '@skillkit/core';
export function trendingRoutes(skills: ApiSkill[]) {
const app = new Hono();
const ranker = new RelevanceRanker();
app.get('/trending', (c) => {
const parsedLimit = parseInt(c.req.query('limit') || '20', 10);
const limit = Math.min(Number.isNaN(parsedLimit) ? 20 : parsedLimit, 100);
const skillMap = new Map(skills.map((s) => [`${s.source}:${s.name}`, s]));
const ranked = ranker.rank(
skills.map((s) => ({
name: s.name,
description: s.description,
content: s.content,
stars: s.stars,
installs: s.installs,
references: [],
source: s.source,
})),
);
const results = ranked.slice(0, limit).map((r) => {
const key = `${(r.skill as Record<string, unknown>).source}:${r.skill.name}`;
const original = skillMap.get(key) ?? skills.find((s) => s.name === r.skill.name)!;
const { content: _, ...rest } = original;
return rest;
});
const response: TrendingResponse = { skills: results, limit };
return c.json(response);
});
return app;
}
-55
View File
@@ -1,55 +0,0 @@
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { MemoryCache } from '@skillkit/core';
import { rateLimiter } from './middleware/rate-limit.js';
import { healthRoutes } from './routes/health.js';
import { searchRoutes } from './routes/search.js';
import { skillRoutes } from './routes/skills.js';
import { trendingRoutes } from './routes/trending.js';
import { categoryRoutes } from './routes/categories.js';
import type { ApiSkill, SearchResponse } from './types.js';
export interface ServerOptions {
port?: number;
host?: string;
corsOrigin?: string;
cacheTtlMs?: number;
skills?: ApiSkill[];
rateLimitMax?: number;
}
export function createApp(options: ServerOptions = {}) {
const skills = options.skills || [];
const cache = new MemoryCache<SearchResponse>({
maxSize: 500,
ttlMs: options.cacheTtlMs ?? 86_400_000,
});
const app = new Hono();
app.use('*', cors({ origin: options.corsOrigin || '*' }));
app.use('*', rateLimiter(options.rateLimitMax ?? 60));
app.route('/', healthRoutes(skills.length, cache));
app.route('/', searchRoutes(skills, cache));
app.route('/', skillRoutes(skills));
app.route('/', trendingRoutes(skills));
app.route('/', categoryRoutes(skills));
return { app, cache };
}
export async function startServer(options: ServerOptions = {}) {
const port = options.port ?? 3737;
const host = options.host ?? '0.0.0.0';
const { app, cache } = createApp(options);
const { serve } = await import('@hono/node-server');
const server = serve({ fetch: app.fetch, port, hostname: host }, () => {
console.log(`SkillKit API server running at http://${host}:${port}`);
console.log(`Skills loaded: ${options.skills?.length ?? 0}`);
});
return { server, app, cache };
}
-48
View File
@@ -1,48 +0,0 @@
export interface ApiSkill {
name: string;
description?: string;
source: string;
repo?: string;
tags?: string[];
category?: string;
content?: string;
stars?: number;
installs?: number;
}
export interface SearchResponse {
skills: ApiSkill[];
total: number;
query: string;
limit: number;
}
export interface HealthResponse {
status: 'ok';
version: string;
skillCount: number;
uptime: number;
}
export interface CacheStatsResponse {
hits: number;
misses: number;
size: number;
maxSize: number;
hitRate: number;
}
export interface TrendingResponse {
skills: ApiSkill[];
limit: number;
}
export interface CategoryCount {
name: string;
count: number;
}
export interface CategoriesResponse {
categories: CategoryCount[];
total: number;
}
-10
View File
@@ -1,10 +0,0 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": false
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
-17
View File
@@ -1,17 +0,0 @@
import { defineConfig } from 'tsup';
export default defineConfig({
entry: ['src/index.ts'],
format: ['esm'],
target: 'node18',
outDir: 'dist',
clean: true,
dts: true,
sourcemap: true,
splitting: false,
skipNodeModulesBundle: true,
platform: 'node',
banner: {
js: '#!/usr/bin/env node',
},
});
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/cli",
"version": "1.12.0",
"version": "1.8.0",
"description": "CLI commands for SkillKit",
"type": "module",
"main": "./dist/index.js",
@@ -22,7 +22,6 @@
},
"dependencies": {
"@clack/prompts": "^0.11.0",
"@skillkit/api": "workspace:*",
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"@skillkit/resources": "workspace:*",
@@ -1,69 +0,0 @@
import { describe, it, expect } from 'vitest';
import { join, normalize, resolve, sep } from 'node:path';
function isPathInside(child: string, parent: string): boolean {
const resolved = resolve(child);
const resolvedParent = resolve(parent);
return resolved === resolvedParent || resolved.startsWith(resolvedParent + sep);
}
function sanitizeName(name: string): string {
return name.split(/[/\\]/).pop() || name;
}
describe('Quick Command Security', () => {
describe('path traversal protection', () => {
const installDir = '/home/user/.claude/skills';
it('should block skill names that escape the install directory', () => {
const maliciousNames = ['../evil', '../../etc/passwd', '../../../tmp/bad', '..\\evil'];
for (const name of maliciousNames) {
const sanitized = sanitizeName(name);
const targetPath = normalize(join(installDir, sanitized));
expect(isPathInside(targetPath, installDir)).toBe(true);
expect(sanitized).not.toContain('..');
expect(sanitized).not.toContain('/');
expect(sanitized).not.toContain('\\');
}
});
it('should sanitize "../evil" to "evil"', () => {
expect(sanitizeName('../evil')).toBe('evil');
});
it('should sanitize "../../etc/passwd" to "passwd"', () => {
expect(sanitizeName('../../etc/passwd')).toBe('passwd');
});
it('should sanitize "..\\evil" to "evil"', () => {
expect(sanitizeName('..\\evil')).toBe('evil');
});
it('should keep valid skill names unchanged', () => {
expect(sanitizeName('my-skill')).toBe('my-skill');
expect(sanitizeName('react-best-practices')).toBe('react-best-practices');
});
it('should produce a path inside installDir after sanitization', () => {
const evilName = '../evil';
const sanitized = sanitizeName(evilName);
const targetPath = normalize(join(installDir, sanitized));
expect(isPathInside(targetPath, installDir)).toBe(true);
expect(targetPath).toBe(join(installDir, 'evil'));
});
it('should detect unsanitized traversal names before normalization', () => {
const rawPath = `${installDir}/../evil`;
expect(isPathInside(rawPath, installDir)).toBe(false);
});
it('should ensure sanitization prevents the traversal entirely', () => {
const evilName = '../evil';
const sanitized = sanitizeName(evilName);
const targetPath = normalize(join(installDir, sanitized));
expect(targetPath).toBe(join(installDir, 'evil'));
expect(targetPath.startsWith(installDir)).toBe(true);
});
});
});
-39
View File
@@ -1,39 +0,0 @@
const SKILLKIT_LOGO_SVG_BASE64 =
'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0id2hpdGUiPjxyZWN0IHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHg9IjEiIHk9IjEiLz48cmVjdCB3aWR0aD0iNiIgaGVpZ2h0PSI2IiB4PSI5IiB5PSIxIi8+PHJlY3Qgd2lkdGg9IjYiIGhlaWdodD0iNiIgeD0iMSIgeT0iOSIvPjxyZWN0IHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHg9IjkiIHk9IjkiLz48L3N2Zz4=';
function encodeBadgeSegment(text: string): string {
return encodeURIComponent(text).replace(/-/g, '--');
}
export function generateBadge(skills: string[]): {
url: string;
markdown: string;
html: string;
} {
const count = skills.length;
if (count === 0) {
const url = `https://img.shields.io/badge/SkillKit-No%20Skills-555555?style=flat-square&logo=data:image/svg+xml;base64,${SKILLKIT_LOGO_SVG_BASE64}`;
return {
url,
markdown: `[![SkillKit Stack](${url})](https://agenstskills.com)`,
html: `<a href="https://agenstskills.com"><img src="${url}" alt="SkillKit Stack" /></a>`,
};
}
const maxDisplay = 5;
const displayNames = skills.slice(0, maxDisplay);
const suffix = count > maxDisplay ? ` +${count - maxDisplay} more` : '';
const label = `SkillKit ${count} skills`;
const message = displayNames.join(' | ') + suffix;
const encodedLabel = encodeBadgeSegment(label);
const encodedMessage = encodeBadgeSegment(message);
const url = `https://img.shields.io/badge/${encodedLabel}-${encodedMessage}-black?style=flat-square&logo=data:image/svg+xml;base64,${SKILLKIT_LOGO_SVG_BASE64}`;
return {
url,
markdown: `[![SkillKit Stack](${url})](https://agenstskills.com)`,
html: `<a href="https://agenstskills.com"><img src="${url}" alt="SkillKit Stack" /></a>`,
};
}
+22 -187
View File
@@ -7,7 +7,7 @@
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { join, basename } from 'node:path';
import { join } from 'node:path';
import { homedir } from 'node:os';
import {
findAllAgents,
@@ -17,14 +17,8 @@ import {
validateAgent,
translateAgent,
getAgentTargetDirectory,
discoverSkills,
readSkillContent,
generateSubagentFromSkill,
type CustomAgent,
type AgentType,
type Skill,
type AgentPermissionMode,
type SkillToSubagentOptions,
} from '@skillkit/core';
import {
getBundledAgents,
@@ -34,6 +28,7 @@ import {
isAgentInstalled,
type BundledAgent,
} from '@skillkit/resources';
// Agent discovery uses root directories, not skill directories
export class AgentCommand extends Command {
static override paths = [['agent']];
@@ -48,19 +43,17 @@ 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 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
agent list - List all installed agents
agent show - Show agent details
agent create - Create a new agent
agent translate - Translate agents between formats
agent sync - Sync agents to target AI agent
agent validate - Validate agent definitions
`,
examples: [
['List all agents', '$0 agent list'],
['Show agent details', '$0 agent show architect'],
['Create new agent', '$0 agent create security-reviewer'],
['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'],
],
@@ -71,7 +64,6 @@ 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');
@@ -262,6 +254,7 @@ 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'));
@@ -269,6 +262,7 @@ export class AgentCreateCommand extends Command {
return 1;
}
// Determine target directory
let targetDir: string;
if (this.global) {
targetDir = join(homedir(), '.claude', 'agents');
@@ -276,19 +270,23 @@ 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}`));
@@ -352,9 +350,11 @@ 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,6 +391,7 @@ 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`));
@@ -423,6 +424,7 @@ export class AgentTranslateCommand extends Command {
}
}
} else {
// Create directory if needed
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
@@ -527,10 +529,12 @@ 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);
@@ -555,6 +559,8 @@ 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);
@@ -825,180 +831,9 @@ 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;
}
+2 -41
View File
@@ -8,7 +8,6 @@ import {
select,
header,
} from '../onboarding/index.js';
import { FederatedSearch, GitHubSkillRegistry, RateLimitError } from '@skillkit/core';
interface SkillResult {
name: string;
@@ -55,10 +54,6 @@ export class FindCommand extends Command {
description: 'Minimal output (just list skills)',
});
federated = Option.Boolean('--federated,-f', false, {
description: 'Search external registries (GitHub SKILL.md files)',
});
async execute(): Promise<number> {
const s = spinner();
const limit = parseInt(this.limit, 10) || 10;
@@ -133,46 +128,12 @@ export class FindCommand extends Command {
}
}
if (this.federated && this.query) {
s.start('Searching external registries...');
const fedSearch = new FederatedSearch();
fedSearch.addRegistry(new GitHubSkillRegistry());
try {
const fedResult = await fedSearch.search(this.query, { limit: parseInt(this.limit, 10) || 10 });
s.stop(`Found ${fedResult.total} external skill(s) from ${fedResult.registries.join(', ') || 'none'}`);
if (fedResult.skills.length > 0) {
console.log('');
console.log(colors.bold('External Skills (SKILL.md):'));
for (const skill of fedResult.skills) {
const stars = typeof skill.stars === 'number' ? colors.muted(` ★${skill.stars}`) : '';
const desc = skill.description
? colors.muted(` - ${skill.description.slice(0, 50)}${skill.description.length > 50 ? '...' : ''}`)
: '';
console.log(` ${colors.cyan(symbols.bullet)} ${colors.primary(skill.name)}${stars}${desc}`);
if (!this.quiet) {
console.log(` ${colors.muted(skill.source)}`);
}
}
console.log('');
}
} catch (err) {
if (err instanceof RateLimitError) {
s.stop(colors.warning('Rate limited by GitHub API'));
console.log(colors.muted('Set GITHUB_TOKEN env var or wait before retrying.'));
} else {
s.stop(colors.warning('Federated search failed'));
}
}
}
if (results.length === 0) {
console.log(colors.muted('No skills found matching your search'));
console.log('');
console.log(colors.muted('Try:'));
console.log(colors.muted(' skillkit find --top # Show featured skills'));
console.log(colors.muted(' skillkit find -f <query> # Search external registries'));
console.log(colors.muted(' skillkit ui # Browse in TUI'));
console.log(colors.muted(' skillkit find --top # Show featured skills'));
console.log(colors.muted(' skillkit ui # Browse in TUI'));
return 0;
}
+1 -14
View File
@@ -43,13 +43,12 @@ export { PlanCommand } from './plan.js';
export { CommandCmd, CommandAvailableCommand, CommandInstallCommand } from './command.js';
export { AICommand } from './ai.js';
export { AuditCommand } from './audit.js';
export { PublishCommand, PublishSubmitCommand } from './publish.js';
export { PublishCommand } from './publish.js';
export {
AgentCommand,
AgentListCommand,
AgentShowCommand,
AgentCreateCommand,
AgentFromSkillCommand,
AgentTranslateCommand,
AgentSyncCommand,
AgentValidateCommand,
@@ -105,15 +104,3 @@ export {
GuidelineCreateCommand,
GuidelineRemoveCommand,
} from './guideline.js';
// Tree command for hierarchical skill browsing (Phase 21)
export { TreeCommand } from './tree.js';
// Quick setup (zero-friction entry)
export { QuickCommand } from './quick.js';
// SKILL.md ecosystem
export { SkillMdValidateCommand, SkillMdInitCommand, SkillMdCheckCommand } from './skillmd.js';
// API server
export { ServeCommand } from './serve.js';
+3 -23
View File
@@ -1,9 +1,5 @@
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';
@@ -46,8 +42,7 @@ 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 skill', '$0 install owner/repo --skill=pdf'],
['Install multiple skills (CI/CD)', '$0 install owner/repo --skills=pdf,xlsx'],
['Install specific skills (CI/CD)', '$0 install owner/repo --skills=pdf,xlsx'],
['Install all skills non-interactively', '$0 install owner/repo --all'],
['Install from local path', '$0 install ./my-skills'],
['Install globally', '$0 install owner/repo --global'],
@@ -58,7 +53,7 @@ export class InstallCommand extends Command {
source = Option.String({ required: true });
skills = Option.String('--skills,--skill,-s', {
skills = Option.String('--skills,-s', {
description: 'Comma-separated list of skills to install (non-interactive)',
});
@@ -148,7 +143,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> --skill=name'));
console.log(colors.muted('To install: skillkit install <source> --skills=skill1,skill2'));
}
const cleanupPath = result.tempRoot || result.path;
@@ -339,21 +334,6 @@ 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 = {
+126 -336
View File
@@ -1,20 +1,8 @@
import { existsSync, readFileSync, mkdirSync, writeFileSync, readdirSync, statSync } from 'node:fs';
import { join, basename, dirname, resolve } from 'node:path';
import { existsSync, readFileSync } from 'node:fs';
import { join, basename, dirname } from 'node:path';
import { execSync } from 'node:child_process';
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
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;
@@ -27,201 +15,141 @@ export class PublishCommand extends Command {
static override paths = [['publish']];
static override usage = Command.Usage({
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
`,
description: 'Publish your skill to the SkillKit marketplace',
examples: [
['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'],
['Publish skill from current directory', '$0 publish'],
['Publish skill from specific path', '$0 publish ./my-skill'],
['Publish with custom name', '$0 publish --name my-awesome-skill'],
],
});
skillPath = Option.String({ required: false, name: 'path' });
output = Option.String('--output,-o', {
description: 'Output directory for well-known structure (default: current directory)',
name = Option.String('--name,-n', {
description: 'Custom skill name (default: parsed from SKILL.md)',
});
dryRun = Option.Boolean('--dry-run,-n', false, {
description: 'Show what would be generated without writing files',
dryRun = Option.Boolean('--dry-run', false, {
description: 'Show what would be published without actually publishing',
});
async execute(): Promise<number> {
const basePath = this.skillPath || process.cwd();
const outputDir = this.output || basePath;
const skillPath = this.skillPath || process.cwd();
const skillMdPath = this.findSkillMd(skillPath);
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'));
if (!skillMdPath) {
console.error(chalk.red('No SKILL.md found'));
console.error(chalk.dim('Run this command from a directory containing SKILL.md'));
console.error(chalk.dim('Or specify the path: skillkit publish ./path/to/skill'));
return 1;
}
console.log(chalk.white(`Found ${discoveredSkills.length} skill(s):\n`));
console.log(chalk.cyan('Publishing skill to SkillKit marketplace...\n'));
const wellKnownSkills: WellKnownSkill[] = [];
// Parse SKILL.md
const content = readFileSync(skillMdPath, 'utf-8');
const frontmatter = this.parseFrontmatter(content);
const skillName = this.name || frontmatter.name || basename(dirname(skillMdPath));
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'));
// Get git repo info
const repoInfo = this.getRepoInfo(dirname(skillMdPath));
if (!repoInfo) {
console.error(chalk.red('Not a git repository or no remote configured'));
console.error(chalk.dim('Your skill must be in a git repository with a GitHub remote'));
return 1;
}
console.log('');
// Build skill entry
const skillSlug = this.slugify(skillName);
if (!skillSlug) {
console.error(chalk.red('Skill name produces an empty slug.'));
console.error(chalk.dim('Please pass --name with letters or numbers.'));
return 1;
}
const skillEntry = {
id: `${repoInfo.owner}/${repoInfo.repo}/${skillSlug}`,
name: this.formatName(skillName),
description: frontmatter.description || `Best practices and patterns for ${this.formatName(skillName)}`,
source: `${repoInfo.owner}/${repoInfo.repo}`,
tags: frontmatter.tags || this.inferTags(skillName, frontmatter.description || ''),
};
console.log(chalk.white('Skill details:'));
console.log(chalk.dim(` ID: ${skillEntry.id}`));
console.log(chalk.dim(` Name: ${skillEntry.name}`));
console.log(chalk.dim(` Description: ${skillEntry.description}`));
console.log(chalk.dim(` Source: ${skillEntry.source}`));
console.log(chalk.dim(` Tags: ${skillEntry.tags.join(', ')}`));
console.log();
if (this.dryRun) {
console.log(chalk.yellow('Dry run - not 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));
console.log(chalk.yellow('Dry run - not publishing'));
console.log(chalk.dim('JSON entry that would be added:'));
console.log(JSON.stringify(skillEntry, null, 2));
return 0;
}
const wellKnownDir = join(outputDir, '.well-known', 'skills');
mkdirSync(wellKnownDir, { recursive: true });
// 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`;
for (const skill of validSkills) {
const skillDir = join(wellKnownDir, skill.safeName);
const resolvedSkillDir = resolve(skillDir);
const resolvedWellKnownDir = resolve(wellKnownDir);
console.log(chalk.green('Opening GitHub to submit your skill...\n'));
if (!resolvedSkillDir.startsWith(resolvedWellKnownDir)) {
console.log(chalk.yellow(` Skipping "${skill.name}" (path traversal detected)`));
continue;
}
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' });
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(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));
}
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();
console.log(chalk.cyan('Next steps:'));
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'));
console.log(chalk.dim(' 1. Review the skill details in the GitHub issue'));
console.log(chalk.dim(' 2. Submit the issue'));
console.log(chalk.dim(' 3. A maintainer will review and add your skill'));
return 0;
}
private 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;
private findSkillMd(basePath: string): string | null {
// Check if path is directly to SKILL.md
if (basePath.endsWith('SKILL.md') && existsSync(basePath)) {
return basePath;
}
const searchDirs = [
basePath,
join(basePath, 'skills'),
join(basePath, '.claude', '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'),
];
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,
});
}
for (const loc of locations) {
if (existsSync(loc)) {
return loc;
}
}
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;
return null;
}
private parseFrontmatter(content: string): SkillFrontmatter {
@@ -233,6 +161,7 @@ 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) {
@@ -261,6 +190,7 @@ 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)
@@ -277,171 +207,6 @@ 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
@@ -453,19 +218,19 @@ export class PublishSubmitCommand 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
// Not a git repo or no remote
}
return null;
@@ -478,6 +243,31 @@ export class PublishSubmitCommand 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 {
@@ -502,6 +292,6 @@ ${JSON.stringify(skill, null, 2)}
- [ ] Tags are appropriate
---
Submitted via \`skillkit publish submit\``;
Submitted via \`skillkit publish\``;
}
}
-375
View File
@@ -1,375 +0,0 @@
import { existsSync, mkdirSync, cpSync, rmSync, symlinkSync } from 'node:fs';
import { join, resolve, normalize } from 'node:path';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
const execFileAsync = promisify(execFile);
import { Command } from 'clipanion';
import {
type ProjectProfile,
type SkillMetadata,
type AgentType,
ContextManager,
RecommendationEngine,
loadIndex as loadIndexFromCache,
isIndexStale,
buildSkillIndex,
saveIndex,
KNOWN_SKILL_REPOS,
isPathInside,
isLocalPath,
detectProvider,
} from '@skillkit/core';
import { getAdapter, detectAgent, getAllAdapters } from '@skillkit/agents';
import { getInstallDir, saveSkillMetadata } from '../helpers.js';
import {
welcome,
spinner,
step,
success,
error,
warn,
colors,
symbols,
confirm,
select,
outro,
formatAgent,
getAgentIcon,
isCancel,
cancel,
showProjectSummary,
progressBar,
formatQualityBadge,
saveLastAgents,
} from '../onboarding/index.js';
function truncate(str: string, maxLen: number): string {
if (str.length <= maxLen) return str;
return str.slice(0, maxLen - 3) + '...';
}
export class QuickCommand extends Command {
static override paths = [['quick']];
static override usage = Command.Usage({
description: 'Zero-friction skill setup: detect agents, analyze project, recommend and install',
examples: [
['Quick setup', '$0 quick'],
],
});
async execute(): Promise<number> {
const s = spinner();
try {
welcome();
step(`${colors.bold('Quick Setup')} - zero-friction skill installation`);
console.log('');
s.start('Detecting installed AI agents...');
const allAdapters = getAllAdapters();
const detectedAgents: AgentType[] = [];
for (const adapter of allAdapters) {
try {
const installDir = getInstallDir(false, adapter.type);
const globalDir = getInstallDir(true, adapter.type);
if (existsSync(installDir) || existsSync(globalDir) || existsSync(adapter.configFile)) {
detectedAgents.push(adapter.type);
}
} catch {
// skip
}
}
if (detectedAgents.length === 0) {
const fallback = await detectAgent();
detectedAgents.push(fallback);
}
s.stop(`Detected ${detectedAgents.length} agent${detectedAgents.length !== 1 ? 's' : ''}: ${detectedAgents.map(formatAgent).join(', ')}`);
s.start('Analyzing project...');
const targetPath = resolve(process.cwd());
const manager = new ContextManager(targetPath);
let context = manager.get();
if (!context) {
context = manager.init();
}
s.stop('Project analyzed');
if (!context) {
error('Failed to analyze project');
return 1;
}
const profile: ProjectProfile = {
name: context.project.name,
type: context.project.type,
stack: context.stack,
patterns: context.patterns,
installedSkills: context.skills?.installed || [],
excludedSkills: context.skills?.excluded || [],
};
const languages = profile.stack.languages.map((l: { name: string; version?: string }) => `${l.name}${l.version ? ` ${l.version}` : ''}`);
const frameworks = profile.stack.frameworks.map((f: { name: string; version?: string }) => `${f.name}${f.version ? ` ${f.version}` : ''}`);
showProjectSummary({
name: profile.name,
type: profile.type,
languages,
frameworks,
});
let index = loadIndexFromCache();
if (!index || index.skills.length === 0) {
s.start('Building skill index from known sources...');
try {
const result = await buildSkillIndex(KNOWN_SKILL_REPOS, (message: string) => {
s.message(message);
});
index = result.index;
saveIndex(index);
s.stop(`Indexed ${index.skills.length} skills`);
} catch {
s.stop(colors.error('Failed to build index'));
warn('Could not fetch skill index. Try running: skillkit recommend --update');
return 1;
}
} else if (isIndexStale(index)) {
step(colors.muted('Skill index is stale. Run "skillkit recommend --update" to refresh.'));
}
const engine = new RecommendationEngine();
engine.loadIndex(index);
const result = engine.recommend(profile, {
limit: 5,
minScore: 20,
excludeInstalled: true,
includeReasons: true,
});
const recommendations = result.recommendations;
if (recommendations.length === 0) {
warn('No matching skills found for your project.');
console.log(colors.muted('Try running: skillkit recommend --update'));
return 0;
}
console.log('');
console.log(colors.bold(`Top ${recommendations.length} Recommended Skills:`));
console.log('');
const options: Array<{ value: string; label: string; hint?: string }> = [];
for (let i = 0; i < recommendations.length; i++) {
const rec = recommendations[i];
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 = typeof qualityScore === 'number' && Number.isFinite(qualityScore)
? ` ${formatQualityBadge(qualityScore)}`
: '';
console.log(` ${colors.bold(`${i + 1}.`)} ${scoreColor(`${rec.score}%`)} ${colors.dim(scoreBar)} ${colors.bold(rec.skill.name)}${qualityDisplay}`);
if (rec.skill.description) {
console.log(` ${colors.muted(truncate(rec.skill.description, 70))}`);
}
options.push({
value: `${i}`,
label: `${rec.skill.name} (${rec.score}% match)`,
hint: rec.skill.source || undefined,
});
}
console.log('');
const skipOption = { value: 'skip', label: 'Skip installation' };
const selectResult = await select({
message: 'Select a skill to install',
options: [...options, skipOption],
});
if (isCancel(selectResult) || selectResult === 'skip') {
cancel('Quick setup complete (no installation)');
return 0;
}
const selectedIndex = parseInt(selectResult as string, 10);
const selectedSkill = recommendations[selectedIndex];
if (!selectedSkill || !selectedSkill.skill.source) {
error('Selected skill has no installable source');
return 1;
}
const agentDisplay = detectedAgents.length <= 3
? detectedAgents.map(formatAgent).join(', ')
: `${detectedAgents.slice(0, 2).map(formatAgent).join(', ')} +${detectedAgents.length - 2} more`;
const confirmResult = await confirm({
message: `Install ${colors.bold(selectedSkill.skill.name)} to ${agentDisplay}?`,
initialValue: true,
});
if (isCancel(confirmResult) || !confirmResult) {
cancel('Installation cancelled');
return 0;
}
saveLastAgents(detectedAgents);
const providerAdapter = detectProvider(selectedSkill.skill.source);
if (!providerAdapter) {
error(`Could not detect provider for: ${selectedSkill.skill.source}`);
return 1;
}
s.start(`Fetching ${selectedSkill.skill.name}...`);
const cloneResult = await providerAdapter.clone(selectedSkill.skill.source, '', { depth: 1 });
if (!cloneResult.success || !cloneResult.path) {
s.stop(colors.error(cloneResult.error || 'Failed to fetch source'));
return 1;
}
const discoveredSkills = cloneResult.discoveredSkills || [];
const matchedSkill = discoveredSkills.find(ds => ds.name === selectedSkill.skill.name) || discoveredSkills[0];
if (!matchedSkill) {
s.stop(colors.error('Skill not found in repository'));
return 1;
}
s.stop(`Found ${selectedSkill.skill.name}`);
let primaryPath: string | null = null;
const installedAgents: string[] = [];
for (const agentType of detectedAgents) {
const adapter = getAdapter(agentType);
const installDir = getInstallDir(false, agentType);
if (!existsSync(installDir)) {
mkdirSync(installDir, { recursive: true });
}
const sanitizedName = matchedSkill.name.split(/[/\\]/).pop() || matchedSkill.name;
const targetInstallPath = normalize(join(installDir, sanitizedName));
if (!isPathInside(targetInstallPath, installDir)) {
error(`Skipping ${matchedSkill.name} for ${adapter.name} (install path escapes target directory)`);
continue;
}
const securityRoot = cloneResult.tempRoot || cloneResult.path;
if (!isPathInside(matchedSkill.path, securityRoot)) {
error(`Skipping ${matchedSkill.name} for ${adapter.name} (path traversal detected)`);
continue;
}
const useSymlink = detectedAgents.length > 1 && primaryPath !== null;
s.start(`Installing to ${adapter.name}${useSymlink ? ' (symlink)' : ''}...`);
try {
if (existsSync(targetInstallPath)) {
rmSync(targetInstallPath, { recursive: true, force: true });
}
if (useSymlink && primaryPath) {
symlinkSync(primaryPath, targetInstallPath, 'dir');
} else {
cpSync(matchedSkill.path, targetInstallPath, { recursive: true, dereference: true });
if (detectedAgents.length > 1 && primaryPath === null) {
primaryPath = targetInstallPath;
}
const packageJsonPath = join(targetInstallPath, 'package.json');
if (existsSync(packageJsonPath)) {
s.stop(`Installed to ${adapter.name}`);
s.start('Installing npm dependencies...');
try {
await execFileAsync('npm', ['install', '--production'], { cwd: targetInstallPath });
s.stop('Dependencies installed');
} catch {
s.stop(colors.warning('Dependencies failed'));
console.log(colors.muted('Run manually: npm install in ' + targetInstallPath));
}
s.start('Finishing installation...');
}
}
const metadata: SkillMetadata = {
name: matchedSkill.name,
description: selectedSkill.skill.description || '',
source: selectedSkill.skill.source,
sourceType: providerAdapter.type,
subpath: matchedSkill.name,
installedAt: new Date().toISOString(),
enabled: true,
};
saveSkillMetadata(targetInstallPath, metadata);
installedAgents.push(agentType);
s.stop(`Installed to ${adapter.name}${useSymlink ? ' (symlink)' : ''}`);
} catch (err) {
s.stop(colors.error(`Failed to install to ${adapter.name}`));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
}
}
const cleanupPath = cloneResult.tempRoot || cloneResult.path;
if (!isLocalPath(selectedSkill.skill.source) && cleanupPath && existsSync(cleanupPath)) {
rmSync(cleanupPath, { recursive: true, force: true });
}
if (installedAgents.length > 0) {
console.log('');
success(`Installed ${colors.bold(matchedSkill.name)} to ${installedAgents.length} agent${installedAgents.length !== 1 ? 's' : ''}`);
for (const a of installedAgents) {
console.log(colors.muted(` ${symbols.success} ${getAgentIcon(a)} ${formatAgent(a)}`));
}
console.log('');
const badgeUrl = `https://img.shields.io/badge/SkillKit-${encodeURIComponent(matchedSkill.name)}-black?style=flat-square`;
console.log(colors.dim('Add to your README:'));
console.log(colors.muted(` [![SkillKit](${badgeUrl})](https://agenstskills.com)`));
outro('Quick setup complete!');
console.log('');
console.log(colors.muted('Next steps:'));
console.log(colors.muted(` ${symbols.arrowRight} Run ${colors.cyan('skillkit sync')} to update agent configs`));
console.log(colors.muted(` ${symbols.arrowRight} Run ${colors.cyan('skillkit recommend')} for more suggestions`));
console.log(colors.muted(` ${symbols.arrowRight} Run ${colors.cyan('skillkit list')} to see installed skills`));
console.log('');
} else {
warn('No agents were installed');
}
return 0;
} catch (err) {
s.stop(colors.error('Quick setup failed'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
}
-332
View File
@@ -3,10 +3,8 @@ import { resolve } from 'node:path';
import {
type ProjectProfile,
type ScoredSkill,
type ExplainedScoredSkill,
ContextManager,
RecommendationEngine,
ReasoningRecommendationEngine,
buildSkillIndex,
saveIndex,
loadIndex as loadIndexFromCache,
@@ -52,9 +50,6 @@ export class RecommendCommand extends Command {
['Update skill index', '$0 recommend --update'],
['Search for skills by task', '$0 recommend --task "authentication"'],
['Search for skills (alias)', '$0 recommend --search "testing"'],
['Hybrid search (vector + keyword)', '$0 recommend --search "auth" --hybrid'],
['Hybrid search with query expansion', '$0 recommend --search "auth" --hybrid --expand'],
['Build hybrid search index', '$0 recommend --build-index'],
],
});
@@ -113,41 +108,6 @@ 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',
});
// Hybrid search mode
hybrid = Option.Boolean('--hybrid,-H', false, {
description: 'Use hybrid search (vector + keyword)',
});
// Query expansion
expand = Option.Boolean('--expand,-x', false, {
description: 'Enable query expansion (requires --hybrid)',
});
// Reranking
rerank = Option.Boolean('--rerank', false, {
description: 'Enable LLM reranking (requires --hybrid)',
});
// Build index
buildIndex = Option.Boolean('--build-index', false, {
description: 'Build/rebuild the hybrid search embedding index',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
@@ -156,16 +116,6 @@ export class RecommendCommand extends Command {
return await this.updateIndex();
}
// Handle hybrid index building
if (this.buildIndex) {
return await this.buildHybridIndex();
}
// Validate hybrid-dependent options
if ((this.expand || this.rerank) && !this.hybrid) {
warn('--expand and --rerank require --hybrid flag. These options will be ignored.');
}
if (!this.quiet && !this.json) {
header('Skill Recommendations');
}
@@ -189,11 +139,6 @@ 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);
@@ -201,9 +146,6 @@ export class RecommendCommand extends Command {
// Handle search mode (--search or --task)
const searchQuery = this.search || this.task;
if (searchQuery) {
if (this.hybrid) {
return await this.handleHybridSearch(engine, searchQuery);
}
return this.handleSearch(engine, searchQuery);
}
@@ -226,63 +168,6 @@ 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();
@@ -391,223 +276,6 @@ 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 async handleHybridSearch(engine: RecommendationEngine, query: string): Promise<number> {
if (!this.quiet && !this.json) {
header(`Hybrid Search: "${query}"`);
}
const s = !this.quiet && !this.json ? spinner() : null;
s?.start('Initializing hybrid search...');
try {
await engine.initHybridSearch();
s?.message('Searching...');
const results = await engine.hybridSearch({
query,
limit: this.limit ? parseInt(this.limit, 10) : 10,
hybrid: true,
enableExpansion: this.expand,
enableReranking: this.rerank,
filters: {
minScore: this.minScore ? parseInt(this.minScore, 10) : undefined,
},
});
s?.stop(`Found ${results.length} results`);
if (this.json) {
console.log(JSON.stringify(results, null, 2));
return 0;
}
if (results.length === 0) {
warn(`No skills found matching "${query}"`);
return 0;
}
console.log('');
console.log(colors.bold(`Hybrid search results for "${query}" (${results.length} found):`));
if (this.expand && results[0]?.expandedTerms?.length) {
console.log(colors.muted(` Expanded: ${results[0].expandedTerms.join(', ')}`));
}
console.log('');
for (const result of results) {
let relevanceColor: (text: string) => string;
if (result.relevance >= 70) {
relevanceColor = colors.success;
} else if (result.relevance >= 50) {
relevanceColor = colors.warning;
} else {
relevanceColor = colors.muted;
}
const relevanceBar = progressBar(result.relevance, 100, 10);
console.log(` ${relevanceColor(`${result.relevance}%`)} ${colors.dim(relevanceBar)} ${colors.bold(result.skill.name)}`);
if (result.skill.description) {
console.log(` ${colors.muted(truncate(result.skill.description, 70))}`);
}
if (this.verbose) {
const scores: string[] = [];
if (typeof result.vectorSimilarity === 'number') {
scores.push(`vector: ${(result.vectorSimilarity * 100).toFixed(0)}%`);
}
if (typeof result.keywordScore === 'number') {
scores.push(`keyword: ${result.keywordScore.toFixed(0)}%`);
}
if (typeof result.rrfScore === 'number') {
scores.push(`rrf: ${result.rrfScore.toFixed(3)}`);
}
if (scores.length > 0) {
console.log(` ${colors.dim('Scores:')} ${scores.join(' | ')}`);
}
}
if (result.matchedTerms.length > 0) {
console.log(` ${colors.dim('Matched:')} ${result.matchedTerms.join(', ')}`);
}
console.log('');
}
return 0;
} catch (err) {
s?.stop(colors.error('Hybrid search failed'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
console.log(colors.muted('Falling back to standard search...'));
return this.handleSearch(engine, query);
}
}
private async buildHybridIndex(): Promise<number> {
if (!this.quiet) {
header('Build Hybrid Search Index');
}
const index = this.loadIndex();
if (!index || index.skills.length === 0) {
warn('No skill index found. Run --update first.');
return 1;
}
const s = spinner();
s.start('Initializing...');
try {
const engine = new RecommendationEngine();
engine.loadIndex(index);
await engine.buildHybridIndex((progress) => {
const percentage = Math.round((progress.current / progress.total) * 100);
s.message(`${progress.phase}: ${progress.message || ''} (${percentage}%)`);
});
s.stop(colors.success(`${symbols.success} Built hybrid index for ${index.skills.length} skills`));
console.log(colors.muted(' Index stored in: ~/.skillkit/search.db'));
console.log(colors.muted(' Use --hybrid flag for vector+keyword search\n'));
return 0;
} catch (err) {
s.stop(colors.error('Failed to build hybrid index'));
console.log(colors.muted(err instanceof Error ? err.message : String(err)));
return 1;
}
}
private handleSearch(engine: RecommendationEngine, query: string): number {
if (!this.quiet && !this.json) {
header(`Search: "${query}"`);
-93
View File
@@ -1,93 +0,0 @@
import { Command, Option } from 'clipanion';
import {
colors,
header,
step,
} from '../onboarding/index.js';
import skillsData from '../../../../marketplace/skills.json' with { type: 'json' };
export class ServeCommand extends Command {
static override paths = [['serve'], ['server']];
static override usage = Command.Usage({
description: 'Start the SkillKit REST API server for skill discovery',
details: `
Launches a local HTTP server that exposes the SkillKit skill catalog
via a REST API. Useful for integrating with other tools, building
custom UIs, or enabling agent-native skill discovery.
`,
examples: [
['Start server on default port', '$0 serve'],
['Start on custom port', '$0 serve --port 8080'],
['Start with custom CORS', '$0 serve --cors "http://localhost:3000"'],
],
});
port = Option.String('--port,-p', '3737', {
description: 'Port to listen on',
});
host = Option.String('--host,-H', '0.0.0.0', {
description: 'Host to bind to',
});
corsOrigin = Option.String('--cors', '*', {
description: 'CORS allowed origin',
});
cacheTtl = Option.String('--cache-ttl', '86400000', {
description: 'Cache TTL in milliseconds',
});
async execute(): Promise<number> {
header('SkillKit API Server');
const skills = (skillsData.skills || []).map((skill: Record<string, unknown>) => ({
name: skill.name as string,
description: skill.description as string | undefined,
source: (skill.source as string) || '',
repo: skill.repo as string | undefined,
tags: skill.tags as string[] | undefined,
category: skill.category as string | undefined,
}));
step(`Loading ${skills.length} skills from marketplace`);
const portNum = parseInt(this.port, 10) || 3737;
const cacheTtlMs = parseInt(this.cacheTtl, 10) || 86_400_000;
try {
const { startServer } = await import('@skillkit/api');
await startServer({
port: portNum,
host: this.host,
corsOrigin: this.corsOrigin,
cacheTtlMs,
skills,
});
step(`Server running at ${colors.cyan(`http://${this.host}:${portNum}`)}`);
console.log('');
console.log(colors.muted('Endpoints:'));
console.log(colors.muted(` GET /health - Server health check`));
console.log(colors.muted(` GET /search?q=... - Search skills`));
console.log(colors.muted(` POST /search - Search with filters`));
console.log(colors.muted(` GET /skills/:o/:r/:id - Get specific skill`));
console.log(colors.muted(` GET /trending - Top skills`));
console.log(colors.muted(` GET /categories - Skill categories`));
console.log(colors.muted(` GET /cache/stats - Cache statistics`));
console.log('');
console.log(colors.muted('Press Ctrl+C to stop'));
await new Promise(() => {});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error(colors.error(`Failed to start server: ${message}`));
return 1;
}
return 0;
}
}
-440
View File
@@ -1,440 +0,0 @@
import { existsSync, readFileSync, writeFileSync, readdirSync } from 'node:fs';
import { join, resolve, basename, relative } from 'node:path';
import { Command, Option } from 'clipanion';
import {
colors,
symbols,
spinner,
step,
success,
error,
warn,
header,
} from '../onboarding/index.js';
interface SkillMdValidation {
path: string;
exists: boolean;
hasName: boolean;
hasDescription: boolean;
hasTriggers: boolean;
hasCapabilities: boolean;
triggerCount: number;
capabilityCount: number;
score: number;
issues: string[];
}
function validateSkillMd(filePath: string): SkillMdValidation {
const result: SkillMdValidation = {
path: filePath,
exists: false,
hasName: false,
hasDescription: false,
hasTriggers: false,
hasCapabilities: false,
triggerCount: 0,
capabilityCount: 0,
score: 0,
issues: [],
};
if (!existsSync(filePath)) {
result.issues.push('File does not exist');
return result;
}
result.exists = true;
const content = readFileSync(filePath, 'utf-8');
if (!content.trim()) {
result.issues.push('File is empty');
return result;
}
const frontmatterMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
const bodyContent = frontmatterMatch
? content.slice(frontmatterMatch[0].length)
: content;
if (frontmatterMatch) {
const frontmatter = frontmatterMatch[1];
if (/^name:\s*.+$/m.test(frontmatter)) result.hasName = true;
if (/^description:\s*.+$/m.test(frontmatter)) result.hasDescription = true;
}
if (!result.hasName) {
if (/^#\s+.+$/m.test(bodyContent)) result.hasName = true;
}
if (!result.hasDescription) {
if (/^##?\s*(description|about|overview)\b/im.test(bodyContent)) {
result.hasDescription = true;
} else {
const lines = bodyContent.split(/\r?\n/).filter(l => l.trim());
const nonHeaderLines = lines.filter(l => !l.startsWith('#'));
if (nonHeaderLines.length >= 2) result.hasDescription = true;
}
}
const triggerPatterns = [
/triggers?\s*when/i,
/when\s*to\s*use/i,
/use\s*this\s*when/i,
/\*\*triggers?\b/i,
/^[-*]\s+.+(when|if|pattern|trigger)/im,
/glob:/i,
];
for (const pattern of triggerPatterns) {
if (pattern.test(content)) {
result.hasTriggers = true;
break;
}
}
if (result.hasTriggers) {
const triggerSection = content.match(/triggers?\s*when[:\s]*\n((?:[-*]\s+.+\n?)+)/i);
result.triggerCount = triggerSection
? (triggerSection[1].match(/^[-*]\s+/gm) || []).length
: 1;
}
const capabilityPatterns = [
/capabilities?[:\s]/i,
/features?[:\s]/i,
/what\s*(it|this)\s*(does|can)/i,
/^##?\s*capabilities/im,
/^##?\s*features/im,
];
for (const pattern of capabilityPatterns) {
if (pattern.test(content)) {
result.hasCapabilities = true;
break;
}
}
if (result.hasCapabilities) {
const capSection = content.match(/(?:capabilities?|features?)[:\s]*\n((?:[-*]\s+.+\n?)+)/i);
result.capabilityCount = capSection
? (capSection[1].match(/^[-*]\s+/gm) || []).length
: 1;
}
if (!result.hasName) result.issues.push('Missing name field');
if (!result.hasDescription) result.issues.push('Missing description section');
if (!result.hasTriggers) result.issues.push('No trigger patterns found');
if (!result.hasCapabilities) result.issues.push('No capabilities list found');
let score = 0;
if (result.exists) score += 10;
if (result.hasName) score += 20;
if (result.hasDescription) score += 25;
if (result.hasTriggers) score += 20;
if (result.hasCapabilities) score += 15;
if (result.triggerCount >= 3) score += 5;
if (result.capabilityCount >= 3) score += 5;
if (frontmatterMatch) {
const fm = frontmatterMatch[1];
if (/^version:/m.test(fm)) score += 3;
if (/^license:/m.test(fm)) score += 2;
if (/^tags:/m.test(fm)) score += 3;
if (/^metadata:/m.test(fm)) score += 2;
}
result.score = Math.min(100, score);
return result;
}
function printValidation(validation: SkillMdValidation, verbose = false): void {
const scoreColor = validation.score >= 80
? colors.success
: validation.score >= 60
? colors.warning
: colors.error;
console.log(` ${colors.muted('Score:')} ${scoreColor(`${validation.score}`)}/100`);
console.log(` ${validation.hasName ? colors.success(symbols.success) : colors.error(symbols.error)} Name field`);
console.log(` ${validation.hasDescription ? colors.success(symbols.success) : colors.error(symbols.error)} Description section`);
console.log(` ${validation.hasTriggers ? colors.success(symbols.success) : colors.error(symbols.error)} Trigger patterns${validation.triggerCount > 0 ? ` (${validation.triggerCount})` : ''}`);
console.log(` ${validation.hasCapabilities ? colors.success(symbols.success) : colors.error(symbols.error)} Capabilities list${validation.capabilityCount > 0 ? ` (${validation.capabilityCount})` : ''}`);
if (verbose && validation.issues.length > 0) {
console.log('');
console.log(` ${colors.warning('Issues:')}`);
for (const issue of validation.issues) {
console.log(` ${colors.warning(symbols.warning)} ${issue}`);
}
}
}
export class SkillMdValidateCommand extends Command {
static override paths = [['skillmd', 'validate'], ['skill-md', 'validate']];
static override usage = Command.Usage({
description: 'Validate a SKILL.md file against the standard',
examples: [
['Validate SKILL.md in current directory', '$0 skillmd validate'],
['Validate specific file', '$0 skillmd validate ./path/to/SKILL.md'],
],
});
targetPath = Option.String({ required: false, name: 'path' });
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed validation results',
});
json = Option.Boolean('--json', false, {
description: 'Output as JSON',
});
async execute(): Promise<number> {
const targetPath = this.targetPath || join(process.cwd(), 'SKILL.md');
const resolvedPath = resolve(targetPath);
const filePath = resolvedPath.endsWith('SKILL.md') ? resolvedPath : join(resolvedPath, 'SKILL.md');
if (!this.json) {
header('SKILL.md Validation');
step(`Validating: ${colors.cyan(filePath)}`);
console.log('');
}
const validation = validateSkillMd(filePath);
if (this.json) {
console.log(JSON.stringify(validation, null, 2));
return validation.score >= 60 ? 0 : 1;
}
console.log(colors.primary(basename(filePath)));
printValidation(validation, this.verbose);
console.log('');
if (validation.score >= 80) {
success(`SKILL.md is compliant (score: ${validation.score}/100)`);
} else if (validation.score >= 60) {
warn(`SKILL.md needs improvement (score: ${validation.score}/100)`);
} else {
error(`SKILL.md does not meet minimum standard (score: ${validation.score}/100)`);
}
return validation.score >= 60 ? 0 : 1;
}
}
export class SkillMdInitCommand extends Command {
static override paths = [['skillmd', 'init'], ['skill-md', 'init']];
static override usage = Command.Usage({
description: 'Create a template SKILL.md in the current directory',
examples: [
['Create SKILL.md template', '$0 skillmd init'],
['Create with custom name', '$0 skillmd init --name my-skill'],
],
});
name = Option.String('--name,-n', {
description: 'Skill name',
});
force = Option.Boolean('--force,-f', false, {
description: 'Overwrite existing SKILL.md',
});
async execute(): Promise<number> {
const outputPath = join(process.cwd(), 'SKILL.md');
if (existsSync(outputPath) && !this.force) {
warn('SKILL.md already exists');
console.log(colors.muted('Use --force to overwrite'));
return 1;
}
const skillName = this.name || basename(process.cwd());
const formattedName = skillName
.split('-')
.map((w: string) => w.charAt(0).toUpperCase() + w.slice(1))
.join(' ');
const template = [
'---',
`name: ${skillName}`,
'description: What this skill does and when to use it',
'version: "1.0"',
'license: MIT',
'tags: [general]',
'metadata:',
' author: your-name',
'---',
'',
`# ${formattedName}`,
'',
'Brief description of what this skill provides to AI coding agents.',
'',
'## Triggers when:',
`- User asks about ${skillName} related tasks`,
`- Project contains ${skillName} configuration files`,
`- Code changes involve ${skillName} patterns`,
'',
'## Capabilities:',
`- Provides best practices for ${skillName}`,
'- Generates boilerplate code and configurations',
'- Validates existing implementations',
'- Suggests improvements and optimizations',
'',
'## Steps',
'1. First step the AI agent should take',
'2. Second step with specific instructions',
'3. Third step with expected outcome',
'',
'## Examples',
'',
'```',
'Example code or configuration here',
'```',
'',
].join('\n');
writeFileSync(outputPath, template);
success(`Created SKILL.md for "${skillName}"`);
console.log('');
console.log(colors.muted('Next steps:'));
console.log(` ${colors.cyan('1.')} Edit SKILL.md with your skill instructions`);
console.log(` ${colors.cyan('2.')} Run ${colors.cyan('skillkit skillmd validate')} to check compliance`);
console.log(` ${colors.cyan('3.')} Run ${colors.cyan('skillkit publish submit')} to share with the marketplace`);
return 0;
}
}
export class SkillMdCheckCommand extends Command {
static override paths = [['skillmd', 'check'], ['skill-md', 'check']];
static override usage = Command.Usage({
description: 'Check all SKILL.md files in the project for compliance',
examples: [
['Check current directory', '$0 skillmd check'],
['Check specific directory', '$0 skillmd check ./skills'],
],
});
targetPath = Option.String({ required: false, name: 'path' });
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed validation results',
});
async execute(): Promise<number> {
const targetPath = resolve(this.targetPath || process.cwd());
header('SKILL.md Compliance Check');
const s = spinner();
s.start('Scanning for SKILL.md files...');
const skillMdFiles = this.findSkillMdFiles(targetPath);
s.stop(`Found ${skillMdFiles.length} SKILL.md file(s)`);
if (skillMdFiles.length === 0) {
warn('No SKILL.md files found');
console.log(colors.muted(`Searched: ${targetPath}`));
console.log('');
console.log(colors.muted('Create one with:'));
console.log(` ${colors.cyan('skillkit skillmd init')}`);
return 0;
}
const validations: SkillMdValidation[] = skillMdFiles.map(f => validateSkillMd(f));
validations.sort((a, b) => b.score - a.score);
console.log('');
for (const validation of validations) {
const relativePath = relative(targetPath, validation.path);
const scoreColor = validation.score >= 80 ? colors.success : validation.score >= 60 ? colors.warning : colors.error;
console.log(`${scoreColor(symbols.bullet)} ${colors.primary(relativePath)} ${colors.muted(`(${validation.score}/100)`)}`);
if (this.verbose) {
printValidation(validation, true);
console.log('');
}
}
console.log('');
const passing = validations.filter(v => v.score >= 60).length;
const failing = validations.filter(v => v.score < 60).length;
const avgScore = Math.round(validations.reduce((sum, v) => sum + v.score, 0) / validations.length);
console.log(colors.muted('Summary:'));
console.log(` ${colors.muted('Total:')} ${validations.length}`);
console.log(` ${colors.success(symbols.success)} Passing (60+): ${passing}`);
if (failing > 0) {
console.log(` ${colors.error(symbols.error)} Failing: ${failing}`);
}
console.log(` ${colors.muted('Average score:')} ${avgScore}/100`);
console.log('');
if (failing > 0) {
error(`${failing} SKILL.md file(s) below minimum standard`);
return 1;
}
success('All SKILL.md files are compliant');
return 0;
}
private findSkillMdFiles(dir: string): string[] {
const results: string[] = [];
const directFile = join(dir, 'SKILL.md');
if (existsSync(directFile)) results.push(directFile);
const searchDirs = [
join(dir, 'skills'),
join(dir, '.claude', 'skills'),
join(dir, '.cursor', 'skills'),
join(dir, '.codex', 'skills'),
join(dir, '.github', 'skills'),
];
for (const searchDir of searchDirs) {
if (!existsSync(searchDir)) continue;
this.scanDir(searchDir, results, 0);
}
try {
const entries = readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) continue;
if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;
const entrySkillMd = join(dir, entry.name, 'SKILL.md');
if (existsSync(entrySkillMd) && !results.includes(entrySkillMd)) {
results.push(entrySkillMd);
}
}
} catch {
// ignore read errors
}
return results;
}
private scanDir(dir: string, results: string[], depth: number): void {
if (depth > 3) return;
try {
const entries = readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const entryPath = join(dir, entry.name);
if (entry.isFile() && entry.name === 'SKILL.md') {
if (!results.includes(entryPath)) results.push(entryPath);
}
if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
this.scanDir(entryPath, results, depth + 1);
}
}
} catch {
// ignore read errors
}
}
}
+6 -5
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 { findAllSkills } from '@skillkit/core';
import { loadConfig, findAllSkills } from '@skillkit/core';
import type { AgentType } from '@skillkit/core';
import { getAdapter, detectAgent, getAllAdapters } from '@skillkit/agents';
import { getSearchDirs, getAgentConfigPath } from '../helpers.js';
@@ -67,9 +67,10 @@ export class SyncCommand extends Command {
if (this.agent) {
agentType = this.agent as AgentType;
} else if (isInteractive) {
// Let user select agent - always detect, don't rely on default config
// Let user select agent
s.start('Detecting agent...');
const detected = await detectAgent();
const config = loadConfig();
const detected = config.agent || (await detectAgent());
s.stop(`Detected: ${formatAgent(detected)}`);
const allAgents = getAllAdapters().map(a => a.type);
@@ -91,8 +92,8 @@ export class SyncCommand extends Command {
agentType = agentResult as AgentType;
} else {
// Non-interactive: always detect, don't rely on default config
agentType = await detectAgent();
const config = loadConfig();
agentType = config.agent || (await detectAgent());
}
const adapter = getAdapter(agentType);
-266
View File
@@ -1,266 +0,0 @@
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 -11
View File
@@ -1,6 +1,6 @@
{
"name": "@skillkit/core",
"version": "1.12.0",
"version": "1.8.0",
"description": "Core functionality for SkillKit - skill discovery, parsing, and translation",
"type": "module",
"main": "./dist/index.js",
@@ -37,10 +37,6 @@
"./learning": {
"import": "./dist/learning/index.js",
"types": "./dist/learning/index.d.ts"
},
"./search": {
"import": "./dist/search/index.js",
"types": "./dist/search/index.d.ts"
}
},
"files": [
@@ -57,13 +53,7 @@
"yaml": "^2.6.1",
"zod": "^3.24.1"
},
"optionalDependencies": {
"node-llama-cpp": "^3.15.0",
"better-sqlite3": "^12.0.0",
"sqlite-vec": "^0.1.6"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.11",
"@types/node": "^22.10.5",
"tsup": "^8.3.5",
"typescript": "^5.7.2",
@@ -1,332 +0,0 @@
/**
* 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,11 +60,3 @@ export {
getAgentTargetDirectory,
isAgentCompatible,
} from './translator.js';
// Skill Converter
export {
skillToSubagent,
generateSubagentFromSkill,
loadAndConvertSkill,
type SkillToSubagentOptions,
} from './skill-converter.js';
-285
View File
@@ -1,285 +0,0 @@
/**
* 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',
};
}
}
+1 -6
View File
@@ -64,12 +64,7 @@ export const AgentFrontmatter = z.object({
/** Allowed tools for this agent */
allowedTools: z.union([
z.array(z.string()),
z.string(),
]).optional(),
/** Tools (Claude Code native format alias for allowedTools) */
tools: z.union([
z.array(z.string()),
z.string(),
z.string(), // YAML-style list in frontmatter
]).optional(),
/** Agent-scoped hooks */
hooks: z.array(AgentHook).optional(),
-91
View File
@@ -1,91 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { MemoryCache } from '../memory.js';
describe('MemoryCache', () => {
let cache: MemoryCache<string>;
beforeEach(() => {
cache = new MemoryCache<string>({ maxSize: 3, ttlMs: 1000 });
});
it('stores and retrieves values', () => {
cache.set('a', 'value-a');
expect(cache.get('a')).toBe('value-a');
});
it('returns undefined for missing keys', () => {
expect(cache.get('missing')).toBeUndefined();
});
it('deletes entries', () => {
cache.set('a', 'value-a');
expect(cache.delete('a')).toBe(true);
expect(cache.get('a')).toBeUndefined();
});
it('checks existence with has()', () => {
cache.set('a', 'value-a');
expect(cache.has('a')).toBe(true);
expect(cache.has('b')).toBe(false);
});
it('clears all entries', () => {
cache.set('a', '1');
cache.set('b', '2');
cache.clear();
expect(cache.has('a')).toBe(false);
expect(cache.stats().size).toBe(0);
});
it('evicts LRU when at capacity', () => {
vi.useFakeTimers();
try {
cache.set('a', '1');
vi.advanceTimersByTime(1);
cache.set('b', '2');
vi.advanceTimersByTime(1);
cache.set('c', '3');
vi.advanceTimersByTime(1);
cache.get('a');
vi.advanceTimersByTime(1);
cache.get('b');
vi.advanceTimersByTime(1);
cache.set('d', '4');
expect(cache.has('c')).toBe(false);
expect(cache.has('a')).toBe(true);
expect(cache.has('d')).toBe(true);
} finally {
vi.useRealTimers();
}
});
it('expires entries after TTL', () => {
vi.useFakeTimers();
try {
cache.set('a', 'value');
expect(cache.get('a')).toBe('value');
vi.advanceTimersByTime(1001);
expect(cache.get('a')).toBeUndefined();
} finally {
vi.useRealTimers();
}
});
it('tracks hit/miss stats', () => {
cache.set('a', '1');
cache.get('a');
cache.get('missing');
const stats = cache.stats();
expect(stats.hits).toBe(1);
expect(stats.misses).toBe(1);
expect(stats.hitRate).toBe(0.5);
expect(stats.size).toBe(1);
expect(stats.maxSize).toBe(3);
});
it('uses default options', () => {
const defaultCache = new MemoryCache<string>();
const stats = defaultCache.stats();
expect(stats.maxSize).toBe(1000);
});
});
-2
View File
@@ -1,2 +0,0 @@
export * from './types.js';
export * from './memory.js';
-101
View File
@@ -1,101 +0,0 @@
import type { CacheBackend, CacheOptions, CacheStats } from './types.js';
interface CacheEntry<V> {
value: V;
expiresAt: number;
lastAccessed: number;
}
const DEFAULT_MAX_SIZE = 1000;
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
export class MemoryCache<V = unknown> implements CacheBackend<V> {
private store = new Map<string, CacheEntry<V>>();
private maxSize: number;
private ttlMs: number;
private hitCount = 0;
private missCount = 0;
constructor(options?: CacheOptions) {
this.maxSize = options?.maxSize ?? DEFAULT_MAX_SIZE;
this.ttlMs = options?.ttlMs ?? DEFAULT_TTL_MS;
}
get(key: string): V | undefined {
const entry = this.store.get(key);
if (!entry) {
this.missCount++;
return undefined;
}
if (Date.now() > entry.expiresAt) {
this.store.delete(key);
this.missCount++;
return undefined;
}
entry.lastAccessed = Date.now();
this.hitCount++;
return entry.value;
}
set(key: string, value: V): void {
if (this.store.size >= this.maxSize && !this.store.has(key)) {
this.evictLRU();
}
const now = Date.now();
this.store.set(key, {
value,
expiresAt: now + this.ttlMs,
lastAccessed: now,
});
}
delete(key: string): boolean {
return this.store.delete(key);
}
has(key: string): boolean {
const entry = this.store.get(key);
if (!entry) return false;
if (Date.now() > entry.expiresAt) {
this.store.delete(key);
return false;
}
return true;
}
clear(): void {
this.store.clear();
this.hitCount = 0;
this.missCount = 0;
}
stats(): CacheStats {
const total = this.hitCount + this.missCount;
return {
hits: this.hitCount,
misses: this.missCount,
size: this.store.size,
maxSize: this.maxSize,
hitRate: total > 0 ? this.hitCount / total : 0,
};
}
private evictLRU(): void {
let oldestKey: string | null = null;
let oldestTime = Infinity;
for (const [key, entry] of this.store) {
if (entry.lastAccessed < oldestTime) {
oldestTime = entry.lastAccessed;
oldestKey = key;
}
}
if (oldestKey) {
this.store.delete(oldestKey);
}
}
}
-21
View File
@@ -1,21 +0,0 @@
export interface CacheStats {
hits: number;
misses: number;
size: number;
maxSize: number;
hitRate: number;
}
export interface CacheOptions {
maxSize?: number;
ttlMs?: number;
}
export interface CacheBackend<V = unknown> {
get(key: string): V | undefined;
set(key: string, value: V): void;
delete(key: string): boolean;
has(key: string): boolean;
clear(): void;
stats(): CacheStats;
}
-22
View File
@@ -1,22 +0,0 @@
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
@@ -1,162 +0,0 @@
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
@@ -1,268 +0,0 @@
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
@@ -1,23 +0,0 @@
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
@@ -1,314 +0,0 @@
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
@@ -1,257 +0,0 @@
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
@@ -1,106 +0,0 @@
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;
}
>;
}
-31
View File
@@ -89,34 +89,3 @@ 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';
// Hybrid Search (QMD-Inspired Vector + Keyword Search)
export * from './search/index.js';
// Federated Registry (External Skill Sources)
export * from './registry/index.js';
// Pluggable Cache Backend
export * from './cache/index.js';
// Multi-Signal Relevance Ranking
export * from './ranking/index.js';
// Enhanced SKILL.md Parser (References & Frontmatter)
export { discoverReferences, stripFrontmatter, parseSkillMd } from './parser/index.js';
export type { SkillReference, ParsedSkillContent } from './parser/index.js';
// Runtime Skill Injection
export * from './runtime/index.js';
@@ -1,94 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { stripFrontmatter, parseSkillMd, discoverReferences } from '../references.js';
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
readdirSync: vi.fn(),
statSync: vi.fn(),
readFileSync: vi.fn(),
}));
import { existsSync, readdirSync, statSync } from 'node:fs';
const mockExistsSync = vi.mocked(existsSync);
const mockReaddirSync = vi.mocked(readdirSync);
const mockStatSync = vi.mocked(statSync);
describe('stripFrontmatter', () => {
it('extracts frontmatter and body', () => {
const raw = `---
name: my-skill
version: 1.0
---
# My Skill
Content here.`;
const result = stripFrontmatter(raw);
expect(result.frontmatter.name).toBe('my-skill');
expect(result.frontmatter.version).toBe('1.0');
expect(result.body).toContain('# My Skill');
expect(result.body).toContain('Content here.');
});
it('returns empty frontmatter when no delimiters', () => {
const raw = '# Just content\n\nNo frontmatter.';
const result = stripFrontmatter(raw);
expect(result.frontmatter).toEqual({});
expect(result.body).toBe(raw);
});
it('handles empty frontmatter block', () => {
const raw = '---\n---\nBody text';
const result = stripFrontmatter(raw);
expect(result.frontmatter).toEqual({});
expect(result.body).toBe('Body text');
});
});
describe('parseSkillMd', () => {
it('parses raw content without skill dir', () => {
const raw = `---
name: test
---
Body content`;
const result = parseSkillMd(raw);
expect(result.frontmatter.name).toBe('test');
expect(result.body).toBe('Body content');
expect(result.references).toEqual([]);
expect(result.raw).toBe(raw);
});
});
describe('discoverReferences', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('finds files in reference directories', () => {
mockExistsSync.mockImplementation((p) => {
return String(p).endsWith('/examples');
});
mockStatSync.mockImplementation((p) => {
const path = String(p);
if (path.endsWith('/examples')) {
return { isDirectory: () => true, isFile: () => false } as any;
}
return { isDirectory: () => false, isFile: () => true } as any;
});
mockReaddirSync.mockReturnValue(['demo.ts', 'readme.md'] as any);
const refs = discoverReferences('/fake/skill');
expect(refs).toHaveLength(2);
expect(refs[0]).toEqual({
path: 'examples/demo.ts',
type: 'example',
name: 'demo.ts',
});
});
it('returns empty array when no reference dirs exist', () => {
mockExistsSync.mockReturnValue(false);
const refs = discoverReferences('/fake/skill');
expect(refs).toEqual([]);
});
});
-1
View File
@@ -1 +0,0 @@
export * from './references.js';
-105
View File
@@ -1,105 +0,0 @@
import { readdirSync, statSync, existsSync } from 'node:fs';
import { join } from 'node:path';
export interface SkillReference {
path: string;
type: 'example' | 'doc' | 'resource' | 'asset';
name: string;
}
export interface ParsedSkillContent {
frontmatter: Record<string, unknown>;
body: string;
references: SkillReference[];
raw: string;
}
const REFERENCE_DIRS = ['references', 'resources', 'docs', 'examples', 'assets', 'scripts'];
const DIR_TYPE_MAP: Record<string, SkillReference['type']> = {
references: 'resource',
resources: 'resource',
docs: 'doc',
examples: 'example',
assets: 'asset',
scripts: 'resource',
};
export function discoverReferences(skillDir: string): SkillReference[] {
const refs: SkillReference[] = [];
for (const dir of REFERENCE_DIRS) {
const fullPath = join(skillDir, dir);
if (!existsSync(fullPath)) continue;
try {
const stat = statSync(fullPath);
if (!stat.isDirectory()) continue;
} catch {
continue;
}
const type = DIR_TYPE_MAP[dir] || 'resource';
try {
const entries = readdirSync(fullPath);
for (const entry of entries) {
const entryPath = join(fullPath, entry);
try {
const entryStat = statSync(entryPath);
if (entryStat.isFile()) {
refs.push({
path: join(dir, entry),
type,
name: entry,
});
}
} catch {
continue;
}
}
} catch {
continue;
}
}
return refs;
}
export function stripFrontmatter(raw: string): { frontmatter: Record<string, unknown>; body: string } {
const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
if (!match) {
const emptyMatch = raw.match(/^---\r?\n---\r?\n?([\s\S]*)$/);
if (emptyMatch) {
return { frontmatter: {}, body: emptyMatch[1] };
}
return { frontmatter: {}, body: raw };
}
const fmBlock = match[1];
const body = match[2];
const frontmatter: Record<string, unknown> = {};
for (const line of fmBlock.split('\n')) {
const colonIdx = line.indexOf(':');
if (colonIdx === -1) continue;
const key = line.slice(0, colonIdx).trim();
const value = line.slice(colonIdx + 1).trim();
if (key) {
frontmatter[key] = value;
}
}
return { frontmatter, body };
}
export function parseSkillMd(raw: string, skillDir?: string): ParsedSkillContent {
const { frontmatter, body } = stripFrontmatter(raw);
const references = skillDir ? discoverReferences(skillDir) : [];
return {
frontmatter,
body,
references,
raw,
};
}
@@ -1,194 +0,0 @@
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,20 +4,17 @@ 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
@@ -1,248 +0,0 @@
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 };
}
@@ -1,85 +0,0 @@
import { describe, it, expect } from 'vitest';
import { RelevanceRanker } from '../relevance.js';
import type { RankableSkill } from '../relevance.js';
describe('RelevanceRanker', () => {
const ranker = new RelevanceRanker();
const skills: RankableSkill[] = [
{
name: 'react-performance',
description: 'Optimize React app performance',
content: 'Full guide on React performance optimization',
stars: 150,
references: ['examples/demo.ts'],
},
{
name: 'testing-basics',
description: 'Unit testing fundamentals',
stars: 10,
},
{
name: 'empty-skill',
},
];
it('ranks skills by relevance score', () => {
const results = ranker.rank(skills);
expect(results).toHaveLength(3);
expect(results[0].skill.name).toBe('react-performance');
expect(results[0].score).toBeGreaterThan(results[1].score);
});
it('gives max content score for description + content', () => {
const results = ranker.rank(skills);
const full = results.find((r) => r.skill.name === 'react-performance')!;
expect(full.breakdown.contentAvailability).toBe(40);
});
it('gives partial content score for description only', () => {
const results = ranker.rank(skills);
const partial = results.find((r) => r.skill.name === 'testing-basics')!;
expect(partial.breakdown.contentAvailability).toBe(20);
});
it('gives zero content score for empty skill', () => {
const results = ranker.rank(skills);
const empty = results.find((r) => r.skill.name === 'empty-skill')!;
expect(empty.breakdown.contentAvailability).toBe(0);
});
it('boosts exact name match on query', () => {
const results = ranker.rank(skills, 'react-performance');
const match = results.find((r) => r.skill.name === 'react-performance')!;
expect(match.breakdown.queryMatch).toBe(30);
});
it('gives partial query match for substring', () => {
const results = ranker.rank(skills, 'react');
const match = results.find((r) => r.skill.name === 'react-performance')!;
expect(match.breakdown.queryMatch).toBeGreaterThan(0);
expect(match.breakdown.queryMatch).toBeLessThan(30);
});
it('scores popularity via log scale', () => {
const results = ranker.rank(skills);
const popular = results.find((r) => r.skill.name === 'react-performance')!;
const less = results.find((r) => r.skill.name === 'testing-basics')!;
expect(popular.breakdown.popularity).toBeGreaterThan(less.breakdown.popularity);
});
it('scores references', () => {
const results = ranker.rank(skills);
const withRefs = results.find((r) => r.skill.name === 'react-performance')!;
const noRefs = results.find((r) => r.skill.name === 'testing-basics')!;
expect(withRefs.breakdown.referenceScore).toBeGreaterThan(0);
expect(noRefs.breakdown.referenceScore).toBe(0);
});
it('returns zero query match when no query provided', () => {
const results = ranker.rank(skills);
for (const r of results) {
expect(r.breakdown.queryMatch).toBe(0);
}
});
});
-1
View File
@@ -1 +0,0 @@
export * from './relevance.js';
-92
View File
@@ -1,92 +0,0 @@
export interface RankableSkill {
name: string;
description?: string;
content?: string;
stars?: number;
installs?: number;
references?: string[];
}
export interface RankedSkill<T extends RankableSkill = RankableSkill> {
skill: T;
score: number;
breakdown: ScoreBreakdown;
}
export interface ScoreBreakdown {
contentAvailability: number;
queryMatch: number;
popularity: number;
referenceScore: number;
}
const WEIGHTS = {
contentAvailability: 40,
queryMatch: 30,
popularity: 15,
references: 15,
} as const;
export class RelevanceRanker {
rank<T extends RankableSkill>(skills: T[], query?: string): RankedSkill<T>[] {
const results = skills.map((skill) => {
const breakdown = this.score(skill, query);
const score =
breakdown.contentAvailability +
breakdown.queryMatch +
breakdown.popularity +
breakdown.referenceScore;
return { skill, score, breakdown };
});
results.sort((a, b) => b.score - a.score);
return results;
}
private score(skill: RankableSkill, query?: string): ScoreBreakdown {
return {
contentAvailability: this.scoreContent(skill),
queryMatch: query ? this.scoreQuery(skill, query) : 0,
popularity: this.scorePopularity(skill),
referenceScore: this.scoreReferences(skill),
};
}
private scoreContent(skill: RankableSkill): number {
let score = 0;
if (skill.description && skill.description.length > 0) score += 20;
if (skill.content && skill.content.length > 0) score += 20;
return score;
}
private scoreQuery(skill: RankableSkill, query: string): number {
const q = query.toLowerCase();
const name = skill.name.toLowerCase();
if (name === q) return WEIGHTS.queryMatch;
if (name.includes(q) || q.includes(name)) {
return WEIGHTS.queryMatch * 0.7;
}
const desc = (skill.description || '').toLowerCase();
const content = (skill.content || '').toLowerCase();
const searchable = `${name} ${desc} ${content}`;
const words = q.split(/\s+/).filter(Boolean);
const matched = words.filter((w) => searchable.includes(w)).length;
if (words.length === 0) return 0;
return Math.round(WEIGHTS.queryMatch * (matched / words.length) * 0.6);
}
private scorePopularity(skill: RankableSkill): number {
const count = (skill.stars ?? 0) + (skill.installs ?? 0);
if (count <= 0) return 0;
return Math.min(WEIGHTS.popularity, Math.round(Math.log10(count + 1) * 5));
}
private scoreReferences(skill: RankableSkill): number {
if (!skill.references || skill.references.length === 0) return 0;
return Math.min(WEIGHTS.references, skill.references.length * 5);
}
}
-618
View File
@@ -1,618 +0,0 @@
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
@@ -1,14 +0,0 @@
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
@@ -1,227 +0,0 @@
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
@@ -1,115 +0,0 @@
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;
}
-233
View File
@@ -11,11 +11,8 @@ import type {
SearchOptions,
SearchResult,
FreshnessResult,
RecommendHybridSearchOptions,
RecommendHybridSearchResult,
} from './types.js';
import { DEFAULT_SCORING_WEIGHTS, TAG_TO_TECH, getTechTags } from './types.js';
import type { HybridSearchPipeline } from '../search/hybrid.js';
/**
* Recommendation engine for matching skills to project profiles
@@ -23,39 +20,16 @@ import type { HybridSearchPipeline } from '../search/hybrid.js';
export class RecommendationEngine {
private weights: ScoringWeights;
private index: SkillIndex | null = null;
private hybridPipeline: HybridSearchPipeline | null = null;
constructor(weights?: Partial<ScoringWeights>) {
this.weights = { ...DEFAULT_SCORING_WEIGHTS, ...weights };
}
/**
* Initialize hybrid search pipeline for vector + keyword search
*/
async initHybridSearch(): Promise<void> {
const { createHybridSearchPipeline } = await import('../search/hybrid.js');
this.hybridPipeline = createHybridSearchPipeline();
if (this.index) {
this.hybridPipeline.loadSkillsIndex(this.index);
}
await this.hybridPipeline.initialize();
}
/**
* Check if hybrid search is available
*/
isHybridSearchAvailable(): boolean {
return this.hybridPipeline !== null && this.hybridPipeline.isInitialized();
}
/**
* Load skill index from cache or generate from local skills
*/
loadIndex(index: SkillIndex): void {
this.index = index;
if (this.hybridPipeline) {
this.hybridPipeline.loadSkillsIndex(index);
}
}
/**
@@ -629,71 +603,6 @@ export class RecommendationEngine {
return { relevance, matchedTerms, snippet };
}
/**
* Hybrid search combining vector embeddings and keyword matching
*/
async hybridSearch(options: RecommendHybridSearchOptions): Promise<RecommendHybridSearchResult[]> {
const { query, limit = 10, hybrid = true, enableExpansion = false, enableReranking = false, filters } = options;
if (!hybrid || !this.hybridPipeline) {
const basicResults = this.search({ query, limit, semantic: true, filters });
return basicResults.map((r) => ({
...r,
hybridScore: r.relevance / 100,
}));
}
const response = await this.hybridPipeline.search({
query,
limit,
enableExpansion,
enableReranking,
});
let results = response.results.map((r) => ({
skill: r.skill,
relevance: r.relevance,
matchedTerms: r.matchedTerms,
snippet: r.snippet,
hybridScore: r.hybridScore,
vectorSimilarity: r.vectorSimilarity,
keywordScore: r.keywordScore,
rrfScore: r.rrfScore,
expandedTerms: r.expandedTerms,
}));
if (filters?.tags && filters.tags.length > 0) {
results = results.filter((r) =>
r.skill.tags?.some((t) => filters.tags!.includes(t))
);
}
if (filters?.verified) {
results = results.filter((r) => r.skill.verified);
}
if (filters?.minScore) {
results = results.filter((r) => r.relevance >= filters.minScore!);
}
return results.slice(0, limit);
}
/**
* Build hybrid search index from skills
*/
async buildHybridIndex(
onProgress?: (progress: { phase: string; current: number; total: number; message?: string }) => void
): Promise<void> {
if (!this.index) {
throw new Error('No skill index loaded. Call loadIndex() first.');
}
if (!this.hybridPipeline) {
await this.initHybridSearch();
}
await this.hybridPipeline!.buildIndex(this.index.skills, onProgress);
}
/**
* Check freshness of installed skills against project dependencies
*
@@ -756,145 +665,3 @@ 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);
}
+1 -6
View File
@@ -14,12 +14,7 @@
export * from './types.js';
export * from './engine.js';
export * from './fetcher.js';
export {
createRecommendationEngine,
RecommendationEngine,
ReasoningRecommendationEngine,
createReasoningRecommendationEngine,
} from './engine.js';
export { createRecommendationEngine, RecommendationEngine } from './engine.js';
export {
fetchSkillsFromRepo,
buildSkillIndex,
-64
View File
@@ -284,67 +284,3 @@ 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;
};
}
/**
* Hybrid search options for RecommendationEngine
*/
export interface RecommendHybridSearchOptions extends SearchOptions {
hybrid?: boolean;
enableExpansion?: boolean;
enableReranking?: boolean;
semanticWeight?: number;
keywordWeight?: number;
}
/**
* Hybrid search result with additional metadata for RecommendationEngine
*/
export interface RecommendHybridSearchResult extends SearchResult {
hybridScore?: number;
vectorSimilarity?: number;
keywordScore?: number;
rrfScore?: number;
expandedTerms?: string[];
}
@@ -1,87 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { CommunityRegistry } from '../community.js';
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
readFileSync: vi.fn(),
}));
import { existsSync, readFileSync } from 'node:fs';
const mockExistsSync = vi.mocked(existsSync);
const mockReadFileSync = vi.mocked(readFileSync);
const SAMPLE_SKILLS_MD = `# SkillKit Community Skills Registry
## Code Quality
- [code-simplifier](https://github.com/anthropics/skills) - Simplifies and refines code
- [code-review](https://github.com/anthropics/skills) - Automated code review
## Testing
- [testing-guide](https://github.com/anthropics/skills) - Unit testing fundamentals
- [e2e-testing](https://github.com/anthropics/skills) - End-to-end testing with Playwright
`;
describe('CommunityRegistry', () => {
beforeEach(() => {
vi.clearAllMocks();
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue(SAMPLE_SKILLS_MD);
});
it('parses SKILLS.md entries', async () => {
const registry = new CommunityRegistry('/fake/SKILLS.md');
const results = await registry.search('code');
expect(results.length).toBeGreaterThan(0);
expect(results[0].registry).toBe('community');
expect(results[0].name).toBe('code-simplifier');
});
it('searches by description', async () => {
const registry = new CommunityRegistry('/fake/SKILLS.md');
const results = await registry.search('Playwright');
expect(results.length).toBe(1);
expect(results[0].name).toBe('e2e-testing');
});
it('searches by category', async () => {
const registry = new CommunityRegistry('/fake/SKILLS.md');
const results = await registry.search('Testing');
expect(results.length).toBe(2);
});
it('respects limit', async () => {
const registry = new CommunityRegistry('/fake/SKILLS.md');
const results = await registry.search('code', { limit: 1 });
expect(results.length).toBe(1);
});
it('returns empty when no match', async () => {
const registry = new CommunityRegistry('/fake/SKILLS.md');
const results = await registry.search('nonexistent-xyz');
expect(results.length).toBe(0);
});
it('getAll returns all entries', () => {
const registry = new CommunityRegistry('/fake/SKILLS.md');
const all = registry.getAll();
expect(all.length).toBe(4);
});
it('getCategories returns unique categories', () => {
const registry = new CommunityRegistry('/fake/SKILLS.md');
const cats = registry.getCategories();
expect(cats).toContain('Code Quality');
expect(cats).toContain('Testing');
expect(cats.length).toBe(2);
});
it('handles missing file gracefully', async () => {
mockExistsSync.mockReturnValue(false);
const registry = new CommunityRegistry('/missing/SKILLS.md');
const results = await registry.search('anything');
expect(results).toEqual([]);
});
});
-97
View File
@@ -1,97 +0,0 @@
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { ExternalRegistry, ExternalSkill } from './index.js';
interface ParsedEntry {
name: string;
url: string;
description: string;
category: string;
}
export class CommunityRegistry implements ExternalRegistry {
name = 'community';
private entries: ParsedEntry[] = [];
private loaded = false;
constructor(private skillsMdPath?: string) {}
private load(): void {
if (this.loaded) return;
this.loaded = true;
const paths = this.skillsMdPath
? [this.skillsMdPath]
: [
join(process.cwd(), 'registry', 'SKILLS.md'),
join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..', '..', 'registry', 'SKILLS.md'),
];
for (const path of paths) {
if (!existsSync(path)) continue;
try {
const content = readFileSync(path, 'utf-8');
this.entries = this.parse(content);
return;
} catch {
continue;
}
}
}
private parse(content: string): ParsedEntry[] {
const results: ParsedEntry[] = [];
let currentCategory = '';
for (const line of content.split('\n')) {
const headerMatch = line.match(/^##\s+(.+)/);
if (headerMatch) {
currentCategory = headerMatch[1].trim();
continue;
}
const entryMatch = line.match(/^-\s+\[([^\]]+)\]\(([^)]+)\)\s*-\s*(.+)/);
if (entryMatch) {
results.push({
name: entryMatch[1].trim(),
url: entryMatch[2].trim(),
description: entryMatch[3].trim(),
category: currentCategory,
});
}
}
return results;
}
async search(query: string, options?: { limit?: number }): Promise<ExternalSkill[]> {
this.load();
const limit = options?.limit ?? 20;
const q = query.toLowerCase();
const matched = this.entries.filter(
(e) =>
e.name.toLowerCase().includes(q) ||
e.description.toLowerCase().includes(q) ||
e.category.toLowerCase().includes(q),
);
return matched.slice(0, limit).map((e) => ({
name: e.name,
description: e.description,
source: e.url,
registry: this.name,
}));
}
getAll(): ParsedEntry[] {
this.load();
return [...this.entries];
}
getCategories(): string[] {
this.load();
return [...new Set(this.entries.map((e) => e.category))];
}
}
-165
View File
@@ -1,165 +0,0 @@
export interface ExternalSkill {
name: string;
description: string;
source: string;
registry: string;
path?: string;
stars?: number;
updatedAt?: string;
}
export interface ExternalRegistry {
name: string;
search(query: string, options?: { limit?: number; timeoutMs?: number }): Promise<ExternalSkill[]>;
}
export interface FederatedResult {
skills: ExternalSkill[];
registries: string[];
total: number;
query: string;
}
export class RateLimitError extends Error {
constructor(registry: string) {
super(`Rate limited by ${registry} API. Authenticate with a token or wait before retrying.`);
this.name = 'RateLimitError';
}
}
export class GitHubSkillRegistry implements ExternalRegistry {
name = 'github';
private baseUrl = 'https://api.github.com';
async search(query: string, options?: { limit?: number; timeoutMs?: number }): Promise<ExternalSkill[]> {
const limit = options?.limit ?? 20;
const timeoutMs = options?.timeoutMs ?? 10_000;
const searchQuery = `SKILL.md ${query} in:path,file`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const headers: Record<string, string> = {
Accept: 'application/vnd.github.v3+json',
'User-Agent': 'skillkit-cli',
};
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const response = await fetch(
`${this.baseUrl}/search/code?q=${encodeURIComponent(searchQuery)}&per_page=${limit}`,
{
headers,
signal: controller.signal,
},
);
clearTimeout(timer);
if (!response.ok) {
if (response.status === 403) {
throw new RateLimitError(this.name);
}
return [];
}
const data = (await response.json()) as {
items?: Array<{
repository: {
full_name: string;
description?: string;
html_url: string;
stargazers_count?: number;
updated_at?: string;
};
path: string;
name: string;
}>;
};
if (!data.items) return [];
const seen = new Set<string>();
const skills: ExternalSkill[] = [];
for (const item of data.items) {
const repo = item.repository.full_name;
if (seen.has(repo)) continue;
seen.add(repo);
const pathParts = item.path.split('/');
const skillName =
pathParts.length > 1
? pathParts[pathParts.length - 2]
: repo.split('/').pop() || repo;
skills.push({
name: skillName,
description: item.repository.description || '',
source: item.repository.html_url,
registry: this.name,
path: item.path,
stars: item.repository.stargazers_count,
updatedAt: item.repository.updated_at,
});
}
return skills;
} catch (err) {
clearTimeout(timer);
if (err instanceof RateLimitError) throw err;
return [];
}
}
}
export { CommunityRegistry } from './community.js';
export class FederatedSearch {
private registries: ExternalRegistry[] = [];
addRegistry(registry: ExternalRegistry): void {
this.registries.push(registry);
}
async search(query: string, options?: { limit?: number }): Promise<FederatedResult> {
const limit = options?.limit ?? 20;
const results = await Promise.allSettled(
this.registries.map((r) => r.search(query, { limit })),
);
const allSkills: ExternalSkill[] = [];
const activeRegistries: string[] = [];
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.status === 'fulfilled' && result.value.length > 0) {
allSkills.push(...result.value);
activeRegistries.push(this.registries[i].name);
} else if (result.status === 'rejected' && result.reason instanceof RateLimitError) {
throw result.reason;
}
}
const seen = new Set<string>();
const deduplicated: ExternalSkill[] = [];
for (const skill of allSkills) {
const key = `${skill.source}:${skill.name}`;
if (!seen.has(key)) {
seen.add(key);
deduplicated.push(skill);
}
}
deduplicated.sort((a, b) => (b.stars ?? 0) - (a.stars ?? 0));
return {
skills: deduplicated.slice(0, limit),
registries: activeRegistries,
total: deduplicated.length,
query,
};
}
}
@@ -1,113 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { SkillInjector } from '../injector.js';
const mockFetch = vi.fn();
global.fetch = mockFetch;
describe('SkillInjector', () => {
let injector: SkillInjector;
beforeEach(() => {
injector = new SkillInjector(60_000);
mockFetch.mockReset();
});
afterEach(() => {
injector.clearCache();
});
const skillMd = `---
name: test-skill
version: 1.0
---
# Test Skill
This is the body content.`;
it('fetches and parses a SKILL.md from GitHub', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => skillMd,
});
const result = await injector.fetch('owner/repo', 'test-skill');
expect(result.source).toEqual({ owner: 'owner', repo: 'repo' });
expect(result.skillId).toBe('test-skill');
expect(result.parsed.frontmatter.name).toBe('test-skill');
expect(result.parsed.body).toContain('# Test Skill');
expect(result.fetchedAt).toBeGreaterThan(0);
});
it('returns cached result on subsequent calls', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => skillMd,
});
await injector.fetch('owner/repo', 'test-skill');
const second = await injector.fetch('owner/repo', 'test-skill');
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(second.parsed.body).toContain('# Test Skill');
});
it('inject() returns body without frontmatter', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => skillMd,
});
const body = await injector.inject('owner/repo', 'test-skill');
expect(body).toContain('# Test Skill');
expect(body).not.toContain('---');
expect(body).not.toContain('name: test-skill');
});
it('throws on invalid source format', async () => {
await expect(injector.fetch('invalid', 'skill')).rejects.toThrow('Invalid source format');
});
it('throws when SKILL.md not found after trying all paths', async () => {
mockFetch.mockResolvedValue({ ok: false, status: 404 });
await expect(injector.fetch('owner/repo', 'missing')).rejects.toThrow('SKILL.md not found');
});
it('tries multiple paths before failing', async () => {
mockFetch
.mockResolvedValueOnce({ ok: false, status: 404 })
.mockResolvedValueOnce({ ok: false, status: 404 })
.mockResolvedValueOnce({
ok: true,
text: async () => skillMd,
});
const result = await injector.fetch('owner/repo', 'skill');
expect(mockFetch).toHaveBeenCalledTimes(3);
expect(result.parsed.body).toContain('# Test Skill');
});
it('reports cache stats', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => skillMd,
});
await injector.fetch('owner/repo', 'skill');
await injector.fetch('owner/repo', 'skill');
const stats = injector.cacheStats();
expect(stats.size).toBe(1);
expect(stats.hits).toBe(1);
expect(stats.misses).toBe(1);
});
it('parses full GitHub URLs as source', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => skillMd,
});
const result = await injector.fetch('https://github.com/owner/repo', 'skill');
expect(result.source).toEqual({ owner: 'owner', repo: 'repo' });
});
});
-1
View File
@@ -1 +0,0 @@
export * from './injector.js';
-99
View File
@@ -1,99 +0,0 @@
import { MemoryCache } from '../cache/memory.js';
import { parseSkillMd } from '../parser/references.js';
import type { ParsedSkillContent } from '../parser/references.js';
export interface RuntimeSkillSource {
owner: string;
repo: string;
}
export interface FetchedSkill {
source: RuntimeSkillSource;
skillId: string;
parsed: ParsedSkillContent;
fetchedAt: number;
}
function parseSource(source: string): RuntimeSkillSource {
const parts = source.replace(/^https?:\/\/github\.com\//, '').split('/');
if (parts.length < 2) {
throw new Error(`Invalid source format: "${source}". Expected "owner/repo".`);
}
return { owner: parts[0], repo: parts[1] };
}
export class SkillInjector {
private cache: MemoryCache<FetchedSkill>;
constructor(cacheTtlMs?: number) {
this.cache = new MemoryCache<FetchedSkill>({
maxSize: 200,
ttlMs: cacheTtlMs ?? 24 * 60 * 60 * 1000,
});
}
async fetch(source: string, skillId: string): Promise<FetchedSkill> {
const cacheKey = `${source}:${skillId}`;
const cached = this.cache.get(cacheKey);
if (cached) return cached;
const { owner, repo } = parseSource(source);
const raw = await this.fetchRawSkillMd(owner, repo, skillId);
const parsed = parseSkillMd(raw);
const result: FetchedSkill = {
source: { owner, repo },
skillId,
parsed,
fetchedAt: Date.now(),
};
this.cache.set(cacheKey, result);
return result;
}
async inject(source: string, skillId: string): Promise<string> {
const fetched = await this.fetch(source, skillId);
return fetched.parsed.body;
}
private async fetchRawSkillMd(owner: string, repo: string, skillId: string): Promise<string> {
const paths = [
`${skillId}/SKILL.md`,
`skills/${skillId}/SKILL.md`,
`SKILL.md`,
];
const headers: Record<string, string> = {
Accept: 'application/vnd.github.v3.raw',
'User-Agent': 'skillkit-runtime',
};
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
if (token) {
headers.Authorization = `Bearer ${token}`;
}
for (const path of paths) {
const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`;
try {
const response = await fetch(url, { headers });
if (response.ok) {
return await response.text();
}
} catch {
continue;
}
}
throw new Error(`SKILL.md not found in ${owner}/${repo} for skill "${skillId}"`);
}
clearCache(): void {
this.cache.clear();
}
cacheStats() {
return this.cache.stats();
}
}
@@ -1,217 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { EmbeddingService } from '../embeddings.js';
import type { SkillSummary } from '../../recommend/types.js';
describe('EmbeddingService', () => {
describe('cosineSimilarity', () => {
let service: EmbeddingService;
beforeEach(() => {
service = new EmbeddingService();
});
it('should return 1 for identical vectors', () => {
const a = new Float32Array([1, 0, 0]);
const b = new Float32Array([1, 0, 0]);
const similarity = service.cosineSimilarity(a, b);
expect(similarity).toBeCloseTo(1, 5);
});
it('should return 0 for orthogonal vectors', () => {
const a = new Float32Array([1, 0, 0]);
const b = new Float32Array([0, 1, 0]);
const similarity = service.cosineSimilarity(a, b);
expect(similarity).toBeCloseTo(0, 5);
});
it('should return -1 for opposite vectors', () => {
const a = new Float32Array([1, 0, 0]);
const b = new Float32Array([-1, 0, 0]);
const similarity = service.cosineSimilarity(a, b);
expect(similarity).toBeCloseTo(-1, 5);
});
it('should handle normalized vectors', () => {
const a = new Float32Array([0.5, 0.5, 0.5, 0.5]);
const b = new Float32Array([0.5, 0.5, 0.5, 0.5]);
const similarity = service.cosineSimilarity(a, b);
expect(similarity).toBeCloseTo(1, 5);
});
it('should throw for mismatched dimensions', () => {
const a = new Float32Array([1, 0]);
const b = new Float32Array([1, 0, 0]);
expect(() => service.cosineSimilarity(a, b)).toThrow('Vector dimensions mismatch');
});
it('should return 0 for zero vectors', () => {
const a = new Float32Array([0, 0, 0]);
const b = new Float32Array([1, 0, 0]);
const similarity = service.cosineSimilarity(a, b);
expect(similarity).toBe(0);
});
});
describe('initialization state', () => {
it('should not be initialized by default', () => {
const service = new EmbeddingService();
expect(service.isInitialized()).toBe(false);
});
it('should return default dimensions', () => {
const service = new EmbeddingService();
expect(service.getDimensions()).toBe(768);
});
});
describe('skill text building', () => {
it('should handle skill with all fields', async () => {
const service = new EmbeddingService();
const skill: SkillSummary = {
name: 'test-skill',
description: 'A test skill',
tags: ['tag1', 'tag2'],
compatibility: {
frameworks: ['react'],
languages: ['typescript'],
libraries: ['lodash'],
},
popularity: 100,
quality: 80,
verified: true,
};
const buildSkillText = (s: SkillSummary): string => {
const parts: string[] = [s.name];
if (s.description) parts.push(s.description);
if (s.tags?.length) parts.push(s.tags.join(' '));
if (s.compatibility?.frameworks?.length) parts.push(s.compatibility.frameworks.join(' '));
if (s.compatibility?.languages?.length) parts.push(s.compatibility.languages.join(' '));
if (s.compatibility?.libraries?.length) parts.push(s.compatibility.libraries.join(' '));
return parts.join(' ').toLowerCase();
};
const text = buildSkillText(skill);
expect(text).toContain('test-skill');
expect(text).toContain('a test skill');
expect(text).toContain('tag1');
expect(text).toContain('react');
expect(text).toContain('typescript');
expect(text).toContain('lodash');
});
it('should handle skill with minimal fields', () => {
const skill: SkillSummary = {
name: 'minimal-skill',
tags: [],
popularity: 0,
quality: 50,
verified: false,
};
const buildSkillText = (s: SkillSummary): string => {
const parts: string[] = [s.name];
if (s.description) parts.push(s.description);
if (s.tags?.length) parts.push(s.tags.join(' '));
return parts.join(' ').toLowerCase();
};
const text = buildSkillText(skill);
expect(text).toBe('minimal-skill');
});
});
});
describe('EmbeddingService chunking', () => {
it('should split text into chunks', () => {
const chunkText = (
text: string,
config = { maxTokens: 100, overlapPercent: 15, minChunkSize: 10 }
) => {
const lines = text.split('\n');
const chunks: { content: string; startLine: number; endLine: number }[] = [];
const avgCharsPerToken = 4;
const maxCharsPerChunk = config.maxTokens * avgCharsPerToken;
const overlapChars = Math.floor(maxCharsPerChunk * (config.overlapPercent / 100));
let currentChunk: string[] = [];
let currentChars = 0;
let startLine = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineChars = line.length + 1;
if (currentChars + lineChars > maxCharsPerChunk && currentChunk.length > 0) {
const content = currentChunk.join('\n');
if (content.length >= config.minChunkSize) {
chunks.push({ content, startLine, endLine: i - 1 });
}
const overlapLines: string[] = [];
let overlapCharsCount = 0;
for (let j = currentChunk.length - 1; j >= 0 && overlapCharsCount < overlapChars; j--) {
overlapLines.unshift(currentChunk[j]);
overlapCharsCount += currentChunk[j].length + 1;
}
currentChunk = overlapLines;
currentChars = overlapCharsCount;
startLine = i - overlapLines.length;
}
currentChunk.push(line);
currentChars += lineChars;
}
if (currentChunk.length > 0) {
const content = currentChunk.join('\n');
if (content.length >= config.minChunkSize) {
chunks.push({ content, startLine, endLine: lines.length - 1 });
}
}
return chunks;
};
const longText = Array(50).fill('This is a line of text for testing.').join('\n');
const chunks = chunkText(longText);
expect(chunks.length).toBeGreaterThan(1);
chunks.forEach((chunk) => {
expect(chunk.content.length).toBeLessThanOrEqual(400);
expect(chunk.startLine).toBeGreaterThanOrEqual(0);
expect(chunk.endLine).toBeGreaterThanOrEqual(chunk.startLine);
});
});
it('should not chunk short text', () => {
const chunkText = (
text: string,
config = { maxTokens: 800, overlapPercent: 15, minChunkSize: 100 }
) => {
const lines = text.split('\n');
if (text.length < config.maxTokens * 4) {
if (text.length >= config.minChunkSize) {
return [{ content: text, startLine: 0, endLine: lines.length - 1 }];
}
return [];
}
return [{ content: text, startLine: 0, endLine: lines.length - 1 }];
};
const shortText = 'This is a short text that should not be chunked.';
const chunks = chunkText(shortText, { maxTokens: 800, overlapPercent: 15, minChunkSize: 10 });
expect(chunks.length).toBe(1);
expect(chunks[0].content).toBe(shortText);
});
});
@@ -1,100 +0,0 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { QueryExpander, expandQuerySimple } from '../expansion.js';
describe('QueryExpander', () => {
let expander: QueryExpander;
beforeEach(() => {
expander = new QueryExpander();
});
afterEach(() => {
expander.clearCache();
});
describe('expandQuerySimple (without LLM)', () => {
it('should expand "auth" to authentication-related terms', () => {
const result = expandQuerySimple('auth');
expect(result.original).toBe('auth');
expect(result.variations.length).toBeGreaterThan(0);
expect(result.variations.some((v) => v.includes('authentication'))).toBe(true);
});
it('should expand "api" to related terms', () => {
const result = expandQuerySimple('api');
expect(result.original).toBe('api');
expect(result.variations.some((v) => v.includes('rest') || v.includes('endpoint'))).toBe(true);
});
it('should expand "test" to testing-related terms', () => {
const result = expandQuerySimple('testing');
expect(result.original).toBe('testing');
expect(result.variations.some((v) => v.includes('test') || v.includes('unit'))).toBe(true);
});
it('should handle queries without synonyms', () => {
const result = expandQuerySimple('xyz123unique');
expect(result.original).toBe('xyz123unique');
expect(result.variations).toEqual([]);
expect(result.weights).toEqual([2.0]);
});
it('should give original query weight of 2.0', () => {
const result = expandQuerySimple('auth');
expect(result.weights[0]).toBe(2.0);
for (let i = 1; i < result.weights.length; i++) {
expect(result.weights[i]).toBe(1.0);
}
});
it('should limit variations to 3', () => {
const result = expandQuerySimple('auth');
expect(result.variations.length).toBeLessThanOrEqual(3);
});
});
describe('expand (fallback without LLM)', () => {
it('should return expanded query without LLM initialization', async () => {
const result = await expander.expand('auth');
expect(result.original).toBe('auth');
expect(result.variations.length).toBeGreaterThan(0);
});
it('should cache results', async () => {
const result1 = await expander.expand('auth');
const result2 = await expander.expand('auth');
expect(result1).toEqual(result2);
});
it('should handle case-insensitive caching', async () => {
const result1 = await expander.expand('Auth');
const result2 = await expander.expand('AUTH');
expect(result1.original).toBe('Auth');
expect(result2.original).toBe('AUTH');
});
});
describe('clearCache', () => {
it('should clear the expansion cache', async () => {
await expander.expand('auth');
expander.clearCache();
const result = await expander.expand('auth');
expect(result).toBeDefined();
});
});
describe('isInitialized', () => {
it('should return false when not initialized with LLM', () => {
expect(expander.isInitialized()).toBe(false);
});
});
});
@@ -1,244 +0,0 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import type { SkillSummary, SkillIndex } from '../../recommend/types.js';
const mockSkills: SkillSummary[] = [
{
name: 'react-auth',
description: 'Authentication utilities for React applications',
tags: ['react', 'auth', 'authentication'],
compatibility: {
frameworks: ['react'],
languages: ['typescript', 'javascript'],
libraries: ['next-auth'],
},
popularity: 500,
quality: 80,
verified: true,
},
{
name: 'vue-forms',
description: 'Form validation library for Vue',
tags: ['vue', 'forms', 'validation'],
compatibility: {
frameworks: ['vue'],
languages: ['typescript', 'javascript'],
libraries: [],
},
popularity: 300,
quality: 75,
verified: false,
},
{
name: 'api-testing',
description: 'API testing utilities for REST endpoints',
tags: ['testing', 'api', 'rest'],
compatibility: {
frameworks: [],
languages: ['typescript'],
libraries: ['jest', 'supertest'],
},
popularity: 400,
quality: 85,
verified: true,
},
{
name: 'login-helper',
description: 'Helper functions for login and authentication flows',
tags: ['auth', 'login', 'oauth'],
compatibility: {
frameworks: ['react', 'vue'],
languages: ['typescript'],
libraries: [],
},
popularity: 200,
quality: 70,
verified: false,
},
];
const mockIndex: SkillIndex = {
version: 1,
lastUpdated: new Date().toISOString(),
skills: mockSkills,
sources: [],
};
vi.mock('better-sqlite3', () => {
return {
default: vi.fn().mockImplementation(() => {
throw new Error("Cannot find module 'better-sqlite3'");
}),
};
});
vi.mock('sqlite-vec', () => {
return {
load: vi.fn(),
};
});
vi.mock('node-llama-cpp', () => {
return {
getLlama: vi.fn().mockImplementation(() => {
throw new Error("Cannot find package 'node-llama-cpp'");
}),
};
});
describe('HybridSearchPipeline', () => {
let HybridSearchPipeline: typeof import('../hybrid.js').HybridSearchPipeline;
let createHybridSearchPipeline: typeof import('../hybrid.js').createHybridSearchPipeline;
let pipeline: InstanceType<typeof HybridSearchPipeline>;
beforeEach(async () => {
const module = await import('../hybrid.js');
HybridSearchPipeline = module.HybridSearchPipeline;
createHybridSearchPipeline = module.createHybridSearchPipeline;
pipeline = createHybridSearchPipeline();
});
afterEach(async () => {
if (pipeline) {
await pipeline.dispose();
}
});
describe('initialization', () => {
it('should create a pipeline', () => {
expect(pipeline).toBeInstanceOf(HybridSearchPipeline);
});
it('should not be initialized before calling initialize()', () => {
expect(pipeline.isInitialized()).toBe(false);
});
it('should be initialized after calling initialize()', async () => {
await pipeline.initialize();
expect(pipeline.isInitialized()).toBe(true);
});
it('should load skills index', async () => {
pipeline.loadSkillsIndex(mockIndex);
const stats = pipeline.getStats();
expect(stats.skillCount).toBe(mockSkills.length);
});
});
describe('search (keyword-only fallback)', () => {
beforeEach(async () => {
pipeline.loadSkillsIndex(mockIndex);
await pipeline.initialize();
});
it('should find skills matching query', async () => {
const response = await pipeline.search({ query: 'authentication' });
expect(response.results.length).toBeGreaterThan(0);
expect(response.results.some((r) => r.skill.name === 'react-auth')).toBe(true);
});
it('should find skills by tag', async () => {
const response = await pipeline.search({ query: 'react' });
expect(response.results.length).toBeGreaterThan(0);
expect(response.results.some((r) => r.skill.tags?.includes('react'))).toBe(true);
});
it('should respect limit parameter', async () => {
const response = await pipeline.search({ query: 'auth', limit: 2 });
expect(response.results.length).toBeLessThanOrEqual(2);
});
it('should include timing information', async () => {
const response = await pipeline.search({ query: 'test' });
expect(typeof response.timing.totalMs).toBe('number');
expect(response.timing.totalMs).toBeGreaterThanOrEqual(0);
expect(response.timing.keywordSearchMs).toBeGreaterThanOrEqual(0);
});
it('should include stats', async () => {
const response = await pipeline.search({ query: 'auth' });
expect(response.stats.candidatesFromKeyword).toBeGreaterThan(0);
expect(response.stats.totalMerged).toBeGreaterThan(0);
});
it('should return original query in response', async () => {
const response = await pipeline.search({ query: 'authentication' });
expect(response.query.original).toBe('authentication');
});
});
describe('search with expansion', () => {
beforeEach(async () => {
pipeline.loadSkillsIndex(mockIndex);
await pipeline.initialize();
});
it('should expand query and find more results', async () => {
const response = await pipeline.search({
query: 'auth',
enableExpansion: true,
});
expect(response.results.length).toBeGreaterThan(0);
expect(response.query.expanded).toBeDefined();
});
it('should include expanded terms in response', async () => {
const response = await pipeline.search({
query: 'auth',
enableExpansion: true,
});
if (response.query.expanded) {
expect(response.query.expanded.original).toBe('auth');
expect(response.query.expanded.weights[0]).toBe(2.0);
}
});
});
describe('getStats', () => {
it('should return stats before initialization', () => {
const stats = pipeline.getStats();
expect(stats.initialized).toBe(false);
expect(stats.skillCount).toBe(0);
});
it('should return updated stats after loading index', async () => {
pipeline.loadSkillsIndex(mockIndex);
await pipeline.initialize();
const stats = pipeline.getStats();
expect(stats.initialized).toBe(true);
expect(stats.skillCount).toBe(mockSkills.length);
});
});
});
describe('hybridSearch helper', () => {
let hybridSearch: typeof import('../hybrid.js').hybridSearch;
beforeEach(async () => {
const module = await import('../hybrid.js');
hybridSearch = module.hybridSearch;
});
it('should perform search on skills array', async () => {
const response = await hybridSearch(mockSkills, 'react');
expect(response.results.length).toBeGreaterThan(0);
expect(response.query.original).toBe('react');
});
it('should respect options', async () => {
const response = await hybridSearch(mockSkills, 'auth', {
limit: 1,
});
expect(response.results.length).toBe(1);
});
});
@@ -1,276 +0,0 @@
import { describe, it, expect } from 'vitest';
import {
computeRRFScore,
fuseWithRRF,
normalizeScores,
weightedCombine,
applyPositionAwareBlending,
getRankFromScore,
mergeRankings,
type RankerResult,
type RRFInput,
} from '../rrf.js';
describe('RRF (Reciprocal Rank Fusion)', () => {
describe('computeRRFScore', () => {
it('should compute RRF score for a single rank', () => {
const score = computeRRFScore([1], 60);
expect(score).toBeCloseTo(1 / 61, 5);
});
it('should sum RRF scores for multiple ranks', () => {
const score = computeRRFScore([1, 2, 3], 60);
const expected = 1 / 61 + 1 / 62 + 1 / 63;
expect(score).toBeCloseTo(expected, 5);
});
it('should use custom k value', () => {
const scoreK60 = computeRRFScore([1], 60);
const scoreK30 = computeRRFScore([1], 30);
expect(scoreK30).toBeGreaterThan(scoreK60);
});
it('should return 0 for empty ranks', () => {
const score = computeRRFScore([]);
expect(score).toBe(0);
});
});
describe('fuseWithRRF', () => {
it('should fuse results from multiple rankers', () => {
const inputs: RRFInput[] = [
{
source: 'vector',
results: [
{ skillName: 'skill-a', score: 0.9 },
{ skillName: 'skill-b', score: 0.8 },
{ skillName: 'skill-c', score: 0.7 },
],
},
{
source: 'keyword',
results: [
{ skillName: 'skill-b', score: 90 },
{ skillName: 'skill-a', score: 80 },
{ skillName: 'skill-d', score: 70 },
],
},
];
const rankings = fuseWithRRF(inputs, 60);
expect(rankings.length).toBe(4);
expect(rankings[0].skillName).toBe('skill-a');
expect(rankings[1].skillName).toBe('skill-b');
});
it('should include rank information from each source', () => {
const inputs: RRFInput[] = [
{
source: 'vector',
results: [{ skillName: 'skill-a', score: 0.9 }],
},
{
source: 'keyword',
results: [{ skillName: 'skill-a', score: 90 }],
},
];
const rankings = fuseWithRRF(inputs);
expect(rankings[0].ranks).toHaveLength(2);
expect(rankings[0].ranks.map((r) => r.source)).toContain('vector');
expect(rankings[0].ranks.map((r) => r.source)).toContain('keyword');
});
it('should handle skills appearing in only one ranker', () => {
const inputs: RRFInput[] = [
{
source: 'vector',
results: [{ skillName: 'skill-a', score: 0.9 }],
},
{
source: 'keyword',
results: [{ skillName: 'skill-b', score: 90 }],
},
];
const rankings = fuseWithRRF(inputs);
expect(rankings).toHaveLength(2);
const skillAInfo = rankings.find((r) => r.skillName === 'skill-a');
const skillBInfo = rankings.find((r) => r.skillName === 'skill-b');
expect(skillAInfo?.ranks).toHaveLength(1);
expect(skillBInfo?.ranks).toHaveLength(1);
});
});
describe('normalizeScores', () => {
it('should normalize scores to 0-1 range', () => {
const results: RankerResult[] = [
{ skillName: 'a', score: 100 },
{ skillName: 'b', score: 50 },
{ skillName: 'c', score: 0 },
];
const normalized = normalizeScores(results);
expect(normalized[0].score).toBe(1);
expect(normalized[1].score).toBe(0.5);
expect(normalized[2].score).toBe(0);
});
it('should handle all same scores', () => {
const results: RankerResult[] = [
{ skillName: 'a', score: 50 },
{ skillName: 'b', score: 50 },
];
const normalized = normalizeScores(results);
expect(normalized[0].score).toBe(1);
expect(normalized[1].score).toBe(1);
});
it('should return empty array for empty input', () => {
const normalized = normalizeScores([]);
expect(normalized).toEqual([]);
});
});
describe('weightedCombine', () => {
it('should combine results with weights', () => {
const inputs: RRFInput[] = [
{
source: 'vector',
results: [
{ skillName: 'a', score: 100 },
{ skillName: 'b', score: 50 },
],
},
{
source: 'keyword',
results: [
{ skillName: 'b', score: 100 },
{ skillName: 'a', score: 50 },
],
},
];
const combined = weightedCombine(inputs, { vector: 0.6, keyword: 0.4 });
expect(combined).toHaveLength(2);
const skillA = combined.find((r) => r.skillName === 'a')!;
const skillB = combined.find((r) => r.skillName === 'b')!;
expect(skillA.score).toBeCloseTo(0.6 * 1 + 0.4 * 0, 5);
expect(skillB.score).toBeCloseTo(0.6 * 0 + 0.4 * 1, 5);
});
it('should default to weight 1 for unknown sources', () => {
const inputs: RRFInput[] = [
{
source: 'unknown',
results: [{ skillName: 'a', score: 100 }],
},
];
const combined = weightedCombine(inputs, {});
expect(combined[0].score).toBe(1);
});
});
describe('applyPositionAwareBlending', () => {
it('should apply different weights based on position', () => {
const retrievalScores = new Map([
['a', 0.9],
['b', 0.8],
['c', 0.7],
['d', 0.6],
]);
const rerankerScores = new Map([
['a', 0.5],
['b', 0.6],
['c', 0.7],
['d', 0.8],
]);
const sortedSkills = ['a', 'b', 'c', 'd'];
const blended = applyPositionAwareBlending(
retrievalScores,
rerankerScores,
sortedSkills
);
const scoreA = blended.get('a')!;
expect(scoreA).toBeCloseTo(0.9 * 0.75 + 0.5 * 0.25, 5);
const scoreD = blended.get('d')!;
expect(scoreD).toBeCloseTo(0.6 * 0.6 + 0.8 * 0.4, 5);
});
it('should handle missing scores', () => {
const retrievalScores = new Map([['a', 0.9]]);
const rerankerScores = new Map<string, number>();
const sortedSkills = ['a'];
const blended = applyPositionAwareBlending(
retrievalScores,
rerankerScores,
sortedSkills
);
expect(blended.get('a')).toBeCloseTo(0.9 * 0.75, 5);
});
});
describe('getRankFromScore', () => {
it('should return correct rank for a skill', () => {
const results: RankerResult[] = [
{ skillName: 'a', score: 90 },
{ skillName: 'b', score: 80 },
{ skillName: 'c', score: 70 },
];
expect(getRankFromScore('a', results)).toBe(1);
expect(getRankFromScore('b', results)).toBe(2);
expect(getRankFromScore('c', results)).toBe(3);
});
it('should return length+1 for missing skill', () => {
const results: RankerResult[] = [
{ skillName: 'a', score: 90 },
{ skillName: 'b', score: 80 },
];
expect(getRankFromScore('missing', results)).toBe(3);
});
});
describe('mergeRankings', () => {
it('should merge primary and secondary rankings with weights', () => {
const primary = [
{ skillName: 'a', rrfScore: 0.1, ranks: [{ source: 'primary', rank: 1 }] },
{ skillName: 'b', rrfScore: 0.05, ranks: [{ source: 'primary', rank: 2 }] },
];
const secondary = [
{ skillName: 'b', rrfScore: 0.1, ranks: [{ source: 'secondary', rank: 1 }] },
{ skillName: 'c', rrfScore: 0.05, ranks: [{ source: 'secondary', rank: 2 }] },
];
const merged = mergeRankings(primary, secondary, 0.7);
expect(merged).toHaveLength(3);
const skillA = merged.find((r) => r.skillName === 'a')!;
const skillB = merged.find((r) => r.skillName === 'b')!;
const skillC = merged.find((r) => r.skillName === 'c')!;
expect(skillA.rrfScore).toBeCloseTo(0.1 * 0.7, 5);
expect(skillB.rrfScore).toBeCloseTo(0.05 * 0.7 + 0.1 * 0.3, 5);
expect(skillC.rrfScore).toBeCloseTo(0.05 * 0.3, 5);
});
});
});

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