From 5bd7ebf607ca08c16819f4c83b6b2dd0298f85bd Mon Sep 17 00:00:00 2001 From: Rohit Ghumare <48523873+rohitg00@users.noreply.github.com> Date: Tue, 3 Feb 2026 13:48:35 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20viral=20growth=20features=20=E2=80=94?= =?UTF-8?q?=20quick=20setup,=20badges,=20matrix,=20SKILL.md,=20federated?= =?UTF-8?q?=20search=20(#41)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add viral growth features (quick setup, badges, matrix, SKILL.md, federated search) Tier 2: skillkit quick zero-friction entry, shareable badge generator, agent compatibility matrix on website. Tier 3: reposition as npm for agent skills, SKILL.md validate/init/check commands, federated GitHub skill search with --federated flag on find. * fix: matrix filtering, path traversal, cross-platform paths, fetch timeout - CompatibilityMatrix: query matching agents now shows all categories (and vice versa) instead of hiding both dimensions independently - quick.ts: sanitize skill names and validate targetInstallPath stays inside installDir before rmSync/cpSync/symlinkSync - skillmd.ts: use path.relative() instead of string replace for cross-platform path display - registry: add AbortController timeout (10s default) and distinct RateLimitError on 403 instead of silent empty return - find.ts: handle RateLimitError with user-facing message - Add quick-security.test.ts regression tests for path traversal * fix: harden isPathInside with path.resolve, propagate RateLimitError - isPathInside now uses path.resolve() + path.sep comparison instead of naive string replacement, fixing detection of paths completely outside the parent directory (both packages/core and src/core copies) - FederatedSearch.search re-throws RateLimitError from rejected Promise.allSettled results so callers (find.ts) can handle 403s - Updated security test to use the corrected isPathInside logic * fix: use GITHUB_TOKEN/GH_TOKEN for authenticated GitHub API requests GitHubSkillRegistry now reads GITHUB_TOKEN or GH_TOKEN from env and sends Bearer auth header, raising the rate limit from 10 to 30 req/min for code search. Matches the guidance shown to users on 403 errors. --- README.md | 7 +- apps/skillkit/src/cli.ts | 9 + docs/skillkit/App.tsx | 26 ++ docs/skillkit/components/BadgeGenerator.tsx | 201 ++++++++ .../components/CompatibilityMatrix.tsx | 351 ++++++++++++++ docs/skillkit/components/Features.tsx | 4 +- docs/skillkit/components/Hero.tsx | 10 +- package.json | 10 +- .../cli/src/__tests__/quick-security.test.ts | 69 +++ packages/cli/src/badge.ts | 39 ++ packages/cli/src/commands/find.ts | 43 +- packages/cli/src/commands/index.ts | 6 + packages/cli/src/commands/quick.ts | 375 +++++++++++++++ packages/cli/src/commands/skillmd.ts | 440 ++++++++++++++++++ packages/core/src/index.ts | 3 + packages/core/src/registry/index.ts | 163 +++++++ packages/core/src/skills.ts | 7 +- src/core/skills.ts | 7 +- 18 files changed, 1751 insertions(+), 19 deletions(-) create mode 100644 docs/skillkit/components/BadgeGenerator.tsx create mode 100644 docs/skillkit/components/CompatibilityMatrix.tsx create mode 100644 packages/cli/src/__tests__/quick-security.test.ts create mode 100644 packages/cli/src/badge.ts create mode 100644 packages/cli/src/commands/quick.ts create mode 100644 packages/cli/src/commands/skillmd.ts create mode 100644 packages/core/src/registry/index.ts diff --git a/README.md b/README.md index bcc16c43..3166089b 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,13 @@ [![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) -## Supercharge Every AI Coding Agent +## One Skill. Every Agent. -**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). +**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. > **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. diff --git a/apps/skillkit/src/cli.ts b/apps/skillkit/src/cli.ts index a0b070b9..8e1eb15a 100644 --- a/apps/skillkit/src/cli.ts +++ b/apps/skillkit/src/cli.ts @@ -98,6 +98,10 @@ import { GuidelineCreateCommand, GuidelineRemoveCommand, TreeCommand, + QuickCommand, + SkillMdValidateCommand, + SkillMdInitCommand, + SkillMdCheckCommand, } from '@skillkit/cli'; const __filename = fileURLToPath(import.meta.url); @@ -220,4 +224,9 @@ cli.register(GuidelineRemoveCommand); cli.register(TreeCommand); +cli.register(QuickCommand); +cli.register(SkillMdValidateCommand); +cli.register(SkillMdInitCommand); +cli.register(SkillMdCheckCommand); + cli.runExit(process.argv.slice(2)); diff --git a/docs/skillkit/App.tsx b/docs/skillkit/App.tsx index 0b87b626..8feee023 100644 --- a/docs/skillkit/App.tsx +++ b/docs/skillkit/App.tsx @@ -12,6 +12,8 @@ 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 = ( @@ -61,6 +63,20 @@ export default function App(): React.ReactElement { > Stack + scrollToSection(e, 'matrix')} + className="text-zinc-500 hover:text-white transition-colors" + > + Matrix + + scrollToSection(e, 'badge')} + className="text-zinc-500 hover:text-white transition-colors" + > + Badge + scrollToSection(e, 'advanced')} @@ -172,6 +188,16 @@ export default function App(): React.ReactElement { + {/* Compatibility Matrix */} +
+ +
+ + {/* Badge Generator */} +
+ +
+ {/* Advanced Capabilities: Memory, Primer, Mesh, Messaging */}
diff --git a/docs/skillkit/components/BadgeGenerator.tsx b/docs/skillkit/components/BadgeGenerator.tsx new file mode 100644 index 00000000..90dfc1b6 --- /dev/null +++ b/docs/skillkit/components/BadgeGenerator.tsx @@ -0,0 +1,201 @@ +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(['react', 'typescript', 'nextjs']); + const [inputValue, setInputValue] = useState(''); + const [copiedType, setCopiedType] = useState(null); + + const badgeUrl = useMemo(() => buildBadgeUrl(skills), [skills]); + + const markdown = `[![SkillKit Stack](${badgeUrl})](https://agenstskills.com)`; + const html = `SkillKit Stack`; + + 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): void { + if (e.key === 'Enter' && inputValue.trim()) { + e.preventDefault(); + addSkill(inputValue); + } + } + + async function copyToClipboard(text: string, type: string): Promise { + 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 ( +
+
+
+

Badge Generator

+

+ Create a shareable badge for your skill stack. Add it to your README. +

+
+ +
+
+
+ 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" + /> +
+ +
+ Quick add: +
+ {availableSuggestions.slice(0, 12).map(skill => ( + + ))} +
+
+ + {skills.length > 0 && ( +
+
+
+ Skills in Badge ({skills.length}) +
+ +
+
+ {skills.map(skill => ( +
+ {skill} + +
+ ))} +
+
+ )} +
+ +
+
+
Preview
+ +
+ {skills.length > 0 ? ( + SkillKit Stack Badge + ) : ( + Add skills to preview + )} +
+ +
+
Markdown
+
+                  
+                    {markdown}
+                  
+                
+ +
+ +
+
HTML
+
+                  
+                    {html}
+                  
+                
+ +
+ +
+ Powered by shields.io +
+
+
+
+
+
+ ); +} diff --git a/docs/skillkit/components/CompatibilityMatrix.tsx b/docs/skillkit/components/CompatibilityMatrix.tsx new file mode 100644 index 00000000..ba0fe16e --- /dev/null +++ b/docs/skillkit/components/CompatibilityMatrix.tsx @@ -0,0 +1,351 @@ +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> = { + '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 = { + 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 = { full: 2, partial: 1, none: 0 }; + +function SupportCell({ support }: { support: Support }): React.ReactElement { + const config = SUPPORT_CONFIG[support]; + return ( + +
+ + {support === 'full' ? '\u2713' : support === 'partial' ? '\u25CB' : '\u2715'} + +
+ + ); +} + +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(null); + + const groups = useMemo(() => { + const seen = new Set(); + return AGENTS.reduce((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 ( +
+
+
+
+

Compatibility Matrix

+

+ Skill support across 16 agents and 12 categories. +

+
+
+ + Updated Feb 2026 +
+
+ +
+
+ + + + 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 && ( + + )} +
+
+ + {groups.map(g => ( + + ))} +
+
+ +
+ {Object.entries(SUPPORT_CONFIG).map(([key, config]) => ( +
+
+ + {key === 'full' ? '\u2713' : key === 'partial' ? '\u25CB' : '\u2715'} + +
+ {config.label} +
+ ))} +
+ +
+
+ + + + + {filteredAgents.map(agent => ( + + ))} + + + + {filteredCategories.map(category => ( + + + {filteredAgents.map(agent => ( + + ))} + + ))} + + + + + {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 ( + + ); + })} + + +
+ Category + +
+ {agent.icon} + + {agent.name.length > 7 ? agent.name.slice(0, 7) : agent.name} + +
+
+
+ {category.icon} + {category.name} +
+
+ Score + +
{pct}%
+
{score}/{maxScore}
+
+
+
+ + {filteredAgents.length === 0 && ( +
+ No agents match your filter. +
+ )} + + {filteredCategories.length === 0 && filteredAgents.length > 0 && ( +
+ No categories match your filter. +
+ )} +
+
+ ); +} diff --git a/docs/skillkit/components/Features.tsx b/docs/skillkit/components/Features.tsx index 6bf0179c..428d7f08 100644 --- a/docs/skillkit/components/Features.tsx +++ b/docs/skillkit/components/Features.tsx @@ -9,7 +9,7 @@ interface Feature { const FEATURES: Feature[] = [ { title: 'Smart Recommendations', - description: 'AI analyzes your codebase and suggests perfect skills.', + description: 'AI analyzes your codebase and recommends from 15,000+ skills.', icon: ( @@ -18,7 +18,7 @@ const FEATURES: Feature[] = [ }, { title: 'Auto Translation', - description: 'Write once, deploy to 32 agents. Zero manual conversion.', + description: 'The npm for agent skills. Write once, auto-translate to 32 formats.', icon: ( diff --git a/docs/skillkit/components/Hero.tsx b/docs/skillkit/components/Hero.tsx index 5cf488a6..e04de192 100644 --- a/docs/skillkit/components/Hero.tsx +++ b/docs/skillkit/components/Hero.tsx @@ -134,14 +134,14 @@ export function Hero({ version }: HeroProps): React.ReactElement {

- Write Once.
- Deploy to 32 Agents. + One Skill.
+ 32 Agents. Zero Rewrites.

- 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. + 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.

diff --git a/package.json b/package.json index d73652dc..e019e7ac 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "skillkit-monorepo", "version": "1.10.0", "private": true, - "description": "Universal skills loader for AI coding agents - Monorepo", + "description": "The package manager for AI agent skills — install, translate, share across 32 coding agents", "type": "module", "scripts": { "build": "turbo run build", @@ -31,7 +31,13 @@ "coding-assistant", "skill-loader", "cli", - "monorepo" + "monorepo", + "skill-md", + "package-manager", + "plugin", + "workflow", + "automation", + "SKILL.md" ], "author": "Rohit Ghumare", "license": "Apache-2.0", diff --git a/packages/cli/src/__tests__/quick-security.test.ts b/packages/cli/src/__tests__/quick-security.test.ts new file mode 100644 index 00000000..b03016e6 --- /dev/null +++ b/packages/cli/src/__tests__/quick-security.test.ts @@ -0,0 +1,69 @@ +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); + }); + }); +}); diff --git a/packages/cli/src/badge.ts b/packages/cli/src/badge.ts new file mode 100644 index 00000000..18b47021 --- /dev/null +++ b/packages/cli/src/badge.ts @@ -0,0 +1,39 @@ +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: `SkillKit Stack`, + }; + } + + 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: `SkillKit Stack`, + }; +} diff --git a/packages/cli/src/commands/find.ts b/packages/cli/src/commands/find.ts index 6b143092..cb043113 100644 --- a/packages/cli/src/commands/find.ts +++ b/packages/cli/src/commands/find.ts @@ -8,6 +8,7 @@ import { select, header, } from '../onboarding/index.js'; +import { FederatedSearch, GitHubSkillRegistry, RateLimitError } from '@skillkit/core'; interface SkillResult { name: string; @@ -54,6 +55,10 @@ 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 { const s = spinner(); const limit = parseInt(this.limit, 10) || 10; @@ -128,12 +133,46 @@ 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 ui # Browse in TUI')); + console.log(colors.muted(' skillkit find --top # Show featured skills')); + console.log(colors.muted(' skillkit find -f # Search external registries')); + console.log(colors.muted(' skillkit ui # Browse in TUI')); return 0; } diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts index 295ee6b0..68799556 100644 --- a/packages/cli/src/commands/index.ts +++ b/packages/cli/src/commands/index.ts @@ -108,3 +108,9 @@ export { // 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'; diff --git a/packages/cli/src/commands/quick.ts b/packages/cli/src/commands/quick.ts new file mode 100644 index 00000000..9e69f05e --- /dev/null +++ b/packages/cli/src/commands/quick.ts @@ -0,0 +1,375 @@ +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 { + 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; + } + } +} diff --git a/packages/cli/src/commands/skillmd.ts b/packages/cli/src/commands/skillmd.ts new file mode 100644 index 00000000..5c5cef53 --- /dev/null +++ b/packages/cli/src/commands/skillmd.ts @@ -0,0 +1,440 @@ +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 { + 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 { + 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 { + 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 + } + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b63034ea..4b826049 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -104,3 +104,6 @@ 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'; diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.ts new file mode 100644 index 00000000..e3fc26d7 --- /dev/null +++ b/packages/core/src/registry/index.ts @@ -0,0 +1,163 @@ +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; +} + +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 { + 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 = { + 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(); + 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 class FederatedSearch { + private registries: ExternalRegistry[] = []; + + addRegistry(registry: ExternalRegistry): void { + this.registries.push(registry); + } + + async search(query: string, options?: { limit?: number }): Promise { + 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(); + 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, + }; + } +} diff --git a/packages/core/src/skills.ts b/packages/core/src/skills.ts index 31d9aaf1..dfd919df 100644 --- a/packages/core/src/skills.ts +++ b/packages/core/src/skills.ts @@ -1,5 +1,5 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs'; -import { join, basename } from 'node:path'; +import { join, basename, resolve, sep } from 'node:path'; import { parse as parseYaml } from 'yaml'; import { SkillFrontmatter, SkillMetadata, type Skill, type SkillLocation } from './types.js'; @@ -391,6 +391,7 @@ export function validateSkill(skillPath: string): { valid: boolean; errors: stri } export function isPathInside(child: string, parent: string): boolean { - const relative = child.replace(parent, ''); - return !relative.startsWith('..') && !relative.includes('/..'); + const resolved = resolve(child); + const resolvedParent = resolve(parent); + return resolved === resolvedParent || resolved.startsWith(resolvedParent + sep); } diff --git a/src/core/skills.ts b/src/core/skills.ts index a3f556ea..9202cc3d 100644 --- a/src/core/skills.ts +++ b/src/core/skills.ts @@ -1,5 +1,5 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs'; -import { join, basename } from 'node:path'; +import { join, basename, resolve, sep } from 'node:path'; import { parse as parseYaml } from 'yaml'; import { SkillFrontmatter, SkillMetadata, type Skill, type SkillLocation } from './types.js'; @@ -328,6 +328,7 @@ export function validateSkill(skillPath: string): { valid: boolean; errors: stri } export function isPathInside(child: string, parent: string): boolean { - const relative = child.replace(parent, ''); - return !relative.startsWith('..') && !relative.includes('/..'); + const resolved = resolve(child); + const resolvedParent = resolve(parent); + return resolved === resolvedParent || resolved.startsWith(resolvedParent + sep); }