Compare commits

..
Author SHA1 Message Date
Rohit Ghumare 64b802a1e6 chore: release v1.4.0
New Features:
- Session Memory System: Cross-agent learning capture and sharing
- Skill Marketplace: Browse and install skills from curated repositories
- Skill Testing Framework: Test assertions and runner
- Workflow Orchestration: Multi-step skill compositions
- CI/CD Templates: GitHub Actions, GitLab CI, CircleCI support

Improvements:
- Enhanced TUI with marketplace browser
- Improved error-solution matching
- ReDoS protection for regex patterns
- Better input validation for CLI flags

All 346 tests passing.
2026-01-23 18:16:51 +00:00
Rohit Ghumare b008a46b8d fix: address remaining CodeRabbit/Devin issues (batch 4)
- ReDoS protection: Add pattern validator to reject dangerous regex patterns
  (nested quantifiers, overlapping alternations, excessive quantifiers)
- Add missing 'cancelled' status message in execution engine
- Make completedAt/durationMs optional in TaskExecutionResult
- Fix tag filter to skip untagged tests when tags are specified
- Improve error-solution matching: require keyword similarity + solution indicator
- Validate --limit and sanitize --tags in memory/marketplace CLI commands
- Guard against missing arrays when importing YAML learnings
- Escape YAML frontmatter values to prevent invalid output
- Preserve original learning source when merging learnings
- Fix keyword double-counting in memory index search
- Normalize keywords by stripping punctuation for better matching
2026-01-23 18:01:56 +00:00
Rohit Ghumare ed90080786 fix: address critical and major CodeRabbit/Devin issues (batch 3)
Security fixes:
- Remove shell: true from spawn to prevent shell injection (agents.ts)
- Add safe regex test with ReDoS protection (engine.ts)
- Add security warning for verification commands (engine.ts)

Bug fixes:
- Fix global memory index path to use ~/.skillkit/ (compressor.ts, memory-index.ts)
- Add task_complete events and verification to resumeExecution (engine.ts)
- Handle absolute URLs in skill entries (aggregator.ts)
- Implement actual port availability check (runner.ts)
- Remove invalid JUnit report format (templates.ts)
- Add crash guard to workflow list command (workflow/list.ts)
2026-01-23 17:40:45 +00:00
Rohit Ghumare b701bb5f47 fix: address CodeRabbit/Devin review issues (batch 2)
- Fix resume skipping checkpoint handling in engine.ts
- Add paused status guard before completeExecution call
- Fix NaN% progress when totalSteps=0 in Execute.tsx
- Fix effectiveness ?? instead of || to preserve 0% values in compressor.ts
- Clear cache on source change in aggregator.ts addSource/removeSource
2026-01-23 16:55:29 +00:00
Rohit Ghumare 1c4c9a794f fix: address 7 bugs identified by Devin code review
- Fix MemoryIndexStore ignoring isGlobal flag (memory-index.ts)
- Fix ESM runtime crash using require('yaml') in test runner (runner.ts)
- Fix ESM runtime crash using require('node:fs') in MarketplaceAggregator (aggregator.ts)
- Fix ESM runtime crash using require('node:fs') in SessionManager (manager.ts)
- Fix memory rate command parsing rating from --content instead of positional arg (memory.ts)
- Fix SkillExecutionEngine emitting failed status for paused executions (engine.ts)
- Fix run command misclassifying directories as skill markdown files (run.ts)
2026-01-23 16:18:38 +00:00
Rohit Ghumare cb37ebeca7 chore: update pnpm-lock.yaml 2026-01-23 16:02:47 +00:00
Rohit Ghumare 7053d1a2b2 fix: add missing yaml dependency to @skillkit/cli 2026-01-23 16:01:00 +00:00
Rohit Ghumare 1ea5ddd4c7 feat: add marketplace, testing, CI/CD, workflows, and fix dry-run bug
New Features:
- Skill Marketplace: Aggregates skills from GitHub repos with caching
- Skill Testing Framework: 18+ assertion types for skill validation
- CI/CD Integration: Templates for GitHub Actions, GitLab CI, CircleCI
- Workflow Orchestration: Wave-based parallel skill execution
- Session Management: Pause/resume support with state persistence
- Agent Execution: CLI spawning for claude/codex/gemini/opencode/goose

New CLI Commands:
- skillkit marketplace - Browse and install from marketplace
- skillkit test - Run skill tests with assertions
- skillkit run - Execute skills with orchestration
- skillkit status - Show session state
- skillkit pause/resume - Session management
- skillkit workflow - Workflow management

New TUI Screens:
- Marketplace browser with search
- History viewer with session details
- Workflow management screen

Bug Fix:
- Fixed dry-run mode in memory compress command (Devin review)
  The --dry-run flag now properly prevents storing learnings
2026-01-23 15:50:54 +00:00
Rohit Ghumare 720532c020 feat: add session memory system for cross-agent learning
Implements a lightweight, local-first memory system that works across
all 17 AI coding agents. Key features:

- YAML-based storage (no databases or external services)
- Three memory layers: Session, Project, and Global
- AI-powered compression of observations into learnings
- Cross-agent memory injection with relevance matching
- Progressive disclosure for token efficiency

Core modules:
- ObservationStore: Capture raw session observations
- LearningStore: Persist compressed learnings
- MemoryCompressor: AI/rule-based compression engine
- MemoryInjector: Context-aware memory retrieval
- MemoryObserver: Automatic observation capture

CLI commands (skillkit memory):
- status, search, list, show, compress, export
- import, clear, add, rate, config

TUI integration:
- New Memory screen with tabs (Learnings/Observations/Search)
- useMemory hook for state management
- Updated navigation and keybindings

Code quality improvements:
- Replaced nested ternaries with explicit functions
- Added named constants for magic numbers
- Simplified navigation with lookup map
2026-01-23 14:24:16 +00:00
Rohit Ghumare bc12775e0e docs: add README files to all packages 2026-01-23 09:58:16 +00:00
Rohit Ghumare cd64f7f7d0 fix: use pnpm recursive publish for monorepo packages 2026-01-23 09:49:31 +00:00
Rohit Ghumare ca9af70f10 chore: bump version to 1.3.0 2026-01-23 09:47:19 +00:00
Rohit Ghumare 160d2b1534 feat: add TUI enhancements and monorepo structure (#2)
* feat: add TUI enhancements and monorepo structure

- Add Translate screen for cross-agent skill translation
- Add Context screen for project context management
- Add Recommend screen with smart skill recommendations
- Fix TUI screen duplication by using fixed height container
- Clean up unnecessary comments following code-simplifier principles
- Refactor to monorepo structure with @skillkit/core, @skillkit/cli,
  @skillkit/tui, and @skillkit/agents packages
- Add comprehensive tests for translator, context, and recommend features
- Update license to Apache-2.0
- Add CONTRIBUTING.md with contribution guidelines

* ci: switch from npm to pnpm for monorepo support

* ci: use pnpm version from package.json

* fix: remove unused import in TUI helpers
2026-01-23 09:41:15 +00:00
Rohit Ghumare 4a632e9262 fix: read version from package.json instead of hardcoding
- CLI now reads version from package.json dynamically
- TUI Home screen reads version from package.json
- Removes hardcoded version strings
2026-01-22 13:32:15 +00:00
Rohit Ghumare a763348922 chore: add local files to .gitignore
- Ignore .claude/ and other agent skill directories
- Ignore skillkit.yaml config file
- Ignore .code-workspace files
2026-01-22 13:25:41 +00:00
Rohit Ghumare 4782b6773b fix: resolve TypeScript errors for CI/CD
- Remove unused React imports (using JSX transform)
- Fix color usage for Ink components (use color prop, not chalk functions)
- Add missing properties to theme (borderDim, check, star)
- Fix useSkills hook to include remove function
- Fix useMarketplace to handle DiscoveredSkill type correctly
- Remove useSkillStats export (not implemented)
- Fix useKeyboard imports
2026-01-22 13:25:03 +00:00
Rohit Ghumare 75001a1310 feat: add interactive TUI for skill management
- Beautiful terminal interface with monochrome design
- Browse 33+ skill repositories dynamically
- Install skills with single keystroke
- Multi-agent installation support
- View installed skills and sync across agents
- Responsive design for all terminal sizes
- Keyboard navigation with clear instructions
- Animated logo reveal on home screen

Features:
- Browse: Discover skills from popular repositories
- List: View all installed skills
- Sync: Sync skills across multiple agents
- Settings: Configure SkillKit preferences

Keyboard shortcuts:
- h/b/l/s/, for navigation
- Enter to install/select
- m for multi-agent selection
- Esc to go back, q to quit
2026-01-22 13:21:58 +00:00
Rohit Ghumare 73f9c26cbe chore: bump version to 1.1.0 2026-01-21 12:07:08 +00:00
Rohit Ghumare e56873c491 fix: update publish workflow for npm authentication 2026-01-21 12:03:04 +00:00
Rohit Ghumare eaeb7ef221 feat: add create command for scaffolding new skills
- Add skillkit create command to scaffold new skills with proper structure
- Generate SKILL.md template with frontmatter following Agent Skills spec
- Support optional directories (references, scripts, assets)
- Validate skill names (lowercase alphanumeric with hyphens)
- Update README with create command documentation
2026-01-21 11:59:54 +00:00
Rohit Ghumare acec136e81 feat: add 10 new agent adapters and enhanced skill discovery
- Add adapters for Amp, Clawdbot, Droid, GitHub Copilot, Goose, Kilo, Kiro CLI, Roo, Trae, Windsurf
- Add --list flag to preview skills without installing
- Add --agent flag for multi-agent install
- Extend skill discovery to search 20+ standard paths
- Add recursive fallback search when no skills in standard paths
- Add tests for new functionality (84 tests total)
2026-01-21 11:51:26 +00:00
Rohit Ghumare 70cb4f74ff add GIF 2026-01-21 10:59:25 +00:00
Rohit Ghumare 2f4232182f Auto-publish on tag push + auto-create release 2026-01-20 16:23:40 +00:00
234 changed files with 39112 additions and 117 deletions
+8 -5
View File
@@ -17,20 +17,23 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
cache: 'pnpm'
- name: Install dependencies
run: npm ci
run: pnpm install --frozen-lockfile
- name: Type check
run: npm run typecheck
run: pnpm typecheck
- name: Build
run: npm run build
run: pnpm build
- name: Test
run: npm test
run: pnpm test
+18 -9
View File
@@ -1,37 +1,46 @@
name: Publish to npm
on:
release:
types: [published]
push:
tags:
- 'v*'
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
contents: write
id-token: write
steps:
- uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: npm ci
run: pnpm install --frozen-lockfile
- name: Build
run: npm run build
run: pnpm build
- name: Test
run: npm test
run: pnpm test
- name: Publish to npm
run: npm publish --provenance --access public
- name: Publish packages to npm
run: pnpm -r publish --access public --no-git-checks
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
generate_release_notes: true
+24 -1
View File
@@ -12,6 +12,7 @@ coverage/
.vscode/
*.swp
*.swo
*.code-workspace
# OS
.DS_Store
@@ -28,7 +29,6 @@ npm-debug.log*
# Package manager
yarn.lock
pnpm-lock.yaml
# Temporary files
tmp/
@@ -37,3 +37,26 @@ temp/
# Installed skills (local testing)
.agent/
.claude/
.cursor/
.codex/
.gemini/
.opencode/
.antigravity/
.agents/
.factory/
.github/skills/
.goose/
.kilocode/
.kiro/
.roo/
.trae/
.windsurf/
.agent/
# SkillKit config
skillkit.yaml
.skillkit/
# Turbo cache
.turbo/
+305
View File
@@ -0,0 +1,305 @@
# Contributing to SkillKit
Thank you for your interest in contributing to SkillKit! This document provides guidelines and instructions for contributing.
## Code of Conduct
By participating in this project, you agree to maintain a respectful and inclusive environment for everyone.
## Getting Started
### Prerequisites
- Node.js 18+
- pnpm 8+ (recommended) or npm/yarn
- Git
### Setting Up the Development Environment
1. **Fork the repository**
Click the "Fork" button on GitHub to create your own copy.
2. **Clone your fork**
```bash
git clone https://github.com/YOUR_USERNAME/skillkit.git
cd skillkit
```
3. **Install dependencies**
```bash
pnpm install
```
4. **Build the project**
```bash
pnpm build
```
5. **Run tests**
```bash
pnpm test
```
6. **Link for local development**
```bash
cd apps/skillkit
pnpm link --global
```
Now you can use `skillkit` command globally to test your changes.
## Project Structure
```
skillkit/
├── apps/
│ └── skillkit/ # Main CLI entry point
├── packages/
│ ├── core/ # @skillkit/core - Shared logic
│ │ ├── discovery/ # Skill discovery
│ │ ├── parser/ # SKILL.md parsing
│ │ ├── translator/ # Cross-agent translation
│ │ ├── context/ # Project context sync
│ │ └── recommend/ # Recommendation engine
│ ├── cli/ # @skillkit/cli - Commands
│ ├── tui/ # @skillkit/tui - Terminal UI
│ └── agents/ # @skillkit/agents - Agent adapters
├── docs/ # Documentation
└── README.md
```
## Development Workflow
### Branch Naming
Use descriptive branch names:
- `feature/skill-translation` - New features
- `fix/cursor-adapter-path` - Bug fixes
- `docs/api-reference` - Documentation
- `refactor/core-types` - Code refactoring
### Making Changes
1. **Create a new branch**
```bash
git checkout -b feature/your-feature-name
```
2. **Make your changes**
- Follow the existing code style
- Add tests for new functionality
- Update documentation as needed
3. **Run checks locally**
```bash
# Build all packages
pnpm build
# Run tests
pnpm test
# Type check
pnpm typecheck
# Lint (if configured)
pnpm lint
```
4. **Commit your changes**
Write clear, descriptive commit messages:
```bash
git commit -m "feat: add skill translation for Windsurf agent"
git commit -m "fix: resolve path resolution in Windows"
git commit -m "docs: add API reference for RecommendationEngine"
```
We follow [Conventional Commits](https://www.conventionalcommits.org/):
- `feat:` - New features
- `fix:` - Bug fixes
- `docs:` - Documentation changes
- `refactor:` - Code refactoring
- `test:` - Adding or updating tests
- `chore:` - Maintenance tasks
5. **Push your branch**
```bash
git push origin feature/your-feature-name
```
6. **Open a Pull Request**
- Provide a clear description of the changes
- Reference any related issues
- Ensure CI checks pass
## Types of Contributions
### Bug Reports
When reporting bugs, please include:
- SkillKit version (`skillkit --version`)
- Node.js version (`node --version`)
- Operating system
- Steps to reproduce
- Expected vs actual behavior
- Relevant error messages or logs
### Feature Requests
For feature requests, please describe:
- The problem you're trying to solve
- Your proposed solution
- Alternative approaches you've considered
- Any relevant examples or mockups
### Adding New Agent Support
To add support for a new AI coding agent:
1. **Create an adapter** in `packages/agents/src/adapters/`
```typescript
// packages/agents/src/adapters/new-agent.ts
import type { AgentAdapter, Skill } from '../types.js';
export const newAgentAdapter: AgentAdapter = {
type: 'new-agent',
name: 'New Agent',
configFile: 'AGENTS.md',
skillsDir: '.new-agent/skills/',
globalSkillsDir: '~/.new-agent/skills/',
generateConfig(skills: Skill[]): string {
// Generate config content
},
detectPresence(): boolean {
// Check if agent is present
},
};
```
2. **Register the adapter** in `packages/agents/src/adapters/index.ts`
3. **Add translator support** in `packages/core/src/translator/` if the agent uses a unique format
4. **Add tests** for the new adapter
5. **Update documentation**
### Adding New Skills
If you want to contribute skills to the ecosystem:
1. Follow the [Agent Skills specification](https://agentskills.io/specification)
2. Include a `SKILL.md` with proper frontmatter
3. Test with multiple agents using `skillkit translate`
4. Submit to the appropriate skill repository
## Code Style
### TypeScript
- Use TypeScript for all new code
- Define explicit types for function parameters and return values
- Use interfaces for object shapes
- Prefer `const` over `let`
### File Organization
- One export per file when possible
- Group related functionality in directories
- Use `index.ts` files for clean exports
### Testing
- Write unit tests for new functionality
- Use descriptive test names
- Test edge cases and error conditions
```typescript
describe('RecommendationEngine', () => {
it('should score skills based on framework match', () => {
// Test implementation
});
it('should return empty array when no skills match', () => {
// Test implementation
});
});
```
## Pull Request Guidelines
### Before Submitting
- [ ] Code builds without errors (`pnpm build`)
- [ ] All tests pass (`pnpm test`)
- [ ] New code has appropriate test coverage
- [ ] Documentation is updated if needed
- [ ] Commit messages follow conventions
### PR Description Template
```markdown
## Summary
Brief description of the changes.
## Changes
- Change 1
- Change 2
## Testing
How were these changes tested?
## Related Issues
Fixes #123
```
### Review Process
1. A maintainer will review your PR
2. Address any requested changes
3. Once approved, the PR will be merged
## Release Process
Releases are managed by maintainers. The process includes:
1. Version bump in package.json files
2. Changelog update
3. Git tag creation
4. npm publish
## Getting Help
- **GitHub Issues**: For bugs and feature requests
- **Discussions**: For questions and ideas
- **Documentation**: Check the README and docs/
## License
By contributing to SkillKit, you agree that your contributions will be licensed under the Apache License 2.0.
---
Thank you for contributing to SkillKit!
+186 -17
View File
@@ -1,21 +1,190 @@
MIT License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2026 Rohit Ghumare
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2025 Rohit Ghumare
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+364 -37
View File
@@ -3,11 +3,100 @@
[![npm version](https://img.shields.io/npm/v/skillkit.svg)](https://www.npmjs.com/package/skillkit)
[![npm downloads](https://img.shields.io/npm/dm/skillkit.svg)](https://www.npmjs.com/package/skillkit)
[![CI](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml/badge.svg)](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
Universal skills loader for AI coding agents. Install, manage, and sync skills across your favorite AI tools.
**The universal skills platform for AI coding agents.** Install, manage, translate, and sync skills across 17+ AI tools with smart recommendations.
Skills follow the [Agent Skills](https://agentskills.io) open format—a simple, portable standard for giving agents new capabilities and expertise.
```bash
npm install -g skillkit && skillkit
```
## Why SkillKit?
| Problem | SkillKit Solution |
|---------|------------------|
| Skills only work with one agent | **Cross-agent translation** - use any skill with any agent |
| Don't know which skills to install | **Smart recommendations** - project-aware suggestions |
| Config fragmented across agents | **One config, all agents** - sync everywhere |
| Manual skill discovery | **Task-based search** - find skills by what you need |
## 30-Second Quick Start
```bash
# Install globally
npm install -g skillkit
# Get personalized skill recommendations for your project
skillkit recommend
# Install top-rated skills
skillkit install anthropics/skills
# Launch interactive TUI
skillkit
```
## Key Features
### Smart Recommendations
Analyzes your project and suggests the best skills:
```bash
skillkit recommend
# Project: my-app (Next.js + TypeScript + Tailwind)
#
# Recommended Skills:
# 92% ██████████ vercel-react-best-practices
# 87% █████████░ tailwind-v4-patterns
# 85% █████████░ nextjs-app-router
```
### Cross-Agent Translation
Use any skill with any agent - automatic format conversion:
```bash
# Translate a Claude skill to Cursor format
skillkit translate react-patterns --to cursor
# Translate all skills for a new agent
skillkit translate --all --to antigravity
```
### Project Context Sync
Configure once, sync to all your agents:
```bash
# Analyze project and create context
skillkit context init
# Sync your config to all detected agents
skillkit context sync --all
```
## Interactive TUI
Launch the beautiful terminal interface:
```bash
skillkit ui
# or simply
skillkit
```
![SkillKit TUI](docs/img/skillkit-ui.png)
**Features:**
- Browse 33+ skill repositories
- Smart skill recommendations based on your project
- Install skills with one keystroke
- Multi-agent installation support
- Cross-agent skill translation
- Responsive design for all terminal sizes
**Navigation:**
- `h` Home | `b` Browse | `r` Recommend | `l` List | `s` Sync | `,` Config
- `↑↓` Navigate | `Enter` Select | `Esc` Back | `q` Quit
- `m` Multi-agent selection | `/` Search
### Compatible With
@@ -18,51 +107,63 @@ Skills follow the [Agent Skills](https://agentskills.io) open format—a simple,
| Cursor | ✅ Native |
| Gemini CLI | ✅ Native |
| OpenCode | ✅ Native |
| Amp | ✅ Supported |
| Goose | ✅ Supported |
| VS Code (Copilot) | ✅ Supported |
| Letta | ✅ Supported |
| Factory | ✅ Supported |
| Antigravity | ✅ Native |
| Amp | ✅ Native |
| Clawdbot | ✅ Native |
| Droid (Factory) | ✅ Native |
| GitHub Copilot | ✅ Native |
| Goose | ✅ Native |
| Kilo Code | ✅ Native |
| Kiro CLI | ✅ Native |
| Roo Code | ✅ Native |
| Trae | ✅ Native |
| Windsurf | ✅ Native |
| *Any markdown-config agent* | ✅ Universal |
## Features
- **Multi-Agent Support**: Works with 10+ AI coding agents out of the box
- **Smart Recommendations**: AI-powered skill suggestions based on your project stack
- **Cross-Agent Translation**: Convert skills between any of 17+ agent formats
- **Project Context Sync**: One config that syncs to all your agents
- **Session Memory**: Cross-agent learning system that captures and shares knowledge
- **Skill Marketplace**: Browse and install skills from curated GitHub repositories
- **Skill Testing**: Test framework for validating skills with assertions
- **Workflow Orchestration**: Compose skills into multi-step workflows
- **Interactive TUI**: Beautiful terminal interface for managing skills
- **Multi-Agent Support**: Works with Claude Code, Cursor, Codex, Windsurf, and 13+ more
- **Multi-Platform Git**: GitHub, GitLab, Bitbucket, and local paths
- **CI/CD Friendly**: Non-interactive flags for automation (`--skills`, `--all`, `--yes`)
- **Skill Toggle**: Enable/disable skills without removing them
- **Type-Safe**: Built with TypeScript and Zod validation
- **CI/CD Integration**: GitHub Actions, GitLab CI, CircleCI templates
- **Zero Config**: Auto-detects your agent and configures appropriately
## Installation
```bash
# Global install (recommended)
npm install -g skillkit
# or
# Or use without installing
npx skillkit <command>
# Or with other package managers
pnpm add -g skillkit
yarn global add skillkit
bun add -g skillkit
```
## Quick Start
```bash
# Initialize in your project (auto-detects agent)
skillkit init
# 1. Get recommendations for your project
skillkit recommend
# Install skills from GitHub
skillkit install owner/repo
# 2. Install recommended skills
skillkit install anthropics/skills
# Install from GitLab
skillkit install gitlab:owner/repo
# Install specific skills (CI/CD friendly)
skillkit install owner/repo --skills=pdf,xlsx,docx
# Sync skills to your agent config
# 3. Sync to your agent
skillkit sync
# Read a skill (for AI consumption)
skillkit read pdf
# Or just launch the TUI and do it all interactively
skillkit
```
## Popular Skill Repositories
@@ -77,6 +178,8 @@ skillkit install anthropics/skills
skillkit install vercel-labs/agent-skills/skills
```
![SkillKit Demo](https://raw.githubusercontent.com/rohitg00/skillkit/main/skillkit.gif)
| Repository | Skills | Description |
|------------|--------|-------------|
| [anthropics/skills](https://github.com/anthropics/skills) | `pdf`, `xlsx`, `docx`, etc. | Official Claude Code skill marketplace |
@@ -85,6 +188,36 @@ skillkit install vercel-labs/agent-skills/skills
## Commands
### `skillkit ui` / `skillkit`
Launch the interactive Terminal User Interface (TUI) for managing skills.
```bash
skillkit ui # Explicit TUI launch
skillkit # Launch TUI if no arguments provided
```
**TUI Features:**
- **Browse**: Discover skills from 33+ repositories
- **Recommend**: Get smart skill suggestions for your project
- **List**: View all installed skills
- **Sync**: Sync skills across multiple agents
- **Settings**: Configure SkillKit preferences
**Keyboard Shortcuts:**
- `h` - Home screen
- `b` - Browse skills marketplace
- `r` - Smart recommendations
- `l` - List installed skills
- `s` - Sync skills across agents
- `,` - Settings
- `↑↓` - Navigate lists
- `Enter` - Select / Install
- `m` - Multi-agent selection (when viewing skills)
- `/` - Search skills
- `Esc` - Return to home
- `q` - Quit
### `skillkit install <source>`
Install skills from various sources.
@@ -109,12 +242,14 @@ skillkit install ./my-skills
skillkit install ~/dev/skills
# Options
--list # List available skills without installing
--skills=pdf,xlsx # Install specific skills only (CI/CD)
--all # Install all discovered skills
--yes # Skip confirmation prompts
--global # Install to global directory
--force # Overwrite existing skills
--provider=gitlab # Force specific provider
--agent=cursor # Install to specific agent (can specify multiple)
```
### `skillkit sync`
@@ -128,6 +263,48 @@ skillkit sync --output AGENTS.md
skillkit sync --enabled-only
```
### `skillkit recommend`
Get smart skill recommendations based on your project's tech stack.
```bash
skillkit recommend # Analyze current directory
skillkit recommend --path ./my-app # Analyze specific project
skillkit recommend --verbose # Show detailed match reasons
skillkit recommend --limit 5 # Limit results
skillkit recommend --min-score 50 # Only show high matches
skillkit recommend --category security # Filter by category
skillkit recommend --search "auth" # Search skills by task
skillkit recommend --update # Update skill index
skillkit recommend --json # Output as JSON
```
### `skillkit translate`
Translate skills between different agent formats.
```bash
skillkit translate react-skill --to cursor # Translate to Cursor format
skillkit translate ./skill --from claude --to windsurf # Explicit source/target
skillkit translate --all --to cursor # Translate all installed skills
skillkit translate react-skill --to cursor --dry-run # Preview without writing
```
**Supported translations:** All 17 agents can translate to/from each other.
### `skillkit context`
Manage project context for cross-agent synchronization.
```bash
skillkit context init # Analyze project and create context
skillkit context show # Display current context
skillkit context export # Export context to file
skillkit context import ./context.yaml # Import context from file
skillkit context sync --agent cursor # Sync context to specific agent
skillkit context sync --all # Sync to all detected agents
```
### `skillkit read <skills>`
Read skill content for AI agent consumption.
@@ -192,20 +369,113 @@ skillkit validate ./my-skill # Validate single skill
skillkit validate ./skills --all # Validate all skills in directory
```
### `skillkit marketplace`
Browse and install skills from the curated marketplace.
```bash
skillkit marketplace # Browse all skills
skillkit marketplace search typescript # Search for skills
skillkit marketplace refresh # Refresh skill index
skillkit marketplace tags # Show popular tags
skillkit marketplace sources # List skill sources
skillkit marketplace --limit 20 # Limit results
skillkit marketplace --tags react,next # Filter by tags
```
### `skillkit memory`
Manage session memory - learnings captured across AI coding sessions.
```bash
skillkit memory status # Show memory status
skillkit memory search "auth" # Search memories
skillkit memory list # List all learnings
skillkit memory show <id> # Show specific learning
skillkit memory compress # Compress observations into learnings
skillkit memory export <id> # Export learning as a skill
skillkit memory import ./file.yaml # Import memories
skillkit memory add --title "..." # Add manual learning
skillkit memory rate <id> 85 # Rate effectiveness (0-100)
skillkit memory --global # Use global memory scope
```
### `skillkit test`
Test skills with the built-in testing framework.
```bash
skillkit test # Run all skill tests
skillkit test ./my-skill # Test specific skill
skillkit test --tags unit # Run tests with specific tags
skillkit test --json # Output results as JSON
skillkit test --verbose # Verbose output
```
### `skillkit workflow`
Manage and run skill workflows (multi-step skill compositions).
```bash
skillkit workflow list # List available workflows
skillkit workflow run <name> # Run a workflow
skillkit workflow create <name> # Create new workflow
skillkit workflow validate <name> # Validate workflow definition
skillkit workflow --verbose # Verbose output
```
### `skillkit cicd`
Generate CI/CD integration templates.
```bash
skillkit cicd github-action # Generate GitHub Actions workflow
skillkit cicd pre-commit # Generate pre-commit hook
skillkit cicd gitlab-ci # Generate GitLab CI config
skillkit cicd circleci # Generate CircleCI config
skillkit cicd --list # List available templates
skillkit cicd --output ./path # Output to specific path
```
### `skillkit create <skill-name>`
Create a new skill with proper structure and template.
```bash
skillkit create my-skill # Basic skill
skillkit create my-skill --full # Include all directories (references, scripts, assets)
skillkit create my-skill --scripts # Include scripts directory
skillkit create my-skill --references # Include references directory
skillkit create my-skill --assets # Include assets directory
skillkit create my-skill --dir ./skills # Create in specific directory
```
## Supported Agents
| Agent | Config File | Skills Directory |
|-------|-------------|------------------|
| Claude Code | `AGENTS.md` | `.claude/skills/` |
| Cursor | `.cursorrules` | `.cursor/skills/` |
| Codex | `AGENTS.md` | `.codex/skills/` |
| Gemini CLI | `GEMINI.md` | `.gemini/skills/` |
| OpenCode | `AGENTS.md` | `.opencode/skills/` |
| Antigravity | `AGENTS.md` | `.antigravity/skills/` |
| Universal | `AGENTS.md` | `.agent/skills/` |
| Agent | Config File | Project Path | Global Path |
|-------|-------------|--------------|-------------|
| Claude Code | `AGENTS.md` | `.claude/skills/` | `~/.claude/skills/` |
| Cursor | `.cursorrules` | `.cursor/skills/` | `~/.cursor/skills/` |
| Codex | `AGENTS.md` | `.codex/skills/` | `~/.codex/skills/` |
| Gemini CLI | `GEMINI.md` | `.gemini/skills/` | `~/.gemini/skills/` |
| OpenCode | `AGENTS.md` | `.opencode/skills/` | `~/.config/opencode/skills/` |
| Antigravity | `AGENTS.md` | `.antigravity/skills/` | `~/.gemini/antigravity/skills/` |
| Amp | `AGENTS.md` | `.agents/skills/` | `~/.config/agents/skills/` |
| Clawdbot | `AGENTS.md` | `skills/` | `~/.clawdbot/skills/` |
| Droid (Factory) | `AGENTS.md` | `.factory/skills/` | `~/.factory/skills/` |
| GitHub Copilot | `AGENTS.md` | `.github/skills/` | `~/.copilot/skills/` |
| Goose | `AGENTS.md` | `.goose/skills/` | `~/.config/goose/skills/` |
| Kilo Code | `AGENTS.md` | `.kilocode/skills/` | `~/.kilocode/skills/` |
| Kiro CLI | `AGENTS.md` | `.kiro/skills/` | `~/.kiro/skills/` |
| Roo Code | `AGENTS.md` | `.roo/skills/` | `~/.roo/skills/` |
| Trae | `AGENTS.md` | `.trae/skills/` | `~/.trae/skills/` |
| Windsurf | `AGENTS.md` | `.windsurf/skills/` | `~/.codeium/windsurf/skills/` |
| Universal | `AGENTS.md` | `.agent/skills/` | `~/.agent/skills/` |
## Creating Skills
Use `skillkit create <name>` to scaffold a new skill, or create manually:
A skill is a directory with a `SKILL.md` file:
```
@@ -268,10 +538,36 @@ Instructions for the AI agent on how to use this skill.
```typescript
import {
// Skill discovery
findAllSkills,
discoverSkills,
detectAgent,
getAdapter,
// Recommendations
RecommendationEngine,
analyzeProject,
// Translation
translateSkill,
translateSkillFile,
// Context
ContextManager,
initContext,
syncToAllAgents,
// Marketplace
createMarketplaceAggregator,
// Session Memory
createMemoryCompressor,
createMemoryInjector,
LearningStore,
ObservationStore,
// Testing
SkillTestRunner,
// Workflows
WorkflowOrchestrator,
parseWorkflow,
// CI/CD
getCICDTemplate,
listCICDTemplates,
} from 'skillkit';
// Find all installed skills
@@ -283,6 +579,37 @@ const agent = await detectAgent();
// Generate config
const adapter = getAdapter(agent);
const config = adapter.generateConfig(skills);
// Get smart recommendations
const engine = new RecommendationEngine();
const profile = await analyzeProject('./my-project');
const recommendations = engine.recommend(profile, skills);
// Translate skills between agents
const result = translateSkill(skillContent, 'cursor');
console.log(result.content); // Cursor MDC format
// Manage project context
const ctx = new ContextManager('./my-project');
await ctx.init();
await syncToAllAgents(ctx.getContext());
// Browse marketplace
const marketplace = createMarketplaceAggregator();
const results = await marketplace.search({ query: 'react' });
// Session memory
const injector = createMemoryInjector('./my-project');
const memories = injector.search('authentication patterns');
// Run skill tests
const runner = new SkillTestRunner('./my-project');
const testResults = await runner.runAll();
// Run workflows
const workflow = parseWorkflow('./workflow.yaml');
const orchestrator = new WorkflowOrchestrator(workflow);
await orchestrator.execute();
```
## Configuration
@@ -302,11 +629,11 @@ disabledSkills:
## License
MIT License - see [LICENSE](LICENSE) for details.
Apache License 2.0 - see [LICENSE](LICENSE) for details.
## Contributing
Contributions welcome! Please read our contributing guidelines.
Contributions welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md) before submitting a pull request.
## Acknowledgments
+43
View File
@@ -0,0 +1,43 @@
version: 1
project:
name: skillkit
description: Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more
type: cli
path: /Users/rohitghumare/skillkit/apps/skillkit
stack:
languages:
- name: typescript
version: 5.7.2
confidence: 100
source: tsconfig.json
frameworks: []
libraries: []
styling: []
testing:
- name: vitest
version: 2.1.8
confidence: 100
source: package.json
databases: []
tools: []
runtime:
- name: nodejs
version: 18.0.0
confidence: 100
source: package.json
patterns:
apiStyle: rest
testing: vitest
skills:
installed: []
recommended: []
excluded: []
autoSync: true
securityLevel: medium
testingRequired: false
agents:
detected: []
synced: []
disabled: []
createdAt: 2026-01-23T00:02:29.727Z
updatedAt: 2026-01-23T00:02:29.728Z
+41
View File
@@ -0,0 +1,41 @@
# SkillKit
Universal skills manager for AI coding agents. Install, manage, and sync skills across 17+ AI agents including Claude Code, Cursor, Codex, Gemini CLI, and more.
## Installation
```bash
npm install -g skillkit
```
## Quick Start
```bash
# Initialize skillkit in your project
skillkit init
# Install a skill
skillkit install github.com/anthropics/courses:prompt-eng/interactive-tutorial
# List installed skills
skillkit list
# Launch interactive TUI
skillkit ui
```
## Features
- **17+ Agent Support**: Claude Code, Cursor, Codex, Gemini CLI, Windsurf, GitHub Copilot, and more
- **Universal Skill Translation**: Convert skills between different agent formats
- **Smart Recommendations**: Get skill suggestions based on your project stack
- **Project Context Sync**: One config, all agents
- **Interactive TUI**: Browse, install, and manage skills visually
## Documentation
Full documentation: https://github.com/rohitg00/skillkit
## License
Apache-2.0
+68
View File
@@ -0,0 +1,68 @@
{
"name": "skillkit",
"version": "1.4.0",
"description": "Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more",
"type": "module",
"bin": {
"skillkit": "./dist/cli.js",
"sk": "./dist/cli.js"
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": [
"dist",
"schemas"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"keywords": [
"ai",
"skills",
"claude",
"codex",
"cursor",
"gemini",
"opencode",
"antigravity",
"agent",
"coding-assistant",
"skill-loader",
"cli"
],
"author": "Rohit Ghumare",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/rohitg00/skillkit.git"
},
"bugs": {
"url": "https://github.com/rohitg00/skillkit/issues"
},
"homepage": "https://github.com/rohitg00/skillkit#readme",
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"@skillkit/cli": "workspace:*",
"@skillkit/tui": "workspace:*",
"clipanion": "^4.0.0-rc.4"
},
"devDependencies": {
"@types/node": "^22.10.5",
"tsup": "^8.3.5",
"typescript": "^5.7.2",
"vitest": "^2.1.8"
}
}
+28
View File
@@ -0,0 +1,28 @@
import { describe, it, expect } from 'vitest';
import { existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
describe('SkillKit CLI', () => {
describe('build artifacts', () => {
it('should have cli entry point', () => {
const distPath = join(__dirname, '../../dist/cli.js');
expect(existsSync(distPath)).toBe(true);
});
it('should have index entry point', () => {
const distPath = join(__dirname, '../../dist/index.js');
expect(existsSync(distPath)).toBe(true);
});
});
describe('package.json', () => {
it('should have correct bin configuration', async () => {
const packageJsonPath = join(__dirname, '../../package.json');
expect(existsSync(packageJsonPath)).toBe(true);
});
});
});
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env node
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { Cli, Builtins } from 'clipanion';
import {
InstallCommand,
SyncCommand,
ReadCommand,
ListCommand,
EnableCommand,
DisableCommand,
UpdateCommand,
RemoveCommand,
InitCommand,
ValidateCommand,
CreateCommand,
UICommand,
TranslateCommand,
ContextCommand,
RecommendCommand,
StatusCommand,
PauseCommand,
ResumeCommand,
WorkflowRunCommand,
WorkflowListCommand,
WorkflowCreateCommand,
RunCommand,
TestCommand,
MarketplaceCommand,
MemoryCommand,
} from '@skillkit/cli';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const packageJsonPath = join(__dirname, '../package.json');
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
const version = packageJson.version || '1.2.0';
const cli = new Cli({
binaryLabel: 'skillkit',
binaryName: 'skillkit',
binaryVersion: version,
});
cli.register(Builtins.HelpCommand);
cli.register(Builtins.VersionCommand);
cli.register(InstallCommand);
cli.register(SyncCommand);
cli.register(ReadCommand);
cli.register(ListCommand);
cli.register(EnableCommand);
cli.register(DisableCommand);
cli.register(UpdateCommand);
cli.register(RemoveCommand);
cli.register(InitCommand);
cli.register(ValidateCommand);
cli.register(CreateCommand);
cli.register(UICommand);
cli.register(TranslateCommand);
cli.register(ContextCommand);
cli.register(RecommendCommand);
cli.register(StatusCommand);
cli.register(PauseCommand);
cli.register(ResumeCommand);
cli.register(WorkflowRunCommand);
cli.register(WorkflowListCommand);
cli.register(WorkflowCreateCommand);
cli.register(RunCommand);
cli.register(TestCommand);
cli.register(MarketplaceCommand);
cli.register(MemoryCommand);
cli.runExit(process.argv.slice(2));
+6
View File
@@ -0,0 +1,6 @@
// Re-export all public APIs from packages
export * from '@skillkit/core';
export * from '@skillkit/agents';
// Re-export TUI entry point
export { startTUI } from '@skillkit/tui';
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": false
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from 'tsup';
export default defineConfig({
entry: ['src/cli.ts', 'src/index.ts'],
format: ['esm'],
dts: true,
splitting: false,
sourcemap: true,
clean: true,
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

+572 -2
View File
@@ -1,19 +1,24 @@
{
"name": "skillkit",
"version": "1.0.0",
"version": "1.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "skillkit",
"version": "1.0.0",
"version": "1.2.0",
"license": "MIT",
"dependencies": {
"chalk": "^5.3.0",
"clipanion": "^4.0.0-rc.4",
"got": "^14.4.1",
"ink": "^5.0.1",
"ink-select-input": "^6.0.0",
"ink-spinner": "^5.0.0",
"ink-text-input": "^6.0.0",
"isomorphic-git": "^1.27.1",
"ora": "^8.1.0",
"react": "^18.3.1",
"yaml": "^2.6.1",
"zod": "^3.24.1"
},
@@ -23,6 +28,7 @@
},
"devDependencies": {
"@types/node": "^22.10.5",
"@types/react": "^18.3.18",
"tsup": "^8.3.5",
"typescript": "^5.7.2",
"vitest": "^2.1.8"
@@ -31,6 +37,19 @@
"node": ">=18.0.0"
}
},
"node_modules/@alcalzone/ansi-tokenize": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.1.3.tgz",
"integrity": "sha512-3yWxPTq3UQ/FY9p1ErPxIyfT64elWaMvM9lIHnaqpyft63tkxodF5aUElYHrdisWve5cETkh1+KBw1yJuW0aRw==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.2.1",
"is-fullwidth-code-point": "^4.0.0"
},
"engines": {
"node": ">=14.13.1"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
@@ -909,6 +928,24 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"devOptional": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.27",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz",
"integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==",
"devOptional": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.2.2"
}
},
"node_modules/@vitest/expect": {
"version": "2.1.9",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
@@ -1061,6 +1098,21 @@
"node": ">=0.4.0"
}
},
"node_modules/ansi-escapes": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.2.0.tgz",
"integrity": "sha512-g6LhBsl+GBPRWGWsBtutpzBYuIIdBkLEvad5C/va/74Db018+5TZiyA26cZJAr3Rft5lprVqOIPxf5Vid6tqAw==",
"license": "MIT",
"dependencies": {
"environment": "^1.0.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/ansi-regex": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz",
@@ -1073,6 +1125,18 @@
"url": "https://github.com/chalk/ansi-regex?sponsor=1"
}
},
"node_modules/ansi-styles": {
"version": "6.2.3",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
"integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/any-promise": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz",
@@ -1096,6 +1160,18 @@
"integrity": "sha512-Az2ZTpuytrtqENulXwO3GGv1Bztugx6TT37NIo7imr/Qo0gsYiGtSdBa2B6fsXhTpVZDNfu1Qn3pk531e3q+nQ==",
"license": "MIT"
},
"node_modules/auto-bind": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/auto-bind/-/auto-bind-5.0.1.tgz",
"integrity": "sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg==",
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/available-typed-arrays": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
@@ -1328,6 +1404,18 @@
"integrity": "sha512-bLSptAy2P0s6hU4PzuIMKmMJJSE6gLXGH1cntDu7bWJUksvuM+7ReOK61mozULErYvP6a15rnYl0zFDef+pyPw==",
"license": "Apache-2.0"
},
"node_modules/cli-boxes": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz",
"integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==",
"license": "MIT",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/cli-cursor": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz",
@@ -1355,6 +1443,38 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/cli-truncate": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz",
"integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==",
"license": "MIT",
"dependencies": {
"slice-ansi": "^5.0.0",
"string-width": "^7.0.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/cli-truncate/node_modules/slice-ansi": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz",
"integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.0.0",
"is-fullwidth-code-point": "^4.0.0"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/chalk/slice-ansi?sponsor=1"
}
},
"node_modules/clipanion": {
"version": "4.0.0-rc.4",
"resolved": "https://registry.npmjs.org/clipanion/-/clipanion-4.0.0-rc.4.tgz",
@@ -1370,6 +1490,18 @@
"typanion": "*"
}
},
"node_modules/code-excerpt": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-4.0.0.tgz",
"integrity": "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA==",
"license": "MIT",
"dependencies": {
"convert-to-spaces": "^2.0.1"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
}
},
"node_modules/commander": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
@@ -1397,6 +1529,15 @@
"node": "^14.18.0 || >=16.10.0"
}
},
"node_modules/convert-to-spaces": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-2.0.1.tgz",
"integrity": "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==",
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
}
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
@@ -1409,6 +1550,13 @@
"node": ">=0.8"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"devOptional": true,
"license": "MIT"
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -1495,6 +1643,18 @@
"integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
"license": "MIT"
},
"node_modules/environment": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz",
"integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -1532,6 +1692,16 @@
"node": ">= 0.4"
}
},
"node_modules/es-toolkit": {
"version": "1.44.0",
"resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.44.0.tgz",
"integrity": "sha512-6penXeZalaV88MM3cGkFZZfOoLGWshWWfdy0tWw/RlVVyhvMaWSBTOvXNeiW3e5FwdS5ePW0LGEu17zT139ktg==",
"license": "MIT",
"workspaces": [
"docs",
"benchmarks"
]
},
"node_modules/esbuild": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",
@@ -1574,6 +1744,15 @@
"@esbuild/win32-x64": "0.27.2"
}
},
"node_modules/escape-string-regexp": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz",
"integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
@@ -1630,6 +1809,21 @@
}
}
},
"node_modules/figures": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz",
"integrity": "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==",
"license": "MIT",
"dependencies": {
"is-unicode-supported": "^2.0.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/fix-dts-default-cjs-exports": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/fix-dts-default-cjs-exports/-/fix-dts-default-cjs-exports-1.0.1.tgz",
@@ -1892,12 +2086,174 @@
"node": ">= 4"
}
},
"node_modules/indent-string": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz",
"integrity": "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ink": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/ink/-/ink-5.2.1.tgz",
"integrity": "sha512-BqcUyWrG9zq5HIwW6JcfFHsIYebJkWWb4fczNah1goUO0vv5vneIlfwuS85twyJ5hYR/y18FlAYUxrO9ChIWVg==",
"license": "MIT",
"dependencies": {
"@alcalzone/ansi-tokenize": "^0.1.3",
"ansi-escapes": "^7.0.0",
"ansi-styles": "^6.2.1",
"auto-bind": "^5.0.1",
"chalk": "^5.3.0",
"cli-boxes": "^3.0.0",
"cli-cursor": "^4.0.0",
"cli-truncate": "^4.0.0",
"code-excerpt": "^4.0.0",
"es-toolkit": "^1.22.0",
"indent-string": "^5.0.0",
"is-in-ci": "^1.0.0",
"patch-console": "^2.0.0",
"react-reconciler": "^0.29.0",
"scheduler": "^0.23.0",
"signal-exit": "^3.0.7",
"slice-ansi": "^7.1.0",
"stack-utils": "^2.0.6",
"string-width": "^7.2.0",
"type-fest": "^4.27.0",
"widest-line": "^5.0.0",
"wrap-ansi": "^9.0.0",
"ws": "^8.18.0",
"yoga-layout": "~3.2.1"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"@types/react": ">=18.0.0",
"react": ">=18.0.0",
"react-devtools-core": "^4.19.1"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"react-devtools-core": {
"optional": true
}
}
},
"node_modules/ink-select-input": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/ink-select-input/-/ink-select-input-6.2.0.tgz",
"integrity": "sha512-304fZXxkpYxJ9si5lxRCaX01GNlmPBgOZumXXRnPYbHW/iI31cgQynqk2tRypGLOF1cMIwPUzL2LSm6q4I5rQQ==",
"license": "MIT",
"dependencies": {
"figures": "^6.1.0",
"to-rotated": "^1.0.0"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"ink": ">=5.0.0",
"react": ">=18.0.0"
}
},
"node_modules/ink-spinner": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/ink-spinner/-/ink-spinner-5.0.0.tgz",
"integrity": "sha512-EYEasbEjkqLGyPOUc8hBJZNuC5GvXGMLu0w5gdTNskPc7Izc5vO3tdQEYnzvshucyGCBXc86ig0ujXPMWaQCdA==",
"license": "MIT",
"dependencies": {
"cli-spinners": "^2.7.0"
},
"engines": {
"node": ">=14.16"
},
"peerDependencies": {
"ink": ">=4.0.0",
"react": ">=18.0.0"
}
},
"node_modules/ink-text-input": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/ink-text-input/-/ink-text-input-6.0.0.tgz",
"integrity": "sha512-Fw64n7Yha5deb1rHY137zHTAbSTNelUKuB5Kkk2HACXEtwIHBCf9OH2tP/LQ9fRYTl1F0dZgbW0zPnZk6FA9Lw==",
"license": "MIT",
"dependencies": {
"chalk": "^5.3.0",
"type-fest": "^4.18.2"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"ink": ">=5",
"react": ">=18"
}
},
"node_modules/ink/node_modules/cli-cursor": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz",
"integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==",
"license": "MIT",
"dependencies": {
"restore-cursor": "^4.0.0"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/ink/node_modules/onetime": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
"integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
"license": "MIT",
"dependencies": {
"mimic-fn": "^2.1.0"
},
"engines": {
"node": ">=6"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/ink/node_modules/restore-cursor": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz",
"integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==",
"license": "MIT",
"dependencies": {
"onetime": "^5.1.0",
"signal-exit": "^3.0.2"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/ink/node_modules/signal-exit": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
"license": "ISC"
},
"node_modules/is-callable": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz",
@@ -1910,6 +2266,33 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz",
"integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-in-ci": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-1.0.0.tgz",
"integrity": "sha512-eUuAjybVTHMYWm/U+vBO1sY/JOCgoPCXRxzdju0K+K0BiGW0SChEL1MLC0PoCIR1OlPo5YAp8HuQoUlsWEICwg==",
"license": "MIT",
"bin": {
"is-in-ci": "cli.js"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/is-interactive": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz",
@@ -2002,6 +2385,12 @@
"node": ">=10"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"license": "MIT"
},
"node_modules/keyv": {
"version": "5.5.5",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-5.5.5.tgz",
@@ -2069,6 +2458,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/loupe": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
@@ -2107,6 +2508,15 @@
"node": ">= 0.4"
}
},
"node_modules/mimic-fn": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
"integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/mimic-function": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz",
@@ -2284,6 +2694,15 @@
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/patch-console": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz",
"integrity": "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA==",
"license": "MIT",
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
}
},
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
@@ -2454,6 +2873,34 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-reconciler": {
"version": "0.29.2",
"resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.29.2.tgz",
"integrity": "sha512-zZQqIiYgDCTP/f1N/mAR10nJGrPD2ZR+jDSEsKWJHYC7Cm2wodlwbR3upZRdC3cjIjSlTLNVyO7Iu0Yy7t2AYg==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
},
"engines": {
"node": ">=0.10.0"
},
"peerDependencies": {
"react": "^18.3.1"
}
},
"node_modules/readable-stream": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
@@ -2596,6 +3043,15 @@
],
"license": "MIT"
},
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
},
"node_modules/set-function-length": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",
@@ -2724,6 +3180,37 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/slice-ansi": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz",
"integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.2.1",
"is-fullwidth-code-point": "^5.0.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/chalk/slice-ansi?sponsor=1"
}
},
"node_modules/slice-ansi/node_modules/is-fullwidth-code-point": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz",
"integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==",
"license": "MIT",
"dependencies": {
"get-east-asian-width": "^1.3.1"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/source-map": {
"version": "0.7.6",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",
@@ -2744,6 +3231,18 @@
"node": ">=0.10.0"
}
},
"node_modules/stack-utils": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz",
"integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==",
"license": "MIT",
"dependencies": {
"escape-string-regexp": "^2.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
@@ -2932,6 +3431,18 @@
"node": ">= 0.4"
}
},
"node_modules/to-rotated": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/to-rotated/-/to-rotated-1.0.0.tgz",
"integrity": "sha512-KsEID8AfgUy+pxVRLsWp0VzCa69wxzUDZnzGbyIST/bcgcrMvTYoFBX/QORH4YApoD89EDuUovx4BTdpOn319Q==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
@@ -3696,12 +4207,65 @@
"node": ">=8"
}
},
"node_modules/widest-line": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/widest-line/-/widest-line-5.0.0.tgz",
"integrity": "sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==",
"license": "MIT",
"dependencies": {
"string-width": "^7.0.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/wrap-ansi": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
"integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^6.2.1",
"string-width": "^7.0.0",
"strip-ansi": "^7.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/ws": {
"version": "8.19.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz",
"integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/yaml": {
"version": "2.8.2",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.2.tgz",
@@ -3717,6 +4281,12 @@
"url": "https://github.com/sponsors/eemeli"
}
},
"node_modules/yoga-layout": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-3.2.1.tgz",
"integrity": "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==",
"license": "MIT"
},
"node_modules/zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
+16 -36
View File
@@ -1,33 +1,18 @@
{
"name": "skillkit",
"version": "1.0.2",
"description": "Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more",
"name": "skillkit-monorepo",
"version": "1.4.0",
"private": true,
"description": "Universal skills loader for AI coding agents - Monorepo",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"bin": {
"skillkit": "./dist/cli.js",
"sk": "./dist/cli.js"
},
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": [
"dist",
"schemas"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"test": "vitest run",
"build": "turbo run build",
"dev": "turbo run dev",
"test": "turbo run test",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"typecheck": "tsc --noEmit",
"lint": "eslint src --ext .ts",
"prepublishOnly": "npm run typecheck && npm run build && npm run test"
"typecheck": "turbo run typecheck",
"lint": "turbo run lint",
"clean": "rm -rf node_modules packages/*/node_modules apps/*/node_modules packages/*/dist apps/*/dist"
},
"keywords": [
"ai",
@@ -41,10 +26,11 @@
"agent",
"coding-assistant",
"skill-loader",
"cli"
"cli",
"monorepo"
],
"author": "Rohit Ghumare",
"license": "MIT",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/rohitg00/skillkit.git"
@@ -56,18 +42,12 @@
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"chalk": "^5.3.0",
"clipanion": "^4.0.0-rc.4",
"got": "^14.4.1",
"isomorphic-git": "^1.27.1",
"ora": "^8.1.0",
"yaml": "^2.6.1",
"zod": "^3.24.1"
},
"packageManager": "pnpm@9.0.0",
"devDependencies": {
"@types/node": "^22.10.5",
"@types/react": "^18.3.18",
"tsup": "^8.3.5",
"turbo": "^2.3.4",
"typescript": "^5.7.2",
"vitest": "^2.1.8"
}
+53
View File
@@ -0,0 +1,53 @@
# @skillkit/agents
Agent adapters for SkillKit - supports 17+ AI coding agents.
## Installation
```bash
npm install @skillkit/agents
```
## Supported Agents
| Agent | Config Format | Skills Directory |
|-------|--------------|------------------|
| Claude Code | SKILL.md | `.claude/skills/` |
| Cursor | .cursorrules, .mdc | `.cursor/skills/` |
| Codex | SKILL.md | `.codex/skills/` |
| Gemini CLI | SKILL.md | `.gemini/skills/` |
| Windsurf | .windsurfrules | `.windsurf/skills/` |
| GitHub Copilot | Markdown | `.github/copilot-instructions.md` |
| OpenCode | SKILL.md | `.opencode/skills/` |
| Antigravity | SKILL.md | `.antigravity/skills/` |
| Amp | SKILL.md | `.amp/skills/` |
| Goose | SKILL.md | `.goose/skills/` |
| Kilo | SKILL.md | `.kilocode/skills/` |
| Roo | SKILL.md | `.roo/skills/` |
| Trae | SKILL.md | `.trae/skills/` |
| And more... | | |
## Usage
```typescript
import { getAdapter, detectAgent, listAdapters } from '@skillkit/agents';
// Get adapter for specific agent
const adapter = getAdapter('claude-code');
console.log(adapter.skillsDir); // .claude/skills/
// Detect installed agents
const detected = detectAgent();
console.log(detected); // ['claude-code', 'cursor']
// List all available adapters
const adapters = listAdapters();
```
## Documentation
Full documentation: https://github.com/rohitg00/skillkit
## License
Apache-2.0
+34
View File
@@ -0,0 +1,34 @@
{
"name": "@skillkit/agents",
"version": "1.4.0",
"description": "Agent adapters for SkillKit - supports 17+ AI coding agents",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": ["dist"],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@skillkit/core": "workspace:*"
},
"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"
}
@@ -0,0 +1,42 @@
import { describe, it, expect } from 'vitest';
import { getAllAdapters, getAdapter, detectAgent } from '../index.js';
describe('Agent Adapters', () => {
describe('getAllAdapters', () => {
it('should return all registered adapters', () => {
const adapters = getAllAdapters();
expect(adapters).toBeInstanceOf(Array);
expect(adapters.length).toBeGreaterThan(0);
});
it('should include common agents', () => {
const adapters = getAllAdapters();
const types = adapters.map(a => a.type);
// Should include at least some well-known agents
expect(types).toContain('claude-code');
expect(types).toContain('cursor');
});
});
describe('getAdapter', () => {
it('should return adapter for known agent type', () => {
const adapter = getAdapter('claude-code');
expect(adapter).toBeDefined();
expect(adapter.type).toBe('claude-code');
expect(adapter.name).toBeDefined();
});
it('should return undefined for unknown agent type', () => {
const adapter = getAdapter('unknown-agent' as any);
expect(adapter).toBeUndefined();
});
});
describe('detectAgent', () => {
it('should return an agent type', async () => {
const agent = await detectAgent();
expect(typeof agent).toBe('string');
});
});
});
+74
View File
@@ -0,0 +1,74 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class AmpAdapter implements AgentAdapter {
readonly type: AgentType = 'amp';
readonly name = 'Amp';
readonly skillsDir = '.agents/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectAgents = join(process.cwd(), '.agents');
const globalAgents = join(homedir(), '.config', 'agents');
return existsSync(projectAgents) || existsSync(globalAgents);
}
}
+80
View File
@@ -0,0 +1,80 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class AntigravityAdapter implements AgentAdapter {
readonly type: AgentType = 'antigravity';
readonly name = 'Antigravity';
readonly skillsDir = '.antigravity/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsYaml = enabledSkills
.map(s => ` - name: ${s.name}\n description: "${s.description}"\n invoke: skillkit read ${s.name}`)
.join('\n');
return `# Antigravity Skills Configuration
<!-- skills:
${skillsYaml}
-->
## Available Skills
${enabledSkills.map(s => `### ${s.name}
${s.description}
**Usage:** \`skillkit read ${s.name}\`
`).join('\n')}
## How Skills Work
1. Skills provide specialized knowledge for specific tasks
2. Load a skill when the current task matches its description
3. Skills are loaded on-demand to preserve context window
`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const yamlMatch = content.match(/<!-- skills:\s*([\s\S]*?)-->/);
if (yamlMatch) {
const nameRegex = /name:\s*([a-z0-9-]+)/g;
let match;
while ((match = nameRegex.exec(yamlMatch[1])) !== null) {
skillNames.push(match[1].trim());
}
}
if (skillNames.length === 0) {
const headerRegex = /^### ([a-z0-9-]+)$/gm;
let match;
while ((match = headerRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const agDir = join(process.cwd(), '.antigravity');
const globalAg = join(homedir(), '.antigravity');
return existsSync(agDir) || existsSync(globalAg);
}
}
+30
View File
@@ -0,0 +1,30 @@
import type { Skill, AgentType } from '@skillkit/core';
export interface AgentAdapter {
readonly type: AgentType;
readonly name: string;
readonly skillsDir: string;
readonly configFile: string;
generateConfig(skills: Skill[]): string;
parseConfig(content: string): string[];
getInvokeCommand(skillName: string): string;
isDetected(): Promise<boolean>;
}
export function createSkillXml(skill: Skill): string {
return `<skill>
<name>${skill.name}</name>
<description>${escapeXml(skill.description)}</description>
<location>${skill.location}</location>
</skill>`;
}
export function escapeXml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
+75
View File
@@ -0,0 +1,75 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class ClaudeCodeAdapter implements AgentAdapter {
readonly type: AgentType = 'claude-code';
readonly name = 'Claude Code';
readonly skillsDir = '.claude/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectClaude = join(process.cwd(), '.claude');
const globalClaude = join(homedir(), '.claude');
const claudeMd = join(process.cwd(), 'CLAUDE.md');
return existsSync(projectClaude) || existsSync(globalClaude) || existsSync(claudeMd);
}
}
+74
View File
@@ -0,0 +1,74 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class ClawdbotAdapter implements AgentAdapter {
readonly type: AgentType = 'clawdbot';
readonly name = 'Clawdbot';
readonly skillsDir = 'skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectSkills = join(process.cwd(), 'skills');
const globalClawdbot = join(homedir(), '.clawdbot');
return existsSync(globalClawdbot) || (existsSync(projectSkills) && existsSync(join(process.cwd(), '.clawdbot')));
}
}
+69
View File
@@ -0,0 +1,69 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class CodexAdapter implements AgentAdapter {
readonly type: AgentType = 'codex';
readonly name = 'OpenAI Codex CLI';
readonly skillsDir = '.codex/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsList = enabledSkills
.map(s => `| ${s.name} | ${s.description} | \`skillkit read ${s.name}\` |`)
.join('\n');
return `# Skills
You have access to specialized skills for completing complex tasks.
| Skill | Description | Command |
|-------|-------------|---------|
${skillsList}
## Usage
When a task matches a skill's capability, run the command to load detailed instructions:
\`\`\`bash
skillkit read <skill-name>
\`\`\`
Skills are loaded on-demand to keep context clean. Only load skills when relevant to the current task.
`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const tableRegex = /^\|\s*([a-z0-9-]+)\s*\|/gm;
let match;
while ((match = tableRegex.exec(content)) !== null) {
const name = match[1].trim();
if (name && name !== 'Skill' && name !== '-------') {
skillNames.push(name);
}
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const codexDir = join(process.cwd(), '.codex');
const globalCodex = join(homedir(), '.codex');
return existsSync(codexDir) || existsSync(globalCodex);
}
}
+71
View File
@@ -0,0 +1,71 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class CursorAdapter implements AgentAdapter {
readonly type: AgentType = 'cursor';
readonly name = 'Cursor';
readonly skillsDir = '.cursor/skills';
readonly configFile = '.cursorrules';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsList = enabledSkills
.map(s => `- **${s.name}**: ${s.description}`)
.join('\n');
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `# Skills System
You have access to specialized skills that can help complete tasks. Use the skillkit CLI to load skill instructions when needed.
## Available Skills
${skillsList}
## How to Use Skills
When a task matches a skill's description, load it with:
\`\`\`bash
skillkit read <skill-name>
\`\`\`
The skill will provide detailed instructions for completing the task.
<!-- SKILLS_DATA_START -->
${skillsXml}
<!-- SKILLS_DATA_END -->
`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const cursorRules = join(process.cwd(), '.cursorrules');
const cursorDir = join(process.cwd(), '.cursor');
return existsSync(cursorRules) || existsSync(cursorDir);
}
}
+74
View File
@@ -0,0 +1,74 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class DroidAdapter implements AgentAdapter {
readonly type: AgentType = 'droid';
readonly name = 'Droid (Factory)';
readonly skillsDir = '.factory/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectFactory = join(process.cwd(), '.factory');
const globalFactory = join(homedir(), '.factory');
return existsSync(projectFactory) || existsSync(globalFactory);
}
}
+88
View File
@@ -0,0 +1,88 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class GeminiCliAdapter implements AgentAdapter {
readonly type: AgentType = 'gemini-cli';
readonly name = 'Gemini CLI';
readonly skillsDir = '.gemini/skills';
readonly configFile = 'GEMINI.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsJson = enabledSkills.map(s => ({
name: s.name,
description: s.description,
invoke: `skillkit read ${s.name}`,
location: s.location,
}));
return `# Skills Configuration
You have access to specialized skills that extend your capabilities.
## Available Skills
${enabledSkills.map(s => `### ${s.name}\n${s.description}\n\nInvoke: \`skillkit read ${s.name}\``).join('\n\n')}
## Skills Data
\`\`\`json
${JSON.stringify(skillsJson, null, 2)}
\`\`\`
## Usage Instructions
1. When a task matches a skill's description, load it using the invoke command
2. Skills provide step-by-step instructions for complex tasks
3. Each skill is self-contained with its own resources
`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const jsonMatch = content.match(/```json\s*([\s\S]*?)```/);
if (jsonMatch) {
try {
const skills = JSON.parse(jsonMatch[1]);
if (Array.isArray(skills)) {
skills.forEach(s => {
if (s.name) skillNames.push(s.name);
});
}
} catch {
// Ignore parse errors
}
}
if (skillNames.length === 0) {
const headerRegex = /^### ([a-z0-9-]+)$/gm;
let match;
while ((match = headerRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const geminiMd = join(process.cwd(), 'GEMINI.md');
const geminiDir = join(process.cwd(), '.gemini');
const globalGemini = join(homedir(), '.gemini');
return existsSync(geminiMd) || existsSync(geminiDir) || existsSync(globalGemini);
}
}
+74
View File
@@ -0,0 +1,74 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class GitHubCopilotAdapter implements AgentAdapter {
readonly type: AgentType = 'github-copilot';
readonly name = 'GitHub Copilot';
readonly skillsDir = '.github/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectGithub = join(process.cwd(), '.github', 'skills');
const globalCopilot = join(homedir(), '.copilot');
return existsSync(projectGithub) || existsSync(globalCopilot);
}
}
+74
View File
@@ -0,0 +1,74 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class GooseAdapter implements AgentAdapter {
readonly type: AgentType = 'goose';
readonly name = 'Goose';
readonly skillsDir = '.goose/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectGoose = join(process.cwd(), '.goose');
const globalGoose = join(homedir(), '.config', 'goose');
return existsSync(projectGoose) || existsSync(globalGoose);
}
}
+105
View File
@@ -0,0 +1,105 @@
import type { AgentAdapter } from './base.js';
import type { AgentType } from '@skillkit/core';
import { ClaudeCodeAdapter } from './claude-code.js';
import { CursorAdapter } from './cursor.js';
import { CodexAdapter } from './codex.js';
import { GeminiCliAdapter } from './gemini-cli.js';
import { OpenCodeAdapter } from './opencode.js';
import { AntigravityAdapter } from './antigravity.js';
import { AmpAdapter } from './amp.js';
import { ClawdbotAdapter } from './clawdbot.js';
import { DroidAdapter } from './droid.js';
import { GitHubCopilotAdapter } from './github-copilot.js';
import { GooseAdapter } from './goose.js';
import { KiloAdapter } from './kilo.js';
import { KiroCliAdapter } from './kiro-cli.js';
import { RooAdapter } from './roo.js';
import { TraeAdapter } from './trae.js';
import { WindsurfAdapter } from './windsurf.js';
import { UniversalAdapter } from './universal.js';
export * from './base.js';
export * from './claude-code.js';
export * from './cursor.js';
export * from './codex.js';
export * from './gemini-cli.js';
export * from './opencode.js';
export * from './antigravity.js';
export * from './amp.js';
export * from './clawdbot.js';
export * from './droid.js';
export * from './github-copilot.js';
export * from './goose.js';
export * from './kilo.js';
export * from './kiro-cli.js';
export * from './roo.js';
export * from './trae.js';
export * from './windsurf.js';
export * from './universal.js';
const adapters: Record<AgentType, AgentAdapter> = {
'claude-code': new ClaudeCodeAdapter(),
cursor: new CursorAdapter(),
codex: new CodexAdapter(),
'gemini-cli': new GeminiCliAdapter(),
opencode: new OpenCodeAdapter(),
antigravity: new AntigravityAdapter(),
amp: new AmpAdapter(),
clawdbot: new ClawdbotAdapter(),
droid: new DroidAdapter(),
'github-copilot': new GitHubCopilotAdapter(),
goose: new GooseAdapter(),
kilo: new KiloAdapter(),
'kiro-cli': new KiroCliAdapter(),
roo: new RooAdapter(),
trae: new TraeAdapter(),
windsurf: new WindsurfAdapter(),
universal: new UniversalAdapter(),
};
export function getAdapter(type: AgentType): AgentAdapter {
return adapters[type];
}
export function getAllAdapters(): AgentAdapter[] {
return Object.values(adapters);
}
export async function detectAgent(): Promise<AgentType> {
const checkOrder: AgentType[] = [
'claude-code',
'cursor',
'codex',
'gemini-cli',
'opencode',
'antigravity',
'amp',
'clawdbot',
'droid',
'github-copilot',
'goose',
'kilo',
'kiro-cli',
'roo',
'trae',
'windsurf',
'universal',
];
for (const type of checkOrder) {
const adapter = adapters[type];
if (await adapter.isDetected()) {
return type;
}
}
return 'universal';
}
export function getSkillsDir(type: AgentType): string {
return adapters[type].skillsDir;
}
export function getConfigFile(type: AgentType): string {
return adapters[type].configFile;
}
+74
View File
@@ -0,0 +1,74 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class KiloAdapter implements AgentAdapter {
readonly type: AgentType = 'kilo';
readonly name = 'Kilo Code';
readonly skillsDir = '.kilocode/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectKilo = join(process.cwd(), '.kilocode');
const globalKilo = join(homedir(), '.kilocode');
return existsSync(projectKilo) || existsSync(globalKilo);
}
}
+84
View File
@@ -0,0 +1,84 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class KiroCliAdapter implements AgentAdapter {
readonly type: AgentType = 'kiro-cli';
readonly name = 'Kiro CLI';
readonly skillsDir = '.kiro/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>
**Note for Kiro CLI users:** After installing skills, you need to manually add them to your custom agent's \`resources\` in \`.kiro/agents/<agent>.json\`:
\`\`\`json
{
"resources": [
"skill://.kiro/skills/**/SKILL.md"
]
}
\`\`\``;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectKiro = join(process.cwd(), '.kiro');
const globalKiro = join(homedir(), '.kiro');
return existsSync(projectKiro) || existsSync(globalKiro);
}
}
+67
View File
@@ -0,0 +1,67 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class OpenCodeAdapter implements AgentAdapter {
readonly type: AgentType = 'opencode';
readonly name = 'OpenCode';
readonly skillsDir = '.opencode/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<!-- SKILLKIT_START -->
# Skills
The following skills are available to help complete tasks:
<skills>
${skillsXml}
</skills>
## How to Use
When a task matches a skill's description:
\`\`\`bash
skillkit read <skill-name>
\`\`\`
This loads the skill's instructions into context.
<!-- SKILLKIT_END -->`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const opencodeDir = join(process.cwd(), '.opencode');
const globalOpencode = join(homedir(), '.opencode');
return existsSync(opencodeDir) || existsSync(globalOpencode);
}
}
+74
View File
@@ -0,0 +1,74 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class RooAdapter implements AgentAdapter {
readonly type: AgentType = 'roo';
readonly name = 'Roo Code';
readonly skillsDir = '.roo/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectRoo = join(process.cwd(), '.roo');
const globalRoo = join(homedir(), '.roo');
return existsSync(projectRoo) || existsSync(globalRoo);
}
}
+74
View File
@@ -0,0 +1,74 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class TraeAdapter implements AgentAdapter {
readonly type: AgentType = 'trae';
readonly name = 'Trae';
readonly skillsDir = '.trae/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectTrae = join(process.cwd(), '.trae');
const globalTrae = join(homedir(), '.trae');
return existsSync(projectTrae) || existsSync(globalTrae);
}
}
+98
View File
@@ -0,0 +1,98 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class UniversalAdapter implements AgentAdapter {
readonly type: AgentType = 'universal';
readonly name = 'Universal (Any Agent)';
readonly skillsDir = '.agent/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
const skillsList = enabledSkills
.map(s => `- **${s.name}**: ${s.description}`)
.join('\n');
return `# Skills System
<!-- SKILLKIT_SKILLS_START -->
## Available Skills
${skillsList}
## How to Use Skills
When a task matches one of the available skills, load it to get detailed instructions:
\`\`\`bash
skillkit read <skill-name>
\`\`\`
Or with npx:
\`\`\`bash
npx skillkit read <skill-name>
\`\`\`
## Skills Data
<skills_system>
<usage>
Skills provide specialized capabilities and domain knowledge.
- Invoke: \`skillkit read <skill-name>\`
- Base directory provided in output for resolving resources
- Only use skills listed below
- Each invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
</skills_system>
<!-- SKILLKIT_SKILLS_END -->
`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
if (skillNames.length === 0) {
const listRegex = /^- \*\*([a-z0-9-]+)\*\*:/gm;
while ((match = listRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const agentDir = join(process.cwd(), '.agent');
const agentsMd = join(process.cwd(), 'AGENTS.md');
return existsSync(agentDir) || existsSync(agentsMd);
}
}
+74
View File
@@ -0,0 +1,74 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type { AgentAdapter } from './base.js';
import { createSkillXml } from './base.js';
import type { Skill, AgentType } from '@skillkit/core';
export class WindsurfAdapter implements AgentAdapter {
readonly type: AgentType = 'windsurf';
readonly name = 'Windsurf';
readonly skillsDir = '.windsurf/skills';
readonly configFile = 'AGENTS.md';
generateConfig(skills: Skill[]): string {
const enabledSkills = skills.filter(s => s.enabled);
if (enabledSkills.length === 0) {
return '';
}
const skillsXml = enabledSkills.map(createSkillXml).join('\n\n');
return `<skills_system priority="1">
## Available Skills
<!-- SKILLS_TABLE_START -->
<usage>
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
How to use skills:
- Invoke: \`skillkit read <skill-name>\` or \`npx skillkit read <skill-name>\`
- The skill content will load with detailed instructions on how to complete the task
- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/)
Usage notes:
- Only use skills listed in <available_skills> below
- Do not invoke a skill that is already loaded in your context
- Each skill invocation is stateless
</usage>
<available_skills>
${skillsXml}
</available_skills>
<!-- SKILLS_TABLE_END -->
</skills_system>`;
}
parseConfig(content: string): string[] {
const skillNames: string[] = [];
const skillRegex = /<name>([^<]+)<\/name>/g;
let match;
while ((match = skillRegex.exec(content)) !== null) {
skillNames.push(match[1].trim());
}
return skillNames;
}
getInvokeCommand(skillName: string): string {
return `skillkit read ${skillName}`;
}
async isDetected(): Promise<boolean> {
const projectWindsurf = join(process.cwd(), '.windsurf');
const globalWindsurf = join(homedir(), '.codeium', 'windsurf');
return existsSync(projectWindsurf) || existsSync(globalWindsurf);
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": false
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
+14
View File
@@ -0,0 +1,14 @@
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',
});
+43
View File
@@ -0,0 +1,43 @@
# @skillkit/cli
CLI commands for SkillKit - install, manage, and sync skills across AI agents.
## Installation
```bash
npm install @skillkit/cli
```
## Commands
```bash
skillkit init # Initialize skillkit in project
skillkit install <skill> # Install a skill
skillkit remove <skill> # Remove a skill
skillkit list # List installed skills
skillkit update # Update installed skills
skillkit sync # Sync skills across agents
skillkit translate # Translate skills between formats
skillkit recommend # Get skill recommendations
skillkit context # Manage project context
skillkit ui # Launch interactive TUI
```
## Usage
```typescript
import { installCommand, listCommand, syncCommand } from '@skillkit/cli';
// Programmatic access to CLI commands
await installCommand('github.com/owner/repo:skill-name');
await listCommand();
await syncCommand({ all: true });
```
## Documentation
Full documentation: https://github.com/rohitg00/skillkit
## License
Apache-2.0
+42
View File
@@ -0,0 +1,42 @@
{
"name": "@skillkit/cli",
"version": "1.4.0",
"description": "CLI commands for SkillKit",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
}
},
"files": ["dist"],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@skillkit/core": "workspace:*",
"@skillkit/agents": "workspace:*",
"@skillkit/tui": "workspace:*",
"chalk": "^5.3.0",
"clipanion": "^4.0.0-rc.4",
"got": "^14.4.1",
"isomorphic-git": "^1.27.1",
"ora": "^8.1.0",
"yaml": "^2.7.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"
}
@@ -0,0 +1,25 @@
import { describe, it, expect } from 'vitest';
describe('CLI Commands', () => {
describe('exports', () => {
it('should export all commands', async () => {
const commands = await import('../commands/index.js');
expect(commands.ListCommand).toBeDefined();
expect(commands.ReadCommand).toBeDefined();
expect(commands.SyncCommand).toBeDefined();
expect(commands.InitCommand).toBeDefined();
expect(commands.EnableCommand).toBeDefined();
expect(commands.DisableCommand).toBeDefined();
expect(commands.RemoveCommand).toBeDefined();
expect(commands.InstallCommand).toBeDefined();
expect(commands.UpdateCommand).toBeDefined();
expect(commands.ValidateCommand).toBeDefined();
expect(commands.CreateCommand).toBeDefined();
expect(commands.UICommand).toBeDefined();
expect(commands.TranslateCommand).toBeDefined();
expect(commands.ContextCommand).toBeDefined();
expect(commands.RecommendCommand).toBeDefined();
});
});
});
+495
View File
@@ -0,0 +1,495 @@
import { Command, Option } from 'clipanion';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import chalk from 'chalk';
import {
type AgentType,
type ProjectContext,
ContextManager,
createContextSync,
analyzeProject,
getStackTags,
} from '@skillkit/core';
import { getAllAdapters } from '@skillkit/agents';
/**
* Context command - manage project context for multi-agent sync
*/
export class ContextCommand extends Command {
static override paths = [['context']];
static override usage = Command.Usage({
description: 'Manage project context for multi-agent skill synchronization',
details: `
The context command helps you configure your project once and sync skills
across all AI coding agents.
Subcommands:
- init: Initialize project context with auto-detection
- show: Display current project context
- export: Export context to a file
- import: Import context from a file
- sync: Sync skills to all configured agents
- detect: Run project detection
`,
examples: [
['Initialize project context', '$0 context init'],
['Show current context', '$0 context show'],
['Sync skills to all agents', '$0 context sync'],
['Sync to specific agent', '$0 context sync --agent cursor'],
['Export context', '$0 context export --output context.yaml'],
],
});
// Subcommand (init, show, export, import, sync, detect)
action = Option.String({ required: false });
// Agent filter
agent = Option.String('--agent,-a', {
description: 'Target agent for sync',
});
// Output file for export
output = Option.String('--output,-o', {
description: 'Output file path',
});
// Input file for import
input = Option.String('--input,-i', {
description: 'Input file path',
});
// Force overwrite
force = Option.Boolean('--force,-f', false, {
description: 'Force overwrite existing files',
});
// Dry run
dryRun = Option.Boolean('--dry-run,-n', false, {
description: 'Preview without making changes',
});
// Merge on import
merge = Option.Boolean('--merge,-m', false, {
description: 'Merge with existing context on import',
});
// JSON output
json = Option.Boolean('--json,-j', false, {
description: 'Output in JSON format',
});
// Verbose output
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed output',
});
async execute(): Promise<number> {
const action = this.action || 'show';
switch (action) {
case 'init':
return this.initContext();
case 'show':
return this.showContext();
case 'export':
return this.exportContext();
case 'import':
return this.importContext();
case 'sync':
return this.syncContext();
case 'detect':
return this.detectProject();
case 'agents':
return this.listAgents();
default:
console.error(chalk.red(`Unknown action: ${action}`));
console.log(chalk.gray('Available actions: init, show, export, import, sync, detect, agents'));
return 1;
}
}
/**
* Initialize project context
*/
private async initContext(): Promise<number> {
const manager = new ContextManager(process.cwd());
if (manager.exists() && !this.force) {
console.log(chalk.yellow('Context already exists. Use --force to reinitialize.'));
return this.showContext();
}
console.log(chalk.cyan('Initializing project context...\n'));
const context = manager.init({ force: this.force });
console.log(chalk.green('✓ Context initialized\n'));
console.log(chalk.gray(` Location: .skillkit/context.yaml\n`));
// Show summary
this.printContextSummary(context);
// Detect agents
const sync = createContextSync(process.cwd());
const detected = sync.detectAgents();
if (detected.length > 0) {
console.log(chalk.cyan('\nDetected agents:'));
for (const agent of detected) {
console.log(` ${chalk.green('•')} ${agent}`);
}
// Update context with detected agents
manager.updateAgents({
detected,
synced: detected,
});
}
console.log(chalk.gray('\nRun `skillkit context sync` to sync skills to all agents.'));
return 0;
}
/**
* Show current context
*/
private async showContext(): Promise<number> {
const manager = new ContextManager(process.cwd());
const context = manager.load();
if (!context) {
console.log(chalk.yellow('No context found. Run `skillkit context init` first.'));
return 1;
}
if (this.json) {
console.log(JSON.stringify(context, null, 2));
return 0;
}
this.printContextSummary(context);
if (this.verbose) {
console.log(chalk.gray('\nFull context:'));
console.log(chalk.gray(JSON.stringify(context, null, 2)));
}
return 0;
}
/**
* Export context to file
*/
private async exportContext(): Promise<number> {
const manager = new ContextManager(process.cwd());
const context = manager.get();
if (!context) {
console.error(chalk.red('No context found. Run `skillkit context init` first.'));
return 1;
}
const format = this.json ? 'json' : 'yaml';
const content = manager.export({
format,
includeSkills: true,
includeAgents: true,
});
if (this.output) {
const outputPath = resolve(this.output);
if (existsSync(outputPath) && !this.force) {
console.error(chalk.red(`File exists: ${outputPath}. Use --force to overwrite.`));
return 1;
}
writeFileSync(outputPath, content, 'utf-8');
console.log(chalk.green(`✓ Context exported to ${outputPath}`));
} else {
// Print to stdout
console.log(content);
}
return 0;
}
/**
* Import context from file
*/
private async importContext(): Promise<number> {
if (!this.input) {
console.error(chalk.red('Error: --input/-i file path is required'));
return 1;
}
const inputPath = resolve(this.input);
if (!existsSync(inputPath)) {
console.error(chalk.red(`File not found: ${inputPath}`));
return 1;
}
const manager = new ContextManager(process.cwd());
const content = readFileSync(inputPath, 'utf-8');
try {
const context = manager.import(content, {
merge: this.merge,
overwrite: this.force,
});
console.log(chalk.green('✓ Context imported successfully'));
this.printContextSummary(context);
return 0;
} catch (error) {
console.error(chalk.red(`Import failed: ${error}`));
return 1;
}
}
/**
* Sync skills to all configured agents
*/
private async syncContext(): Promise<number> {
const manager = new ContextManager(process.cwd());
const context = manager.get();
if (!context) {
console.log(chalk.yellow('No context found. Initializing...'));
manager.init();
}
const sync = createContextSync(process.cwd());
console.log(chalk.cyan('Syncing skills across agents...\n'));
// Determine target agents
const agents = this.agent ? [this.agent as AgentType] : undefined;
const report = await sync.syncAll({
agents,
force: this.force,
dryRun: this.dryRun,
});
// Print results
for (const result of report.results) {
const status = result.success ? chalk.green('✓') : chalk.red('✗');
console.log(`${status} ${result.agent}: ${result.skillsSynced} synced, ${result.skillsSkipped} skipped`);
if (this.verbose && result.files.length > 0) {
for (const file of result.files) {
console.log(chalk.gray(` → ${file}`));
}
}
if (result.warnings.length > 0) {
for (const warning of result.warnings) {
console.log(chalk.yellow(` ⚠ ${warning}`));
}
}
if (result.errors.length > 0) {
for (const error of result.errors) {
console.log(chalk.red(` ✗ ${error}`));
}
}
}
console.log();
console.log(chalk.bold(`Summary: ${report.successfulAgents}/${report.totalAgents} agents, ${report.totalSkills} skills`));
if (this.dryRun) {
console.log(chalk.gray('\n(Dry run - no files were written)'));
}
return report.successfulAgents === report.totalAgents ? 0 : 1;
}
/**
* Detect project stack
*/
private async detectProject(): Promise<number> {
console.log(chalk.cyan('Analyzing project...\n'));
const stack = analyzeProject(process.cwd());
const tags = getStackTags(stack);
// Languages
if (stack.languages.length > 0) {
console.log(chalk.bold('Languages:'));
for (const lang of stack.languages) {
const version = lang.version ? ` (${lang.version})` : '';
console.log(` ${chalk.green('•')} ${lang.name}${version}`);
}
console.log();
}
// Frameworks
if (stack.frameworks.length > 0) {
console.log(chalk.bold('Frameworks:'));
for (const fw of stack.frameworks) {
const version = fw.version ? ` (${fw.version})` : '';
console.log(` ${chalk.green('•')} ${fw.name}${version}`);
}
console.log();
}
// Libraries
if (stack.libraries.length > 0) {
console.log(chalk.bold('Libraries:'));
for (const lib of stack.libraries) {
const version = lib.version ? ` (${lib.version})` : '';
console.log(` ${chalk.green('•')} ${lib.name}${version}`);
}
console.log();
}
// Styling
if (stack.styling.length > 0) {
console.log(chalk.bold('Styling:'));
for (const style of stack.styling) {
console.log(` ${chalk.green('•')} ${style.name}`);
}
console.log();
}
// Testing
if (stack.testing.length > 0) {
console.log(chalk.bold('Testing:'));
for (const test of stack.testing) {
console.log(` ${chalk.green('•')} ${test.name}`);
}
console.log();
}
// Databases
if (stack.databases.length > 0) {
console.log(chalk.bold('Databases:'));
for (const db of stack.databases) {
console.log(` ${chalk.green('•')} ${db.name}`);
}
console.log();
}
// Tools
if (stack.tools.length > 0) {
console.log(chalk.bold('Tools:'));
for (const tool of stack.tools) {
console.log(` ${chalk.green('•')} ${tool.name}`);
}
console.log();
}
// Tags
if (tags.length > 0) {
console.log(chalk.bold('Recommended skill tags:'));
console.log(` ${chalk.cyan(tags.join(', '))}`);
console.log();
}
if (this.json) {
console.log(chalk.gray('\nJSON:'));
console.log(JSON.stringify(stack, null, 2));
}
return 0;
}
/**
* List detected agents
*/
private async listAgents(): Promise<number> {
const sync = createContextSync(process.cwd());
const detected = sync.detectAgents();
const status = sync.checkStatus();
const adapters = getAllAdapters();
console.log(chalk.bold('\nAgent Status:\n'));
for (const [agent, info] of Object.entries(status)) {
const adapter = adapters.find(a => a.type === agent);
const name = adapter?.name || agent;
const isDetected = detected.includes(agent as AgentType);
const statusIcon = info.hasSkills ? chalk.green('●') : isDetected ? chalk.yellow('○') : chalk.gray('○');
const skillInfo = info.skillCount > 0 ? chalk.gray(` (${info.skillCount} skills)`) : '';
console.log(` ${statusIcon} ${name.padEnd(20)} ${chalk.gray(agent)}${skillInfo}`);
if (this.verbose && info.skills.length > 0) {
for (const skill of info.skills) {
console.log(chalk.gray(` └─ ${skill}`));
}
}
}
console.log();
console.log(chalk.gray('Legend: ● has skills, ○ detected/configured, ○ not detected'));
console.log();
return 0;
}
/**
* Print context summary
*/
private printContextSummary(context: ProjectContext): void {
console.log(chalk.bold('Project:'));
console.log(` Name: ${chalk.cyan(context.project.name)}`);
if (context.project.type) {
console.log(` Type: ${context.project.type}`);
}
if (context.project.description) {
console.log(` Description: ${context.project.description}`);
}
// Stack summary
const stackItems: string[] = [];
if (context.stack.languages.length > 0) {
stackItems.push(`${context.stack.languages.length} languages`);
}
if (context.stack.frameworks.length > 0) {
stackItems.push(`${context.stack.frameworks.length} frameworks`);
}
if (context.stack.libraries.length > 0) {
stackItems.push(`${context.stack.libraries.length} libraries`);
}
if (context.stack.databases.length > 0) {
stackItems.push(`${context.stack.databases.length} databases`);
}
if (stackItems.length > 0) {
console.log(`\n${chalk.bold('Stack:')} ${stackItems.join(', ')}`);
// Show top items
const topFrameworks = context.stack.frameworks.slice(0, 3).map(f => f.name);
if (topFrameworks.length > 0) {
console.log(` Frameworks: ${chalk.cyan(topFrameworks.join(', '))}`);
}
const topLibs = context.stack.libraries.slice(0, 3).map(l => l.name);
if (topLibs.length > 0) {
console.log(` Libraries: ${chalk.cyan(topLibs.join(', '))}`);
}
}
// Skills summary
if (context.skills) {
console.log(`\n${chalk.bold('Skills:')}`);
console.log(` Installed: ${context.skills.installed?.length || 0}`);
console.log(` Auto-sync: ${context.skills.autoSync ? 'enabled' : 'disabled'}`);
}
// Agents summary
if (context.agents) {
console.log(`\n${chalk.bold('Agents:')}`);
if (context.agents.primary) {
console.log(` Primary: ${chalk.cyan(context.agents.primary)}`);
}
if (context.agents.synced?.length) {
console.log(` Synced: ${context.agents.synced.join(', ')}`);
}
}
}
}
+130
View File
@@ -0,0 +1,130 @@
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
export class CreateCommand extends Command {
static override paths = [['create'], ['new']];
static override usage = Command.Usage({
description: 'Create a new skill with proper structure',
examples: [
['Create a new skill', '$0 create my-skill'],
['Create with all optional directories', '$0 create my-skill --full'],
['Create with scripts directory', '$0 create my-skill --scripts'],
],
});
name = Option.String({ required: true, name: 'skill-name' });
full = Option.Boolean('--full,-f', false, {
description: 'Include all optional directories (references, scripts, assets)',
});
scripts = Option.Boolean('--scripts', false, {
description: 'Include scripts directory',
});
references = Option.Boolean('--references', false, {
description: 'Include references directory',
});
assets = Option.Boolean('--assets', false, {
description: 'Include assets directory',
});
directory = Option.String('--dir,-d', {
description: 'Parent directory to create skill in (default: current directory)',
});
async execute(): Promise<number> {
const skillName = this.name.toLowerCase();
if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(skillName)) {
console.error(chalk.red('Invalid skill name'));
console.error(chalk.dim('Must be lowercase alphanumeric with hyphens (e.g., my-skill)'));
return 1;
}
const parentDir = this.directory || process.cwd();
const skillDir = join(parentDir, skillName);
if (existsSync(skillDir)) {
console.error(chalk.red(`Directory already exists: ${skillDir}`));
return 1;
}
try {
mkdirSync(skillDir, { recursive: true });
const skillMd = generateSkillMd(skillName);
writeFileSync(join(skillDir, 'SKILL.md'), skillMd);
if (this.full || this.references) {
const refsDir = join(skillDir, 'references');
mkdirSync(refsDir);
writeFileSync(join(refsDir, '.gitkeep'), '');
}
if (this.full || this.scripts) {
const scriptsDir = join(skillDir, 'scripts');
mkdirSync(scriptsDir);
writeFileSync(join(scriptsDir, '.gitkeep'), '');
}
if (this.full || this.assets) {
const assetsDir = join(skillDir, 'assets');
mkdirSync(assetsDir);
writeFileSync(join(assetsDir, '.gitkeep'), '');
}
console.log(chalk.green(`Created skill: ${skillName}`));
console.log();
console.log(chalk.dim('Structure:'));
console.log(chalk.dim(` ${skillDir}/`));
console.log(chalk.dim(' ├── SKILL.md'));
if (this.full || this.references) console.log(chalk.dim(' ├── references/'));
if (this.full || this.scripts) console.log(chalk.dim(' ├── scripts/'));
if (this.full || this.assets) console.log(chalk.dim(' └── assets/'));
console.log();
console.log(chalk.cyan('Next steps:'));
console.log(chalk.dim(' 1. Edit SKILL.md with your instructions'));
console.log(chalk.dim(' 2. Validate: skillkit validate ' + skillDir));
console.log(chalk.dim(' 3. Test: skillkit read ' + skillName));
return 0;
} catch (error) {
console.error(chalk.red('Failed to create skill'));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
return 1;
}
}
}
function generateSkillMd(name: string): string {
const title = name
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
return `---
name: ${name}
description: Describe what this skill does and when to use it. Include trigger keywords.
---
# ${title}
Instructions for the AI agent on how to use this skill.
## When to Use
- Scenario 1
- Scenario 2
## Steps
1. First step
2. Second step
3. Third step
`;
}
+106
View File
@@ -0,0 +1,106 @@
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { setSkillEnabled, findSkill } from '@skillkit/core';
import { getSearchDirs } from '../helpers.js';
export class EnableCommand extends Command {
static override paths = [['enable']];
static override usage = Command.Usage({
description: 'Enable one or more skills',
examples: [
['Enable a skill', '$0 enable pdf'],
['Enable multiple skills', '$0 enable pdf xlsx docx'],
],
});
skills = Option.Rest({ required: 1 });
async execute(): Promise<number> {
const searchDirs = getSearchDirs();
let success = 0;
let failed = 0;
for (const skillName of this.skills) {
const skill = findSkill(skillName, searchDirs);
if (!skill) {
console.log(chalk.red(`Skill not found: ${skillName}`));
failed++;
continue;
}
if (skill.enabled) {
console.log(chalk.dim(`Already enabled: ${skillName}`));
continue;
}
const result = setSkillEnabled(skill.path, true);
if (result) {
console.log(chalk.green(`Enabled: ${skillName}`));
success++;
} else {
console.log(chalk.red(`Failed to enable: ${skillName}`));
failed++;
}
}
if (success > 0) {
console.log(chalk.dim('\nRun `skillkit sync` to update your agent config'));
}
return failed > 0 ? 1 : 0;
}
}
export class DisableCommand extends Command {
static override paths = [['disable']];
static override usage = Command.Usage({
description: 'Disable one or more skills',
examples: [
['Disable a skill', '$0 disable pdf'],
['Disable multiple skills', '$0 disable pdf xlsx docx'],
],
});
skills = Option.Rest({ required: 1 });
async execute(): Promise<number> {
const searchDirs = getSearchDirs();
let success = 0;
let failed = 0;
for (const skillName of this.skills) {
const skill = findSkill(skillName, searchDirs);
if (!skill) {
console.log(chalk.red(`Skill not found: ${skillName}`));
failed++;
continue;
}
if (!skill.enabled) {
console.log(chalk.dim(`Already disabled: ${skillName}`));
continue;
}
const result = setSkillEnabled(skill.path, false);
if (result) {
console.log(chalk.yellow(`Disabled: ${skillName}`));
success++;
} else {
console.log(chalk.red(`Failed to disable: ${skillName}`));
failed++;
}
}
if (success > 0) {
console.log(chalk.dim('\nRun `skillkit sync` to update your agent config'));
}
return failed > 0 ? 1 : 0;
}
}
+23
View File
@@ -0,0 +1,23 @@
// Command exports
export { ListCommand } from './list.js';
export { ReadCommand } from './read.js';
export { SyncCommand } from './sync.js';
export { InitCommand } from './init.js';
export { EnableCommand, DisableCommand } from './enable.js';
export { RemoveCommand } from './remove.js';
export { InstallCommand } from './install.js';
export { UpdateCommand } from './update.js';
export { ValidateCommand } from './validate.js';
export { CreateCommand } from './create.js';
export { UICommand } from './ui.js';
export { TranslateCommand } from './translate.js';
export { ContextCommand } from './context.js';
export { RecommendCommand } from './recommend.js';
export { StatusCommand } from './status.js';
export { PauseCommand } from './pause.js';
export { ResumeCommand } from './resume.js';
export { WorkflowRunCommand, WorkflowListCommand, WorkflowCreateCommand } from './workflow/index.js';
export { RunCommand } from './run.js';
export { TestCommand } from './test.js';
export { MarketplaceCommand } from './marketplace.js';
export { MemoryCommand } from './memory.js';
+79
View File
@@ -0,0 +1,79 @@
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import type { AgentType } from '@skillkit/core';
import { detectAgent, getAdapter, getAllAdapters } from '@skillkit/agents';
import { initProject } from '../helpers.js';
export class InitCommand extends Command {
static override paths = [['init']];
static override usage = Command.Usage({
description: 'Initialize skillkit in a project',
examples: [
['Auto-detect agent and initialize', '$0 init'],
['Initialize for specific agent', '$0 init --agent cursor'],
['List supported agents', '$0 init --list'],
],
});
agent = Option.String('--agent,-a', {
description: 'Target agent type',
});
list = Option.Boolean('--list,-l', false, {
description: 'List supported agents',
});
async execute(): Promise<number> {
if (this.list) {
console.log(chalk.cyan('Supported agents:\n'));
const adapters = getAllAdapters();
for (const adapter of adapters) {
console.log(` ${chalk.green(adapter.type)}`);
console.log(` Name: ${adapter.name}`);
console.log(` Skills dir: ${adapter.skillsDir}`);
console.log(` Config file: ${adapter.configFile}`);
console.log();
}
return 0;
}
try {
let agentType: AgentType;
if (this.agent) {
agentType = this.agent as AgentType;
} else {
console.log(chalk.dim('Auto-detecting agent...'));
agentType = await detectAgent();
}
const adapter = getAdapter(agentType);
console.log(chalk.cyan(`Initializing for ${adapter.name}...`));
await initProject(agentType);
console.log();
console.log(chalk.green('Initialized successfully!'));
console.log();
console.log(chalk.dim('Created:'));
console.log(chalk.dim(` - ${adapter.skillsDir}/ (skills directory)`));
console.log(chalk.dim(` - skillkit.yaml (config file)`));
console.log(chalk.dim(` - ${adapter.configFile} (agent config)`));
console.log();
console.log(chalk.cyan('Next steps:'));
console.log(chalk.dim(' 1. Install skills: skillkit install owner/repo'));
console.log(chalk.dim(' 2. Sync config: skillkit sync'));
console.log(chalk.dim(' 3. Use skills: skillkit read <skill-name>'));
return 0;
} catch (error) {
console.error(chalk.red('Initialization failed'));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
return 1;
}
}
}
+248
View File
@@ -0,0 +1,248 @@
import { existsSync, mkdirSync, cpSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import chalk from 'chalk';
import ora from 'ora';
import { Command, Option } from 'clipanion';
import { detectProvider, isLocalPath, getProvider } from '@skillkit/core';
import type { SkillMetadata, GitProvider, AgentType } from '@skillkit/core';
import { isPathInside } from '@skillkit/core';
import { getAdapter, detectAgent } from '@skillkit/agents';
import { getInstallDir, saveSkillMetadata } from '../helpers.js';
export class InstallCommand extends Command {
static override paths = [['install'], ['i']];
static override usage = Command.Usage({
description: 'Install skills from GitHub, GitLab, Bitbucket, or local path',
examples: [
['Install from GitHub', '$0 install owner/repo'],
['Install from GitLab', '$0 install gitlab:owner/repo'],
['Install from Bitbucket', '$0 install bitbucket:owner/repo'],
['Install specific skills (CI/CD)', '$0 install owner/repo --skills=pdf,xlsx'],
['Install all skills non-interactively', '$0 install owner/repo --all'],
['Install from local path', '$0 install ./my-skills'],
['Install globally', '$0 install owner/repo --global'],
['List available skills', '$0 install owner/repo --list'],
['Install to specific agents', '$0 install owner/repo --agent claude-code --agent cursor'],
],
});
source = Option.String({ required: true });
skills = Option.String('--skills,-s', {
description: 'Comma-separated list of skills to install (non-interactive)',
});
all = Option.Boolean('--all,-a', false, {
description: 'Install all discovered skills (non-interactive)',
});
yes = Option.Boolean('--yes,-y', false, {
description: 'Skip confirmation prompts',
});
global = Option.Boolean('--global,-g', false, {
description: 'Install to global skills directory',
});
force = Option.Boolean('--force,-f', false, {
description: 'Overwrite existing skills',
});
provider = Option.String('--provider,-p', {
description: 'Force specific provider (github, gitlab, bitbucket)',
});
list = Option.Boolean('--list,-l', false, {
description: 'List available skills without installing',
});
agent = Option.Array('--agent', {
description: 'Target specific agents (can specify multiple)',
});
async execute(): Promise<number> {
const spinner = ora();
try {
let providerAdapter = detectProvider(this.source);
if (this.provider) {
providerAdapter = getProvider(this.provider as GitProvider);
}
if (!providerAdapter) {
console.error(chalk.red(`Could not detect provider for: ${this.source}`));
console.error(chalk.dim('Use --provider flag or specify source as:'));
console.error(chalk.dim(' GitHub: owner/repo or https://github.com/owner/repo'));
console.error(chalk.dim(' GitLab: gitlab:owner/repo or https://gitlab.com/owner/repo'));
console.error(chalk.dim(' Bitbucket: bitbucket:owner/repo'));
console.error(chalk.dim(' Local: ./path or ~/path'));
return 1;
}
spinner.start(`Fetching from ${providerAdapter.name}...`);
const result = await providerAdapter.clone(this.source, '', { depth: 1 });
if (!result.success || !result.path) {
spinner.fail(chalk.red(result.error || 'Failed to fetch source'));
return 1;
}
spinner.succeed(`Found ${result.skills?.length || 0} skill(s)`);
const discoveredSkills = result.discoveredSkills || [];
if (this.list) {
if (discoveredSkills.length === 0) {
console.log(chalk.yellow('\nNo skills found in this repository'));
} else {
console.log(chalk.cyan('\nAvailable skills:\n'));
for (const skill of discoveredSkills) {
console.log(` ${chalk.green(skill.name)}`);
}
console.log();
console.log(chalk.dim(`Total: ${discoveredSkills.length} skill(s)`));
console.log(chalk.dim('\nTo install specific skills: skillkit install <source> --skills=skill1,skill2'));
console.log(chalk.dim('To install all skills: skillkit install <source> --all'));
}
const cleanupPath = result.tempRoot || result.path;
if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) {
rmSync(cleanupPath, { recursive: true, force: true });
}
return 0;
}
let skillsToInstall = discoveredSkills;
if (this.skills) {
const requestedSkills = this.skills.split(',').map(s => s.trim());
const available = discoveredSkills.map(s => s.name);
const notFound = requestedSkills.filter(s => !available.includes(s));
if (notFound.length > 0) {
console.error(chalk.red(`Skills not found: ${notFound.join(', ')}`));
console.error(chalk.dim(`Available: ${available.join(', ')}`));
return 1;
}
skillsToInstall = discoveredSkills.filter(s => requestedSkills.includes(s.name));
} else if (this.all || this.yes) {
skillsToInstall = discoveredSkills;
} else {
skillsToInstall = discoveredSkills;
if (skillsToInstall.length > 0) {
console.log(chalk.cyan('\nSkills to install:'));
skillsToInstall.forEach(s => console.log(chalk.dim(` - ${s.name}`)));
console.log();
}
}
if (skillsToInstall.length === 0) {
console.log(chalk.yellow('No skills to install'));
return 0;
}
let targetAgents: AgentType[];
if (this.agent && this.agent.length > 0) {
targetAgents = this.agent as AgentType[];
} else {
const detectedAgent = await detectAgent();
targetAgents = [detectedAgent];
}
let totalInstalled = 0;
const installResults: { agent: string; dir: string; count: number }[] = [];
for (const agentType of targetAgents) {
const adapter = getAdapter(agentType);
const installDir = getInstallDir(this.global, agentType);
if (!existsSync(installDir)) {
mkdirSync(installDir, { recursive: true });
}
if (targetAgents.length > 1) {
console.log(chalk.cyan(`\nInstalling to ${adapter.name}...`));
}
let installed = 0;
for (const skill of skillsToInstall) {
const skillName = skill.name;
const sourcePath = skill.path;
const targetPath = join(installDir, skillName);
if (existsSync(targetPath) && !this.force) {
console.log(chalk.yellow(` Skipping ${skillName} (already exists, use --force to overwrite)`));
continue;
}
const securityRoot = result.tempRoot || result.path;
if (!isPathInside(sourcePath, securityRoot)) {
console.log(chalk.red(` Skipping ${skillName} (path traversal detected)`));
continue;
}
spinner.start(`Installing ${skillName}...`);
try {
if (existsSync(targetPath)) {
rmSync(targetPath, { recursive: true, force: true });
}
cpSync(sourcePath, targetPath, { recursive: true, dereference: true });
const metadata: SkillMetadata = {
name: skillName,
description: '',
source: this.source,
sourceType: providerAdapter.type,
subpath: skillName,
installedAt: new Date().toISOString(),
enabled: true,
};
saveSkillMetadata(targetPath, metadata);
spinner.succeed(chalk.green(`Installed ${skillName}`));
installed++;
} catch (error) {
spinner.fail(chalk.red(`Failed to install ${skillName}`));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
}
}
totalInstalled += installed;
installResults.push({ agent: adapter.name, dir: installDir, count: installed });
}
const cleanupPath = result.tempRoot || result.path;
if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) {
rmSync(cleanupPath, { recursive: true, force: true });
}
console.log();
if (targetAgents.length > 1) {
console.log(chalk.green(`Installed ${totalInstalled} skill(s) across ${targetAgents.length} agents:`));
for (const r of installResults) {
console.log(chalk.dim(` - ${r.agent}: ${r.count} skill(s) to ${r.dir}`));
}
} else {
console.log(chalk.green(`Installed ${totalInstalled} skill(s) to ${installResults[0]?.dir}`));
}
if (!this.yes) {
console.log(chalk.dim('\nRun `skillkit sync` to update your agent config'));
}
return 0;
} catch (error) {
spinner.fail(chalk.red('Installation failed'));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
return 1;
}
}
}
+107
View File
@@ -0,0 +1,107 @@
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { findAllSkills } from '@skillkit/core';
import { getSearchDirs } from '../helpers.js';
export class ListCommand extends Command {
static override paths = [['list'], ['ls'], ['l']];
static override usage = Command.Usage({
description: 'List all installed skills',
examples: [
['List all skills', '$0 list'],
['Show only enabled skills', '$0 list --enabled'],
['Show JSON output', '$0 list --json'],
],
});
enabled = Option.Boolean('--enabled,-e', false, {
description: 'Show only enabled skills',
});
disabled = Option.Boolean('--disabled,-d', false, {
description: 'Show only disabled skills',
});
json = Option.Boolean('--json,-j', false, {
description: 'Output as JSON',
});
async execute(): Promise<number> {
const searchDirs = getSearchDirs();
let skills = findAllSkills(searchDirs);
if (this.enabled) {
skills = skills.filter(s => s.enabled);
} else if (this.disabled) {
skills = skills.filter(s => !s.enabled);
}
skills.sort((a, b) => {
if (a.location !== b.location) {
return a.location === 'project' ? -1 : 1;
}
return a.name.localeCompare(b.name);
});
if (this.json) {
console.log(JSON.stringify(skills, null, 2));
return 0;
}
if (skills.length === 0) {
console.log(chalk.yellow('No skills installed'));
console.log(chalk.dim('Install skills with: skillkit install <source>'));
return 0;
}
console.log(chalk.cyan(`Installed skills (${skills.length}):\n`));
const projectSkills = skills.filter(s => s.location === 'project');
const globalSkills = skills.filter(s => s.location === 'global');
if (projectSkills.length > 0) {
console.log(chalk.blue('Project skills:'));
for (const skill of projectSkills) {
printSkill(skill);
}
console.log();
}
if (globalSkills.length > 0) {
console.log(chalk.dim('Global skills:'));
for (const skill of globalSkills) {
printSkill(skill);
}
console.log();
}
const enabledCount = skills.filter(s => s.enabled).length;
const disabledCount = skills.length - enabledCount;
console.log(
chalk.dim(
`${projectSkills.length} project, ${globalSkills.length} global` +
(disabledCount > 0 ? `, ${disabledCount} disabled` : '')
)
);
return 0;
}
}
function printSkill(skill: { name: string; description: string; enabled: boolean; location: string }) {
const status = skill.enabled ? chalk.green('✓') : chalk.red('○');
const name = skill.enabled ? skill.name : chalk.dim(skill.name);
const desc = chalk.dim(truncate(skill.description, 50));
console.log(` ${status} ${name}`);
if (skill.description) {
console.log(` ${desc}`);
}
}
function truncate(str: string, maxLen: number): string {
if (str.length <= maxLen) return str;
return str.slice(0, maxLen - 3) + '...';
}
+250
View File
@@ -0,0 +1,250 @@
import { Command, Option } from 'clipanion';
import chalk from 'chalk';
import ora from 'ora';
import {
createMarketplaceAggregator,
type MarketplaceSearchOptions,
} from '@skillkit/core';
/**
* Marketplace command - browse and install skills from the marketplace
*/
export class MarketplaceCommand extends Command {
static override paths = [['marketplace'], ['market'], ['mp']];
static override usage = Command.Usage({
description: 'Browse and install skills from the marketplace',
details: `
The marketplace command lets you discover and install skills
from curated repositories.
Skills are aggregated from multiple sources including:
- composioHQ/awesome-claude-code-skills
- anthropics/courses
- User-added custom sources
`,
examples: [
['Browse marketplace', '$0 marketplace'],
['Search for skills', '$0 marketplace search typescript'],
['Refresh marketplace index', '$0 marketplace refresh'],
['Show popular tags', '$0 marketplace tags'],
['List sources', '$0 marketplace sources'],
],
});
action = Option.String({ required: false });
query = Option.String({ required: false });
limit = Option.String('--limit,-l', {
description: 'Limit results',
});
tags = Option.String('--tags,-t', {
description: 'Filter by tags (comma-separated)',
});
source = Option.String('--source,-s', {
description: 'Filter by source',
});
json = Option.Boolean('--json,-j', false, {
description: 'Output as JSON',
});
async execute(): Promise<number> {
const marketplace = createMarketplaceAggregator();
switch (this.action) {
case 'search':
return this.searchSkills(marketplace);
case 'refresh':
return this.refreshIndex(marketplace);
case 'tags':
return this.showTags(marketplace);
case 'sources':
return this.showSources(marketplace);
default:
// Default: browse/search
if (this.query || this.action) {
return this.searchSkills(marketplace);
}
return this.browseMarketplace(marketplace);
}
}
private async browseMarketplace(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
const spinner = ora('Loading marketplace...').start();
try {
const index = await marketplace.getIndex();
spinner.stop();
if (this.json) {
console.log(JSON.stringify({
totalSkills: index.totalCount,
sources: index.sources.length,
updatedAt: index.updatedAt,
}));
return 0;
}
console.log(chalk.bold('Skill Marketplace\n'));
console.log(`Total skills: ${chalk.cyan(index.totalCount)}`);
console.log(`Sources: ${chalk.cyan(index.sources.length)}`);
console.log(`Last updated: ${chalk.dim(new Date(index.updatedAt).toLocaleString())}\n`);
// Show sample skills
console.log(chalk.bold('Featured Skills:\n'));
const featured = index.skills.slice(0, 10);
for (const skill of featured) {
console.log(` ${chalk.cyan(skill.name)}`);
if (skill.description) {
console.log(` ${chalk.dim(skill.description.slice(0, 60))}${skill.description.length > 60 ? '...' : ''}`);
}
console.log(` ${chalk.dim(`Source: ${skill.source.name}`)}`);
console.log();
}
console.log(chalk.dim('Use "skillkit marketplace search <query>" to search for skills.'));
console.log(chalk.dim('Use "skillkit marketplace tags" to see popular tags.'));
return 0;
} catch (error) {
spinner.fail('Failed to load marketplace');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
return 1;
}
}
private async searchSkills(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
const query = this.query || this.action;
// Validate and parse limit
let limit = 20;
if (this.limit) {
const parsed = parseInt(this.limit, 10);
if (isNaN(parsed) || parsed <= 0) {
console.error(chalk.red('Invalid --limit value. Must be a positive number.'));
return 1;
}
limit = parsed;
}
// Sanitize tags - filter out empty strings
const tags = this.tags
?.split(',')
.map((t) => t.trim())
.filter((t) => t.length > 0);
const spinner = ora(`Searching for "${query}"...`).start();
try {
const options: MarketplaceSearchOptions = {
query: query || undefined,
limit,
tags: tags && tags.length > 0 ? tags : undefined,
source: this.source,
};
const result = await marketplace.search(options);
spinner.stop();
if (this.json) {
console.log(JSON.stringify(result));
return 0;
}
if (result.skills.length === 0) {
console.log(chalk.yellow(`No skills found${query ? ` matching "${query}"` : ''}.`));
return 0;
}
console.log(chalk.bold(`Found ${result.total} skill(s):\n`));
for (const skill of result.skills) {
console.log(`${chalk.cyan(skill.name)} ${chalk.dim(`(${skill.source.name})`)}`);
if (skill.description) {
console.log(` ${skill.description}`);
}
if (skill.tags.length > 0) {
console.log(` Tags: ${chalk.dim(skill.tags.join(', '))}`);
}
console.log();
}
if (result.total > result.skills.length) {
console.log(chalk.dim(`Showing ${result.skills.length} of ${result.total} results. Use --limit to see more.`));
}
return 0;
} catch (error) {
spinner.fail('Search failed');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
return 1;
}
}
private async refreshIndex(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
const spinner = ora('Refreshing marketplace index...').start();
try {
const index = await marketplace.refresh();
spinner.succeed(`Marketplace refreshed: ${index.totalCount} skills from ${index.sources.length} sources`);
return 0;
} catch (error) {
spinner.fail('Refresh failed');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
return 1;
}
}
private async showTags(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
const spinner = ora('Loading tags...').start();
try {
const tags = await marketplace.getPopularTags(30);
spinner.stop();
if (this.json) {
console.log(JSON.stringify(tags));
return 0;
}
console.log(chalk.bold('Popular Tags:\n'));
for (const { tag, count } of tags) {
const bar = '█'.repeat(Math.min(count, 20));
console.log(` ${tag.padEnd(15)} ${chalk.cyan(bar)} ${count}`);
}
return 0;
} catch (error) {
spinner.fail('Failed to load tags');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
return 1;
}
}
private async showSources(marketplace: ReturnType<typeof createMarketplaceAggregator>): Promise<number> {
const sources = marketplace.getSources();
if (this.json) {
console.log(JSON.stringify(sources));
return 0;
}
console.log(chalk.bold('Skill Sources:\n'));
for (const source of sources) {
console.log(`${chalk.cyan(source.name)} ${source.official ? chalk.green('(official)') : ''}`);
console.log(` ${chalk.dim(`${source.owner}/${source.repo}`)}`);
if (source.description) {
console.log(` ${source.description}`);
}
console.log();
}
return 0;
}
}
+872
View File
@@ -0,0 +1,872 @@
import { Command, Option } from 'clipanion';
import chalk from 'chalk';
import {
ObservationStore,
LearningStore,
getMemoryPaths,
initializeMemoryDirectory,
getMemoryStatus,
createMemoryCompressor,
createMemoryInjector,
type Learning,
} from '@skillkit/core';
/**
* Memory command - manage session memory across AI agents
*/
export class MemoryCommand extends Command {
static override paths = [['memory'], ['mem']];
static override usage = Command.Usage({
description: 'Manage session memory across AI coding agents',
details: `
The memory command helps you view, search, and manage learnings
captured from coding sessions across all AI agents.
Subcommands:
- status: Show current memory status
- search: Search memories by query
- list: List all learnings
- show: Show a specific learning
- compress: Compress observations into learnings
- export: Export a learning as a skill
- import: Import memories from another project
- clear: Clear session observations
- add: Manually add a learning
- rate: Rate a learning's effectiveness
- config: Configure memory settings
`,
examples: [
['Show memory status', '$0 memory status'],
['Search memories', '$0 memory search "authentication"'],
['Search global memories', '$0 memory search --global "react hooks"'],
['List project learnings', '$0 memory list'],
['List global learnings', '$0 memory list --global'],
['Show a learning', '$0 memory show <id>'],
['Compress observations', '$0 memory compress'],
['Export as skill', '$0 memory export <id> --name my-skill'],
['Clear session', '$0 memory clear'],
['Add manual learning', '$0 memory add --title "..." --content "..."'],
['Rate effectiveness', '$0 memory rate <id> 85'],
],
});
// Subcommand (status, search, list, show, compress, export, import, clear, add, rate, config)
action = Option.String({ required: false });
// Second argument (query for search, id for show/export/rate)
arg = Option.String({ required: false });
// Third argument (rating value for rate command)
ratingArg = Option.String({ required: false });
// Global scope
global = Option.Boolean('--global,-g', false, {
description: 'Use global memories instead of project',
});
// Tags filter
tags = Option.String('--tags,-t', {
description: 'Filter by tags (comma-separated)',
});
// Limit results
limit = Option.String('--limit,-l', {
description: 'Maximum number of results',
});
// Title for add
title = Option.String('--title', {
description: 'Title for new learning',
});
// Content for add
content = Option.String('--content,-c', {
description: 'Content for new learning',
});
// Name for export
name = Option.String('--name,-n', {
description: 'Name for exported skill',
});
// Output file
output = Option.String('--output,-o', {
description: 'Output file path',
});
// Input file
input = Option.String('--input,-i', {
description: 'Input file path',
});
// Keep learnings when clearing
keepLearnings = Option.Boolean('--keep-learnings', false, {
description: 'Keep learnings when clearing',
});
// Dry run
dryRun = Option.Boolean('--dry-run', false, {
description: 'Preview without making changes',
});
// JSON output
json = Option.Boolean('--json,-j', false, {
description: 'Output in JSON format',
});
// Verbose output
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed output',
});
async execute(): Promise<number> {
const action = this.action || 'status';
switch (action) {
case 'status':
return this.showStatus();
case 'search':
return this.searchMemories();
case 'list':
return this.listLearnings();
case 'show':
return this.showLearning();
case 'compress':
return this.compressObservations();
case 'export':
return this.exportLearning();
case 'import':
return this.importMemories();
case 'clear':
return this.clearMemory();
case 'add':
return this.addLearning();
case 'rate':
return this.rateLearning();
case 'config':
return this.showConfig();
default:
console.error(chalk.red(`Unknown action: ${action}`));
console.log(chalk.gray('Available actions: status, search, list, show, compress, export, import, clear, add, rate, config'));
return 1;
}
}
/**
* Show memory status
*/
private async showStatus(): Promise<number> {
const projectPath = process.cwd();
const status = getMemoryStatus(projectPath);
const paths = getMemoryPaths(projectPath);
// Get counts from stores
const observationStore = new ObservationStore(projectPath);
const projectLearningStore = new LearningStore('project', projectPath);
const globalLearningStore = new LearningStore('global');
const sessionObservations = status.hasObservations ? observationStore.count() : 0;
const projectLearnings = status.hasLearnings ? projectLearningStore.count() : 0;
const globalLearnings = status.hasGlobalLearnings ? globalLearningStore.count() : 0;
const sessionId = status.hasObservations ? observationStore.getSessionId() : null;
if (this.json) {
console.log(JSON.stringify({
...status,
sessionObservations,
projectLearnings,
globalLearnings,
sessionId,
paths,
}, null, 2));
return 0;
}
console.log(chalk.bold('\nMemory Status\n'));
// Session observations
console.log(chalk.cyan('Session:'));
console.log(` Observations: ${sessionObservations}`);
if (sessionId) {
console.log(` Session ID: ${chalk.gray(sessionId.slice(0, 8))}`);
}
console.log();
// Project learnings
console.log(chalk.cyan('Project:'));
console.log(` Learnings: ${projectLearnings}`);
console.log(` Path: ${chalk.gray(status.projectMemoryExists ? paths.projectMemoryDir : 'Not initialized')}`);
console.log();
// Global learnings
console.log(chalk.cyan('Global:'));
console.log(` Learnings: ${globalLearnings}`);
console.log(` Path: ${chalk.gray(status.globalMemoryExists ? paths.globalMemoryDir : 'Not initialized')}`);
console.log();
// Recommendations
if (sessionObservations >= 50) {
console.log(chalk.yellow('💡 You have many uncompressed observations. Consider running:'));
console.log(chalk.gray(' skillkit memory compress'));
}
return 0;
}
/**
* Search memories
*/
private async searchMemories(): Promise<number> {
const query = this.arg;
if (!query) {
console.error(chalk.red('Error: Search query is required'));
console.log(chalk.gray('Usage: skillkit memory search "your query"'));
return 1;
}
const projectPath = process.cwd();
const injector = createMemoryInjector(projectPath);
// Validate and parse limit
let maxLearnings = 10;
if (this.limit) {
const parsed = parseInt(this.limit, 10);
if (isNaN(parsed) || parsed <= 0) {
console.log(chalk.red('Invalid --limit value. Must be a positive number.'));
return 1;
}
maxLearnings = parsed;
}
// Sanitize tags - filter out empty strings
const tags = this.tags
?.split(',')
.map((t) => t.trim())
.filter((t) => t.length > 0);
const results = injector.search(query, {
includeGlobal: this.global,
tags: tags && tags.length > 0 ? tags : undefined,
maxLearnings,
minRelevance: 0,
});
if (this.json) {
console.log(JSON.stringify(results, null, 2));
return 0;
}
if (results.length === 0) {
console.log(chalk.yellow(`No memories found for: "${query}"`));
return 0;
}
console.log(chalk.bold(`\nFound ${results.length} memories:\n`));
for (const { learning, relevanceScore, matchedBy } of results) {
console.log(`${chalk.cyan('●')} ${chalk.bold(learning.title)}`);
console.log(` ID: ${chalk.gray(learning.id.slice(0, 8))}`);
console.log(` Relevance: ${this.formatScore(relevanceScore)}%`);
console.log(` Tags: ${learning.tags.join(', ')}`);
console.log(` Scope: ${learning.scope}`);
if (this.verbose) {
console.log(` Matched: ${this.formatMatchedBy(matchedBy)}`);
console.log(` Created: ${new Date(learning.createdAt).toLocaleDateString()}`);
console.log(` Uses: ${learning.useCount}`);
}
// Show excerpt
const excerpt = learning.content.slice(0, 100);
console.log(` ${chalk.gray(excerpt)}${learning.content.length > 100 ? '...' : ''}`);
console.log();
}
return 0;
}
/**
* List all learnings
*/
private async listLearnings(): Promise<number> {
const projectPath = process.cwd();
const store = new LearningStore(
this.global ? 'global' : 'project',
this.global ? undefined : projectPath
);
let learnings = store.getAll();
// Filter by tags if specified
if (this.tags) {
const tagList = this.tags.split(',').map((t) => t.trim().toLowerCase());
learnings = learnings.filter((l) =>
l.tags.some((t) => tagList.includes(t.toLowerCase()))
);
}
// Limit results
const limit = this.limit ? parseInt(this.limit, 10) : learnings.length;
learnings = learnings.slice(0, limit);
if (this.json) {
console.log(JSON.stringify(learnings, null, 2));
return 0;
}
const scope = this.global ? 'Global' : 'Project';
console.log(chalk.bold(`\n${scope} Learnings (${learnings.length}):\n`));
if (learnings.length === 0) {
console.log(chalk.gray('No learnings found.'));
console.log(chalk.gray('\nCapture learnings by running skills or add manually:'));
console.log(chalk.gray(' skillkit memory add --title "..." --content "..."'));
return 0;
}
for (const learning of learnings) {
const effectiveness = learning.effectiveness !== undefined
? ` [${this.formatScore(learning.effectiveness)}%]`
: '';
console.log(`${chalk.cyan('●')} ${learning.title}${chalk.green(effectiveness)}`);
console.log(` ${chalk.gray(learning.id.slice(0, 8))} | ${learning.tags.join(', ')} | ${learning.useCount} uses`);
if (this.verbose) {
const excerpt = learning.content.slice(0, 80);
console.log(` ${chalk.gray(excerpt)}${learning.content.length > 80 ? '...' : ''}`);
}
}
console.log();
return 0;
}
/**
* Show a specific learning
*/
private async showLearning(): Promise<number> {
const id = this.arg;
if (!id) {
console.error(chalk.red('Error: Learning ID is required'));
console.log(chalk.gray('Usage: skillkit memory show <id>'));
return 1;
}
const projectPath = process.cwd();
// Try project store first
let learning = new LearningStore('project', projectPath).getById(id);
// Try global store
if (!learning) {
learning = new LearningStore('global').getById(id);
}
// Try matching by prefix
if (!learning) {
const projectLearnings = new LearningStore('project', projectPath).getAll();
const globalLearnings = new LearningStore('global').getAll();
const all = [...projectLearnings, ...globalLearnings];
learning = all.find((l) => l.id.startsWith(id));
}
if (!learning) {
console.error(chalk.red(`Learning not found: ${id}`));
return 1;
}
if (this.json) {
console.log(JSON.stringify(learning, null, 2));
return 0;
}
console.log(chalk.bold(`\n${learning.title}\n`));
console.log(chalk.gray(`ID: ${learning.id}`));
console.log(chalk.gray(`Scope: ${learning.scope}`));
console.log(chalk.gray(`Source: ${learning.source}`));
console.log(chalk.gray(`Tags: ${learning.tags.join(', ')}`));
if (learning.frameworks?.length) {
console.log(chalk.gray(`Frameworks: ${learning.frameworks.join(', ')}`));
}
if (learning.patterns?.length) {
console.log(chalk.gray(`Patterns: ${learning.patterns.join(', ')}`));
}
console.log(chalk.gray(`Created: ${new Date(learning.createdAt).toLocaleString()}`));
console.log(chalk.gray(`Updated: ${new Date(learning.updatedAt).toLocaleString()}`));
console.log(chalk.gray(`Uses: ${learning.useCount}`));
if (learning.effectiveness !== undefined) {
console.log(chalk.gray(`Effectiveness: ${this.formatScore(learning.effectiveness)}%`));
}
console.log(chalk.bold('\nContent:\n'));
console.log(learning.content);
console.log();
return 0;
}
/**
* Compress observations into learnings
*/
private async compressObservations(): Promise<number> {
const projectPath = process.cwd();
// Initialize memory directory if needed
initializeMemoryDirectory(projectPath);
const observationStore = new ObservationStore(projectPath);
const observations = observationStore.getAll();
if (observations.length === 0) {
console.log(chalk.yellow('No observations to compress.'));
return 0;
}
console.log(chalk.cyan(`Found ${observations.length} observations to compress...\n`));
const compressor = createMemoryCompressor(projectPath);
const compressionOptions = {
minObservations: 2,
additionalTags: this.tags?.split(',').map((t) => t.trim()),
};
if (this.dryRun) {
console.log(chalk.gray('(Dry run - no changes will be made)\n'));
// For dry-run, only compress without storing
const result = await compressor.compress(observations, compressionOptions);
console.log(chalk.green(`✓ Would compress ${result.stats.inputCount} observations into ${result.stats.outputCount} learnings\n`));
if (result.learnings.length > 0) {
console.log(chalk.bold('Learnings that would be created:'));
for (const learning of result.learnings) {
console.log(` ${chalk.cyan('●')} ${learning.title}`);
console.log(` Tags: ${learning.tags.join(', ')}`);
}
console.log();
}
return 0;
}
// Actual compression with storage
const { learnings, result } = await compressor.compressAndStore(observations, compressionOptions);
console.log(chalk.green(`✓ Compressed ${result.stats.inputCount} observations into ${result.stats.outputCount} learnings\n`));
if (learnings.length > 0) {
console.log(chalk.bold('New Learnings:'));
for (const learning of learnings) {
console.log(` ${chalk.cyan('●')} ${learning.title}`);
console.log(` Tags: ${learning.tags.join(', ')}`);
}
console.log();
}
if (result.processedObservationIds.length > 0) {
// Remove processed observations
const deleted = observationStore.deleteMany(result.processedObservationIds);
console.log(chalk.gray(`Cleared ${deleted} processed observations.`));
}
return 0;
}
/**
* Export a learning as a skill
*/
private async exportLearning(): Promise<number> {
const id = this.arg;
if (!id) {
console.error(chalk.red('Error: Learning ID is required'));
console.log(chalk.gray('Usage: skillkit memory export <id> --name my-skill'));
return 1;
}
const projectPath = process.cwd();
// Find the learning
let learning = new LearningStore('project', projectPath).getById(id);
if (!learning) {
learning = new LearningStore('global').getById(id);
}
// Try matching by prefix
if (!learning) {
const projectLearnings = new LearningStore('project', projectPath).getAll();
const globalLearnings = new LearningStore('global').getAll();
const all = [...projectLearnings, ...globalLearnings];
learning = all.find((l) => l.id.startsWith(id));
}
if (!learning) {
console.error(chalk.red(`Learning not found: ${id}`));
return 1;
}
// Generate skill name
const skillName = this.name || this.slugify(learning.title);
// Generate skill content
const skillContent = this.generateSkillContent(learning, skillName);
if (this.dryRun) {
console.log(chalk.gray('(Dry run preview)\n'));
console.log(skillContent);
return 0;
}
// Determine output path
const outputPath = this.output || `.skillkit/exports/${skillName}/SKILL.md`;
const { dirname } = await import('node:path');
const { existsSync, mkdirSync, writeFileSync } = await import('node:fs');
const outputDir = dirname(outputPath);
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
writeFileSync(outputPath, skillContent, 'utf-8');
console.log(chalk.green(`✓ Exported learning as skill: ${skillName}`));
console.log(chalk.gray(` Path: ${outputPath}`));
return 0;
}
/**
* Import memories from another project
*/
private async importMemories(): Promise<number> {
const inputPath = this.input || this.arg;
if (!inputPath) {
console.error(chalk.red('Error: Input path is required'));
console.log(chalk.gray('Usage: skillkit memory import --input <path>'));
return 1;
}
const { existsSync, readFileSync } = await import('node:fs');
const { resolve } = await import('node:path');
const fullPath = resolve(inputPath);
if (!existsSync(fullPath)) {
console.error(chalk.red(`File not found: ${fullPath}`));
return 1;
}
const projectPath = process.cwd();
const store = new LearningStore(
this.global ? 'global' : 'project',
this.global ? undefined : projectPath
);
try {
const content = readFileSync(fullPath, 'utf-8');
const { parse: parseYaml } = await import('yaml');
const data = parseYaml(content) as { learnings?: Learning[] };
if (!data.learnings || !Array.isArray(data.learnings)) {
console.error(chalk.red('Invalid memory file format'));
return 1;
}
let imported = 0;
for (const learning of data.learnings) {
if (this.dryRun) {
console.log(chalk.gray(`Would import: ${learning.title}`));
} else {
store.add({
source: 'imported',
title: learning.title,
content: learning.content,
// Default to empty arrays if not present in imported YAML
tags: Array.isArray(learning.tags) ? learning.tags : [],
frameworks: Array.isArray(learning.frameworks) ? learning.frameworks : [],
patterns: Array.isArray(learning.patterns) ? learning.patterns : [],
});
imported++;
}
}
if (this.dryRun) {
console.log(chalk.gray(`\n(Dry run - ${data.learnings.length} learnings would be imported)`));
} else {
console.log(chalk.green(`✓ Imported ${imported} learnings`));
}
return 0;
} catch (error) {
console.error(chalk.red(`Import failed: ${error}`));
return 1;
}
}
/**
* Clear session observations
*/
private async clearMemory(): Promise<number> {
const projectPath = process.cwd();
if (this.dryRun) {
const observationStore = new ObservationStore(projectPath);
const learningStore = new LearningStore('project', projectPath);
console.log(chalk.gray('(Dry run preview)\n'));
console.log(`Would clear ${observationStore.count()} observations`);
if (!this.keepLearnings) {
console.log(`Would clear ${learningStore.count()} learnings`);
}
return 0;
}
const observationStore = new ObservationStore(projectPath);
observationStore.clear();
console.log(chalk.green('✓ Cleared session observations'));
if (!this.keepLearnings) {
const learningStore = new LearningStore('project', projectPath);
learningStore.clear();
console.log(chalk.green('✓ Cleared project learnings'));
}
return 0;
}
/**
* Add a manual learning
*/
private async addLearning(): Promise<number> {
if (!this.title) {
console.error(chalk.red('Error: --title is required'));
console.log(chalk.gray('Usage: skillkit memory add --title "..." --content "..."'));
return 1;
}
if (!this.content) {
console.error(chalk.red('Error: --content is required'));
console.log(chalk.gray('Usage: skillkit memory add --title "..." --content "..."'));
return 1;
}
const projectPath = process.cwd();
const store = new LearningStore(
this.global ? 'global' : 'project',
this.global ? undefined : projectPath
);
const tags = this.tags?.split(',').map((t) => t.trim()) || [];
const learning = store.add({
source: 'manual',
title: this.title,
content: this.content,
tags,
});
console.log(chalk.green(`✓ Added learning: ${learning.title}`));
console.log(chalk.gray(` ID: ${learning.id}`));
return 0;
}
/**
* Rate a learning's effectiveness
*/
private async rateLearning(): Promise<number> {
const id = this.arg;
if (!id) {
console.error(chalk.red('Error: Learning ID is required'));
console.log(chalk.gray('Usage: skillkit memory rate <id> <rating>'));
return 1;
}
const rating = parseInt(this.ratingArg || '0', 10);
if (isNaN(rating) || rating < 0 || rating > 100) {
console.error(chalk.red('Error: Rating must be 0-100'));
console.log(chalk.gray('Usage: skillkit memory rate <id> <rating>'));
return 1;
}
const projectPath = process.cwd();
// Try project store first
const projectStore = new LearningStore('project', projectPath);
let learning = projectStore.getById(id);
let store = projectStore;
if (!learning) {
const globalStore = new LearningStore('global');
learning = globalStore.getById(id);
store = globalStore;
}
// Try prefix match
if (!learning) {
const projectLearnings = projectStore.getAll();
const globalStore = new LearningStore('global');
const globalLearnings = globalStore.getAll();
learning = projectLearnings.find((l) => l.id.startsWith(id));
if (learning) {
store = projectStore;
} else {
learning = globalLearnings.find((l) => l.id.startsWith(id));
if (learning) {
store = globalStore;
}
}
}
if (!learning) {
console.error(chalk.red(`Learning not found: ${id}`));
return 1;
}
store.setEffectiveness(learning.id, rating);
console.log(chalk.green(`✓ Rated "${learning.title}" as ${rating}% effective`));
return 0;
}
/**
* Show memory configuration
*/
private async showConfig(): Promise<number> {
const projectPath = process.cwd();
const paths = getMemoryPaths(projectPath);
if (this.json) {
console.log(JSON.stringify(paths, null, 2));
return 0;
}
console.log(chalk.bold('\nMemory Configuration\n'));
console.log(chalk.cyan('Paths:'));
console.log(` Project observations: ${chalk.gray(paths.observationsFile)}`);
console.log(` Project learnings: ${chalk.gray(paths.learningsFile)}`);
console.log(` Project index: ${chalk.gray(paths.indexFile)}`);
console.log(` Global learnings: ${chalk.gray(paths.globalLearningsFile)}`);
console.log(` Global index: ${chalk.gray(paths.globalIndexFile)}`);
console.log();
return 0;
}
/**
* Format relevance/effectiveness score with color
*/
private formatScore(score: number): string {
if (score >= 80) return chalk.green(score.toString());
if (score >= 50) return chalk.yellow(score.toString());
return chalk.red(score.toString());
}
/**
* Format matched by info
*/
private formatMatchedBy(matchedBy: {
frameworks: string[];
tags: string[];
keywords: string[];
patterns: string[];
}): string {
const parts: string[] = [];
if (matchedBy.frameworks.length > 0) {
parts.push(`frameworks: ${matchedBy.frameworks.join(', ')}`);
}
if (matchedBy.tags.length > 0) {
parts.push(`tags: ${matchedBy.tags.join(', ')}`);
}
if (matchedBy.keywords.length > 0) {
parts.push(`keywords: ${matchedBy.keywords.slice(0, 3).join(', ')}`);
}
if (matchedBy.patterns.length > 0) {
parts.push(`patterns: ${matchedBy.patterns.join(', ')}`);
}
return parts.join(' | ') || 'general';
}
/**
* Convert title to slug
*/
private slugify(text: string): string {
return text
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 50);
}
/**
* Escape a YAML scalar value if it contains special characters
*/
private escapeYamlValue(value: string): string {
// Check if value needs quoting (contains special YAML characters)
if (/[:#\[\]{}|>&*!?,'"\\@`]/.test(value) || value.includes('\n')) {
// Use double quotes and escape internal quotes/backslashes
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
}
return value;
}
/**
* Generate skill content from learning
*/
private generateSkillContent(learning: Learning, skillName: string): string {
// Escape values that might contain special YAML characters
const escapedName = this.escapeYamlValue(skillName);
const escapedDesc = this.escapeYamlValue(learning.title);
const escapedTags = learning.tags.map((t) => this.escapeYamlValue(t));
const lines: string[] = [
'---',
`name: ${escapedName}`,
`description: ${escapedDesc}`,
`version: 1.0.0`,
`tags: [${escapedTags.join(', ')}]`,
`source: skillkit-memory`,
`sourceType: local`,
];
if (learning.frameworks?.length) {
const escapedFrameworks = learning.frameworks.map((f) => this.escapeYamlValue(f));
lines.push(`compatibility:`);
lines.push(` frameworks: [${escapedFrameworks.join(', ')}]`);
}
lines.push('---', '', `# ${learning.title}`, '');
if (learning.patterns?.length) {
lines.push(`## Patterns`, '');
for (const pattern of learning.patterns) {
lines.push(`- ${pattern}`);
}
lines.push('');
}
lines.push(`## Content`, '', learning.content, '');
lines.push(
'---',
'',
'*Exported from SkillKit session memory*',
`*Created: ${new Date(learning.createdAt).toLocaleDateString()}*`,
`*Uses: ${learning.useCount}*`
);
if (learning.effectiveness !== undefined) {
lines.push(`*Effectiveness: ${learning.effectiveness}%*`);
}
return lines.join('\n');
}
}
+71
View File
@@ -0,0 +1,71 @@
import { Command, Option } from 'clipanion';
import { resolve } from 'node:path';
import chalk from 'chalk';
import { SessionManager } from '@skillkit/core';
/**
* Pause command - pause current skill execution
*/
export class PauseCommand extends Command {
static override paths = [['pause']];
static override usage = Command.Usage({
description: 'Pause current skill execution for later resumption',
details: `
The pause command saves the current execution state so you can
continue later with "skillkit resume".
This is useful when you need to:
- Take a break from a long skill execution
- Handle an interruption
- Review progress before continuing
`,
examples: [
['Pause current execution', '$0 pause'],
],
});
// Project path
projectPath = Option.String('--path,-p', {
description: 'Project path (default: current directory)',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
const manager = new SessionManager(targetPath);
const state = manager.get();
if (!state) {
console.log(chalk.yellow('No active session found.'));
return 1;
}
if (!state.currentExecution) {
console.log(chalk.yellow('No skill execution in progress.'));
return 1;
}
if (state.currentExecution.status === 'paused') {
console.log(chalk.yellow('Execution is already paused.'));
console.log(chalk.dim('Resume with: skillkit resume'));
return 0;
}
const success = manager.pause();
if (success) {
const exec = state.currentExecution;
console.log(chalk.green('✓ Execution paused'));
console.log();
console.log(` Skill: ${chalk.bold(exec.skillName)}`);
console.log(` Progress: ${exec.currentStep}/${exec.totalSteps} tasks completed`);
console.log();
console.log(chalk.dim('Resume with: skillkit resume'));
console.log(chalk.dim('View status: skillkit status'));
return 0;
} else {
console.log(chalk.red('Failed to pause execution.'));
return 1;
}
}
}
+79
View File
@@ -0,0 +1,79 @@
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { findSkill, readSkillContent } from '@skillkit/core';
import { getSearchDirs } from '../helpers.js';
export class ReadCommand extends Command {
static override paths = [['read'], ['r']];
static override usage = Command.Usage({
description: 'Read skill content for AI agent consumption',
examples: [
['Read a single skill', '$0 read pdf'],
['Read multiple skills', '$0 read pdf,xlsx,docx'],
['Read with verbose output', '$0 read pdf --verbose'],
],
});
skills = Option.String({ required: true });
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show additional information',
});
async execute(): Promise<number> {
const searchDirs = getSearchDirs();
const skillNames = this.skills
.split(',')
.map(s => s.trim())
.filter(s => s.length > 0);
if (skillNames.length === 0) {
console.error(chalk.red('No skill names provided'));
return 1;
}
let exitCode = 0;
for (const skillName of skillNames) {
const skill = findSkill(skillName, searchDirs);
if (!skill) {
console.error(chalk.red(`Skill not found: ${skillName}`));
console.error(chalk.dim('Available directories:'));
searchDirs.forEach(d => console.error(chalk.dim(` - ${d}`)));
exitCode = 1;
continue;
}
if (!skill.enabled) {
console.error(chalk.yellow(`Skill disabled: ${skillName}`));
console.error(chalk.dim('Enable with: skillkit enable ' + skillName));
exitCode = 1;
continue;
}
const content = readSkillContent(skill.path);
if (!content) {
console.error(chalk.red(`Could not read SKILL.md for: ${skillName}`));
exitCode = 1;
continue;
}
console.log(`Reading: ${skillName}`);
console.log(`Base directory: ${skill.path}`);
console.log();
console.log(content);
console.log();
console.log(`Skill read: ${skillName}`);
if (skillNames.length > 1 && skillName !== skillNames[skillNames.length - 1]) {
console.log('\n---\n');
}
}
return exitCode;
}
}
+387
View File
@@ -0,0 +1,387 @@
import { Command, Option } from 'clipanion';
import { resolve } from 'node:path';
import chalk from 'chalk';
import ora from 'ora';
import {
type ProjectProfile,
type ScoredSkill,
ContextManager,
RecommendationEngine,
buildSkillIndex,
saveIndex,
loadIndex as loadIndexFromCache,
isIndexStale,
INDEX_PATH,
KNOWN_SKILL_REPOS,
} from '@skillkit/core';
/**
* Recommend command - get smart skill recommendations based on project analysis
*/
export class RecommendCommand extends Command {
static override paths = [['recommend'], ['rec']];
static override usage = Command.Usage({
description: 'Get skill recommendations based on your project',
details: `
The recommend command analyzes your project and suggests skills that match
your technology stack, frameworks, and patterns.
It scores skills based on:
- Framework compatibility (React, Vue, Next.js, etc.)
- Language match (TypeScript, Python, etc.)
- Library alignment (Tailwind, Prisma, etc.)
- Tag relevance
- Popularity and quality metrics
Run "skillkit recommend --update" to refresh the skill index from known sources.
`,
examples: [
['Get recommendations', '$0 recommend'],
['Show top 5 recommendations', '$0 recommend --limit 5'],
['Filter by category', '$0 recommend --category security'],
['Show detailed reasons', '$0 recommend --verbose'],
['Update skill index', '$0 recommend --update'],
['Search for skills by task', '$0 recommend --task "authentication"'],
['Search for skills (alias)', '$0 recommend --search "testing"'],
],
});
// Limit number of results
limit = Option.String('--limit,-l', {
description: 'Maximum number of recommendations',
});
// Minimum score threshold
minScore = Option.String('--min-score', {
description: 'Minimum match score (0-100)',
});
// Filter by category/tag
category = Option.Array('--category,-c', {
description: 'Filter by category (can be used multiple times)',
});
// Verbose output with reasons
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed match reasons',
});
// Update index
update = Option.Boolean('--update,-u', false, {
description: 'Update skill index from sources',
});
// Search mode (--search or --task)
search = Option.String('--search,-s', {
description: 'Search skills by task/query',
});
// Task alias for search (GSD-style)
task = Option.String('--task,-t', {
description: 'Search skills by task (alias for --search)',
});
// Include installed skills
includeInstalled = Option.Boolean('--include-installed', false, {
description: 'Include already installed skills',
});
// JSON output
json = Option.Boolean('--json,-j', false, {
description: 'Output in JSON format',
});
// Project path
projectPath = Option.String('--path,-p', {
description: 'Project path (default: current directory)',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
// Handle index update
if (this.update) {
return await this.updateIndex();
}
// Load or create project profile
const profile = await this.getProjectProfile(targetPath);
if (!profile) {
console.error(chalk.red('Failed to analyze project'));
return 1;
}
// Load skill index
const index = this.loadIndex();
if (!index || index.skills.length === 0) {
console.log(chalk.yellow('No skill index found.'));
console.log(chalk.dim('Run "skillkit recommend --update" to fetch skills from known sources.'));
console.log(chalk.dim('Or install skills manually with "skillkit install <source>"\n'));
// Still show project profile
this.showProjectProfile(profile);
return 0;
}
// Create recommendation engine
const engine = new RecommendationEngine();
engine.loadIndex(index);
// Handle search mode (--search or --task)
const searchQuery = this.search || this.task;
if (searchQuery) {
return this.handleSearch(engine, searchQuery);
}
// Get recommendations
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,
});
// Output results
if (this.json) {
console.log(JSON.stringify(result, null, 2));
return 0;
}
this.displayRecommendations(result.recommendations, profile, result.totalSkillsScanned);
return 0;
}
/**
* Get project profile from context or by analyzing project
*/
private async getProjectProfile(projectPath: string): Promise<ProjectProfile | null> {
const manager = new ContextManager(projectPath);
let context = manager.get();
if (!context) {
// Auto-analyze project
if (!this.json) {
console.log(chalk.dim('Analyzing project...\n'));
}
context = manager.init();
}
if (!context) {
return null;
}
// Convert ProjectContext to ProjectProfile
return {
name: context.project.name,
type: context.project.type,
stack: context.stack,
patterns: context.patterns,
installedSkills: context.skills?.installed || [],
excludedSkills: context.skills?.excluded || [],
};
}
/**
* Show project profile summary
*/
private showProjectProfile(profile: ProjectProfile): void {
console.log(chalk.cyan('Project Profile:'));
console.log(` Name: ${chalk.bold(profile.name)}`);
if (profile.type) {
console.log(` Type: ${profile.type}`);
}
const stackItems: string[] = [];
for (const lang of profile.stack.languages) {
stackItems.push(`${lang.name}${lang.version ? ` ${lang.version}` : ''}`);
}
for (const fw of profile.stack.frameworks) {
stackItems.push(`${fw.name}${fw.version ? ` ${fw.version}` : ''}`);
}
if (stackItems.length > 0) {
console.log(` Stack: ${chalk.dim(stackItems.join(', '))}`);
}
console.log();
}
/**
* Display recommendations
*/
private displayRecommendations(
recommendations: ScoredSkill[],
profile: ProjectProfile,
totalScanned: number
): void {
// Show project profile
this.showProjectProfile(profile);
if (recommendations.length === 0) {
console.log(chalk.yellow('No matching skills found.'));
console.log(chalk.dim('Try lowering the minimum score with --min-score'));
return;
}
console.log(chalk.cyan(`Recommended Skills (${recommendations.length} of ${totalScanned} scanned):\n`));
for (const rec of recommendations) {
const scoreColor = rec.score >= 70 ? chalk.green : rec.score >= 50 ? chalk.yellow : chalk.dim;
const scoreBar = this.getScoreBar(rec.score);
console.log(` ${scoreColor(`${rec.score}%`)} ${scoreBar} ${chalk.bold(rec.skill.name)}`);
if (rec.skill.description) {
console.log(` ${chalk.dim(truncate(rec.skill.description, 70))}`);
}
if (rec.skill.source) {
console.log(` ${chalk.dim('Source:')} ${rec.skill.source}`);
}
if (this.verbose && rec.reasons.length > 0) {
console.log(chalk.dim(' Reasons:'));
for (const reason of rec.reasons.filter(r => r.weight > 0)) {
console.log(` ${chalk.dim('•')} ${reason.description} (+${reason.weight})`);
}
}
if (rec.warnings.length > 0) {
for (const warning of rec.warnings) {
console.log(` ${chalk.yellow('⚠')} ${warning}`);
}
}
console.log();
}
console.log(chalk.dim('Install with: skillkit install <source>'));
}
/**
* Generate a visual score bar
*/
private getScoreBar(score: number): string {
const filled = Math.round(score / 10);
const empty = 10 - filled;
return chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty));
}
/**
* Handle search mode
*/
private handleSearch(engine: RecommendationEngine, query: string): number {
const results = engine.search({
query,
limit: this.limit ? parseInt(this.limit, 10) : 10,
semantic: true,
filters: {
minScore: this.minScore ? parseInt(this.minScore, 10) : undefined,
},
});
if (this.json) {
console.log(JSON.stringify(results, null, 2));
return 0;
}
if (results.length === 0) {
console.log(chalk.yellow(`No skills found matching "${query}"`));
return 0;
}
console.log(chalk.cyan(`Search results for "${query}" (${results.length} found):\n`));
for (const result of results) {
const relevanceColor =
result.relevance >= 70 ? chalk.green : result.relevance >= 50 ? chalk.yellow : chalk.dim;
console.log(` ${relevanceColor(`${result.relevance}%`)} ${chalk.bold(result.skill.name)}`);
if (result.snippet) {
console.log(` ${chalk.dim(result.snippet)}`);
}
if (result.matchedTerms.length > 0) {
console.log(` ${chalk.dim('Matched:')} ${result.matchedTerms.join(', ')}`);
}
console.log();
}
return 0;
}
/**
* Load skill index from cache
*/
private loadIndex() {
const index = loadIndexFromCache();
if (!index) {
return null;
}
// Check if index is stale
if (isIndexStale(index) && !this.json) {
const lastUpdated = new Date(index.lastUpdated);
const hoursSinceUpdate = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60);
console.log(
chalk.dim(`Index is ${Math.round(hoursSinceUpdate)} hours old. Run --update to refresh.\n`)
);
}
return index;
}
/**
* Update skill index from sources
*/
private async updateIndex(): Promise<number> {
console.log(chalk.cyan('Updating skill index from GitHub repositories...\n'));
console.log(chalk.dim(`Sources: ${KNOWN_SKILL_REPOS.map(r => `${r.owner}/${r.repo}`).join(', ')}\n`));
const spinner = ora('Fetching skills...').start();
try {
const { index, errors } = await buildSkillIndex(KNOWN_SKILL_REPOS, (message) => {
spinner.text = message;
});
spinner.stop();
// Report any errors
if (errors.length > 0) {
console.log(chalk.yellow('\nWarnings:'));
for (const error of errors) {
console.log(chalk.dim(` • ${error}`));
}
console.log();
}
// Save the index
saveIndex(index);
console.log(chalk.green(`✓ Updated index with ${index.skills.length} skills`));
if (index.sources.length > 0) {
console.log(chalk.dim(` Sources: ${index.sources.map((s) => s.name).join(', ')}`));
}
console.log(chalk.dim(` Saved to: ${INDEX_PATH}\n`));
return 0;
} catch (error) {
spinner.fail('Failed to update index');
console.error(chalk.red(error instanceof Error ? error.message : String(error)));
return 1;
}
}
}
/**
* Truncate string to max length
*/
function truncate(str: string, maxLen: number): string {
if (str.length <= maxLen) return str;
return str.slice(0, maxLen - 3) + '...';
}
+60
View File
@@ -0,0 +1,60 @@
import { existsSync, rmSync } from 'node:fs';
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { findSkill } from '@skillkit/core';
import { getSearchDirs } from '../helpers.js';
export class RemoveCommand extends Command {
static override paths = [['remove'], ['rm'], ['uninstall']];
static override usage = Command.Usage({
description: 'Remove installed skills',
examples: [
['Remove a skill', '$0 remove pdf'],
['Remove multiple skills', '$0 remove pdf xlsx docx'],
['Force removal without confirmation', '$0 remove pdf --force'],
],
});
skills = Option.Rest({ required: 1 });
force = Option.Boolean('--force,-f', false, {
description: 'Skip confirmation',
});
async execute(): Promise<number> {
const searchDirs = getSearchDirs();
let removed = 0;
let failed = 0;
for (const skillName of this.skills) {
const skill = findSkill(skillName, searchDirs);
if (!skill) {
console.log(chalk.yellow(`Skill not found: ${skillName}`));
continue;
}
if (!existsSync(skill.path)) {
console.log(chalk.yellow(`Path not found: ${skill.path}`));
continue;
}
try {
rmSync(skill.path, { recursive: true, force: true });
console.log(chalk.green(`Removed: ${skillName}`));
removed++;
} catch (error) {
console.log(chalk.red(`Failed to remove: ${skillName}`));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
failed++;
}
}
if (removed > 0) {
console.log(chalk.dim('\nRun `skillkit sync` to update your agent config'));
}
return failed > 0 ? 1 : 0;
}
}
+83
View File
@@ -0,0 +1,83 @@
import { Command, Option } from 'clipanion';
import { resolve } from 'node:path';
import chalk from 'chalk';
import { SessionManager } from '@skillkit/core';
/**
* Resume command - resume paused skill execution
*/
export class ResumeCommand extends Command {
static override paths = [['resume']];
static override usage = Command.Usage({
description: 'Resume a paused skill execution',
details: `
The resume command continues a previously paused skill execution
from where it left off.
The execution state is preserved, including:
- Completed tasks
- User decisions
- Modified files
`,
examples: [
['Resume paused execution', '$0 resume'],
],
});
// Project path
projectPath = Option.String('--path,-p', {
description: 'Project path (default: current directory)',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
const manager = new SessionManager(targetPath);
const state = manager.get();
if (!state) {
console.log(chalk.yellow('No active session found.'));
return 1;
}
if (!state.currentExecution) {
console.log(chalk.yellow('No skill execution to resume.'));
console.log(chalk.dim('Start a new execution with: skillkit run <skill>'));
return 1;
}
if (state.currentExecution.status !== 'paused') {
if (state.currentExecution.status === 'running') {
console.log(chalk.yellow('Execution is already running.'));
} else {
console.log(chalk.yellow(`Execution is ${state.currentExecution.status}.`));
}
return 1;
}
const success = manager.resume();
if (success) {
const exec = state.currentExecution;
console.log(chalk.green('✓ Execution resumed'));
console.log();
console.log(` Skill: ${chalk.bold(exec.skillName)}`);
console.log(` Progress: ${exec.currentStep}/${exec.totalSteps} tasks`);
console.log();
// Show next task
const nextTask = exec.tasks.find((t) => t.status === 'pending' || t.status === 'in_progress');
if (nextTask) {
console.log(` Next task: ${chalk.cyan(nextTask.name)}`);
}
console.log();
console.log(chalk.dim('The execution will continue from where it left off.'));
console.log(chalk.dim('View status: skillkit status'));
return 0;
} else {
console.log(chalk.red('Failed to resume execution.'));
return 1;
}
}
}
+336
View File
@@ -0,0 +1,336 @@
import { Command, Option } from 'clipanion';
import { resolve, join } from 'node:path';
import { existsSync, readFileSync, statSync } from 'node:fs';
import chalk from 'chalk';
import ora from 'ora';
import {
createExecutionEngine,
discoverSkills,
extractFrontmatter,
type ExecutableSkill,
type ExecutableTask,
type AgentType,
} from '@skillkit/core';
/**
* Run command - execute a skill
*/
export class RunCommand extends Command {
static override paths = [['run']];
static override usage = Command.Usage({
description: 'Execute a skill with task-based orchestration',
details: `
The run command executes a skill, optionally breaking it down into
tasks with verification checkpoints.
Skills can be:
- Installed skills (by name)
- Local skill files (by path)
- Remote skills (owner/repo/path)
`,
examples: [
['Run an installed skill', '$0 run typescript-strict-mode'],
['Run a local skill file', '$0 run ./my-skill/SKILL.md'],
['Dry run (show what would happen)', '$0 run typescript-strict-mode --dry-run'],
['Run with verification', '$0 run setup-testing --verify'],
],
});
// Skill name or path
skillRef = Option.String({ required: true });
// Target agent
agent = Option.String('--agent,-a', {
description: 'Target agent (claude-code, cursor, etc.)',
});
// Dry run
dryRun = Option.Boolean('--dry-run,-n', false, {
description: 'Show what would be executed without running',
});
// Enable verification
verify = Option.Boolean('--verify', false, {
description: 'Run verification checks after each task',
});
// Auto-commit
autoCommit = Option.Boolean('--auto-commit', false, {
description: 'Create git commits after each task',
});
// Continue on error
continueOnError = Option.Boolean('--continue-on-error', false, {
description: 'Continue execution even if a task fails',
});
// Verbose output
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed execution progress',
});
// JSON output
json = Option.Boolean('--json,-j', false, {
description: 'Output in JSON format',
});
// Project path
projectPath = Option.String('--path,-p', {
description: 'Project path (default: current directory)',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
// Load the skill
const skill = await this.loadSkill(targetPath);
if (!skill) {
return 1;
}
// Show skill info
if (!this.json) {
console.log(chalk.cyan(`Executing skill: ${chalk.bold(skill.name)}`));
if (skill.description) {
console.log(chalk.dim(skill.description));
}
console.log();
}
// Dry run mode
if (this.dryRun) {
this.showDryRun(skill);
return 0;
}
const spinner = ora();
let currentTask = '';
// Create execution engine
const engine = createExecutionEngine(targetPath, {
onProgress: (event) => {
if (this.json) return;
switch (event.type) {
case 'task_start':
currentTask = event.taskName || '';
spinner.start(`Task ${(event.taskIndex || 0) + 1}/${event.totalTasks}: ${currentTask}`);
break;
case 'task_complete':
const icon = event.status === 'completed' ? chalk.green('✓') : chalk.red('✗');
spinner.stopAndPersist({
symbol: icon,
text: `Task ${(event.taskIndex || 0) + 1}/${event.totalTasks}: ${currentTask}`,
});
if (event.error && this.verbose) {
console.log(chalk.red(` Error: ${event.error}`));
}
break;
case 'checkpoint':
spinner.info(`Checkpoint: ${event.message}`);
break;
case 'verification':
if (this.verbose) {
console.log(chalk.dim(` ${event.message}`));
}
break;
case 'complete':
console.log();
if (event.status === 'completed') {
console.log(chalk.green('✓ Skill execution completed'));
} else {
console.log(chalk.red(`✗ Skill execution ${event.status}`));
if (event.error) {
console.log(chalk.red(` Error: ${event.error}`));
}
}
break;
}
},
checkpointHandler: async (task, _context) => {
// For CLI, we auto-continue but could add interactive prompts
if (task.type === 'checkpoint:decision' && task.options) {
// Use first option by default
return {
continue: true,
selectedOption: task.options[0],
};
}
return { continue: true };
},
});
// Execute the skill
const result = await engine.execute(skill, {
agent: this.agent as AgentType | undefined,
autoCommit: this.autoCommit,
verify: this.verify,
continueOnError: this.continueOnError,
});
if (this.json) {
console.log(JSON.stringify(result, null, 2));
} else {
// Show summary
console.log();
console.log(chalk.cyan('Summary:'));
console.log(` Duration: ${chalk.dim(this.formatDuration(result.durationMs || 0))}`);
console.log(` Tasks: ${chalk.dim(`${result.tasks.filter(t => t.status === 'completed').length}/${result.tasks.length} completed`)}`);
if (result.filesModified.length > 0) {
console.log(` Files modified: ${chalk.dim(result.filesModified.length.toString())}`);
}
if (result.commits.length > 0) {
console.log(` Commits: ${chalk.dim(result.commits.join(', '))}`);
}
}
return result.status === 'completed' ? 0 : 1;
}
private async loadSkill(projectPath: string): Promise<ExecutableSkill | null> {
// Check if it's a file path (must be a file, not directory)
if (this.skillRef.endsWith('.md') || (existsSync(this.skillRef) && statSync(this.skillRef).isFile())) {
return this.loadSkillFromFile(resolve(this.skillRef));
}
// Check installed skills
const skill = this.findInstalledSkill(projectPath, this.skillRef);
if (skill) {
return skill;
}
console.error(chalk.red(`Skill "${this.skillRef}" not found`));
console.log(chalk.dim('Install skills with: skillkit install <source>'));
return null;
}
private loadSkillFromFile(filePath: string): ExecutableSkill | null {
if (!existsSync(filePath)) {
console.error(chalk.red(`File not found: ${filePath}`));
return null;
}
try {
const content = readFileSync(filePath, 'utf-8');
const frontmatter = extractFrontmatter(content);
// Parse tasks from frontmatter if present
const tasks = this.parseTasksFromFrontmatter(frontmatter);
return {
name: (frontmatter?.name as string) || this.skillRef,
description: frontmatter?.description as string,
version: frontmatter?.version as string,
source: filePath,
content,
tasks,
};
} catch (error) {
console.error(chalk.red(`Failed to load skill: ${error}`));
return null;
}
}
private findInstalledSkill(projectPath: string, skillName: string): ExecutableSkill | null {
// Search in common skill directories
const skillDirs = [
join(projectPath, '.claude', 'skills'),
join(projectPath, '.cursor', 'skills'),
join(projectPath, 'skills'),
join(projectPath, '.skillkit', 'skills'),
];
for (const dir of skillDirs) {
if (!existsSync(dir)) continue;
const skills = discoverSkills(dir);
const skill = skills.find((s) => s.name === skillName);
if (skill) {
const skillMdPath = join(skill.path, 'SKILL.md');
if (existsSync(skillMdPath)) {
return this.loadSkillFromFile(skillMdPath);
}
}
}
return null;
}
private parseTasksFromFrontmatter(frontmatter: Record<string, unknown> | null): ExecutableTask[] | undefined {
if (!frontmatter?.tasks || !Array.isArray(frontmatter.tasks)) {
return undefined;
}
return frontmatter.tasks.map((task: Record<string, unknown>, index: number) => ({
id: (task.id as string) || `task-${index}`,
name: (task.name as string) || `Task ${index + 1}`,
type: (task.type as ExecutableTask['type']) || 'auto',
action: (task.action as string) || '',
files: task.files as string[] | undefined,
options: task.options as string[] | undefined,
verify: task.verify as ExecutableTask['verify'],
}));
}
private showDryRun(skill: ExecutableSkill): void {
console.log(chalk.cyan('Dry Run - Execution Plan'));
console.log();
console.log(`Skill: ${chalk.bold(skill.name)}`);
if (skill.description) {
console.log(`Description: ${chalk.dim(skill.description)}`);
}
console.log(`Source: ${chalk.dim(skill.source)}`);
console.log();
if (skill.tasks && skill.tasks.length > 0) {
console.log(chalk.cyan('Tasks:'));
for (let i = 0; i < skill.tasks.length; i++) {
const task = skill.tasks[i];
const typeLabel = this.getTaskTypeLabel(task.type);
console.log(` ${i + 1}. ${task.name} ${typeLabel}`);
if (task.action) {
console.log(` ${chalk.dim(task.action)}`);
}
if (task.files && task.files.length > 0) {
console.log(` Files: ${chalk.dim(task.files.join(', '))}`);
}
}
} else {
console.log(chalk.dim('No structured tasks defined. Skill will be executed as a single unit.'));
}
console.log();
console.log(chalk.dim('This is a dry run. Remove --dry-run to execute.'));
}
private getTaskTypeLabel(type: string): string {
switch (type) {
case 'auto':
return chalk.green('[auto]');
case 'checkpoint:human-verify':
return chalk.yellow('[verify]');
case 'checkpoint:decision':
return chalk.blue('[decision]');
case 'checkpoint:human-action':
return chalk.magenta('[manual]');
default:
return '';
}
}
private formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`;
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
const minutes = Math.floor(ms / 60000);
const seconds = Math.floor((ms % 60000) / 1000);
return `${minutes}m ${seconds}s`;
}
}
+174
View File
@@ -0,0 +1,174 @@
import { Command, Option } from 'clipanion';
import { resolve } from 'node:path';
import chalk from 'chalk';
import { SessionManager } from '@skillkit/core';
/**
* Status command - show current session state
*/
export class StatusCommand extends Command {
static override paths = [['status'], ['st']];
static override usage = Command.Usage({
description: 'Show current session state and execution progress',
details: `
The status command shows the current state of skill execution sessions,
including any paused executions and recent history.
`,
examples: [
['Show session status', '$0 status'],
['Show with history', '$0 status --history'],
['Show JSON output', '$0 status --json'],
],
});
// Show history
history = Option.Boolean('--history,-h', false, {
description: 'Show execution history',
});
// History limit
limit = Option.String('--limit,-l', {
description: 'Limit history entries (default: 10)',
});
// JSON output
json = Option.Boolean('--json,-j', false, {
description: 'Output in JSON format',
});
// Project path
projectPath = Option.String('--path,-p', {
description: 'Project path (default: current directory)',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
const manager = new SessionManager(targetPath);
const state = manager.get();
if (this.json) {
console.log(JSON.stringify(state || { message: 'No session found' }, null, 2));
return 0;
}
if (!state) {
console.log(chalk.dim('No active session found.'));
console.log(chalk.dim('Run a skill with "skillkit run <skill>" to start a session.'));
return 0;
}
// Show current execution
if (state.currentExecution) {
const exec = state.currentExecution;
const statusColor = exec.status === 'paused' ? chalk.yellow : chalk.green;
console.log(chalk.cyan('Current Execution:\n'));
console.log(` Skill: ${chalk.bold(exec.skillName)}`);
console.log(` Source: ${chalk.dim(exec.skillSource)}`);
console.log(` Status: ${statusColor(exec.status)}`);
console.log(` Progress: ${exec.currentStep}/${exec.totalSteps} tasks`);
console.log(` Started: ${chalk.dim(new Date(exec.startedAt).toLocaleString())}`);
if (exec.pausedAt) {
console.log(` Paused: ${chalk.dim(new Date(exec.pausedAt).toLocaleString())}`);
}
console.log(chalk.cyan('\n Tasks:'));
for (const task of exec.tasks) {
const statusIcon = this.getStatusIcon(task.status);
const statusText = this.getStatusColor(task.status)(task.status);
console.log(` ${statusIcon} ${task.name} - ${statusText}`);
if (task.error) {
console.log(` ${chalk.red('Error:')} ${task.error}`);
}
}
if (exec.status === 'paused') {
console.log(chalk.yellow('\n Resume with: skillkit resume'));
}
} else {
console.log(chalk.dim('No active execution.'));
}
// Show history
if (this.history || (!state.currentExecution && state.history.length > 0)) {
const limit = this.limit ? parseInt(this.limit, 10) : 10;
const history = manager.getHistory(limit);
if (history.length > 0) {
console.log(chalk.cyan('\nExecution History:\n'));
for (const entry of history) {
const statusColor = entry.status === 'completed' ? chalk.green : chalk.red;
const duration = this.formatDuration(entry.durationMs);
console.log(` ${statusColor('●')} ${chalk.bold(entry.skillName)}`);
console.log(` ${chalk.dim(entry.skillSource)} • ${duration}`);
console.log(` ${chalk.dim(new Date(entry.completedAt).toLocaleString())}`);
if (entry.commits.length > 0) {
console.log(` Commits: ${chalk.dim(entry.commits.join(', '))}`);
}
if (entry.error) {
console.log(` ${chalk.red('Error:')} ${entry.error}`);
}
console.log();
}
}
}
// Show decisions
if (state.decisions.length > 0) {
console.log(chalk.cyan('Saved Decisions:\n'));
for (const decision of state.decisions.slice(0, 5)) {
console.log(` ${chalk.dim(decision.key)}: ${decision.value}`);
}
if (state.decisions.length > 5) {
console.log(chalk.dim(` ... and ${state.decisions.length - 5} more`));
}
}
return 0;
}
private getStatusIcon(status: string): string {
switch (status) {
case 'completed':
return chalk.green('✓');
case 'failed':
return chalk.red('✗');
case 'in_progress':
return chalk.blue('●');
case 'paused':
return chalk.yellow('⏸');
default:
return chalk.dim('○');
}
}
private getStatusColor(status: string): (text: string) => string {
switch (status) {
case 'completed':
return chalk.green;
case 'failed':
return chalk.red;
case 'in_progress':
return chalk.blue;
case 'paused':
return chalk.yellow;
default:
return chalk.dim;
}
}
private formatDuration(ms: number): string {
if (ms < 1000) return `${ms}ms`;
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
const minutes = Math.floor(ms / 60000);
const seconds = Math.floor((ms % 60000) / 1000);
return `${minutes}m ${seconds}s`;
}
}
+153
View File
@@ -0,0 +1,153 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { loadConfig, findAllSkills } from '@skillkit/core';
import type { AgentType } from '@skillkit/core';
import { getAdapter, detectAgent } from '@skillkit/agents';
import { getSearchDirs, getAgentConfigPath } from '../helpers.js';
export class SyncCommand extends Command {
static override paths = [['sync'], ['s']];
static override usage = Command.Usage({
description: 'Sync skills to agent configuration file',
examples: [
['Sync all enabled skills', '$0 sync'],
['Sync to specific file', '$0 sync --output AGENTS.md'],
['Sync for specific agent', '$0 sync --agent cursor'],
['Only sync enabled skills', '$0 sync --enabled-only'],
],
});
output = Option.String('--output,-o', {
description: 'Output file path (default: agent-specific config file)',
});
agent = Option.String('--agent,-a', {
description: 'Target agent type (claude-code, cursor, codex, etc.)',
});
enabledOnly = Option.Boolean('--enabled-only,-e', true, {
description: 'Only include enabled skills (default: true)',
});
yes = Option.Boolean('--yes,-y', false, {
description: 'Skip confirmation prompts',
});
async execute(): Promise<number> {
try {
let agentType: AgentType;
if (this.agent) {
agentType = this.agent as AgentType;
} else {
const config = loadConfig();
agentType = config.agent || (await detectAgent());
}
const adapter = getAdapter(agentType);
const outputPath = this.output || getAgentConfigPath(agentType);
const searchDirs = getSearchDirs(agentType);
let skills = findAllSkills(searchDirs);
if (this.enabledOnly) {
skills = skills.filter(s => s.enabled);
}
if (skills.length === 0) {
console.log(chalk.yellow('No skills found to sync'));
console.log(chalk.dim('Install skills with: skillkit install <source>'));
return 0;
}
console.log(chalk.cyan(`Syncing ${skills.length} skill(s) for ${adapter.name}:`));
skills.forEach(s => {
const status = s.enabled ? chalk.green('✓') : chalk.dim('○');
const location = s.location === 'project' ? chalk.blue('[project]') : chalk.dim('[global]');
console.log(` ${status} ${s.name} ${location}`);
});
console.log();
const config = adapter.generateConfig(skills);
if (!config) {
console.log(chalk.yellow('No configuration generated'));
return 0;
}
let existingContent = '';
if (existsSync(outputPath)) {
existingContent = readFileSync(outputPath, 'utf-8');
}
const newContent = updateConfigContent(existingContent, config, agentType);
const dir = dirname(outputPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
writeFileSync(outputPath, newContent, 'utf-8');
console.log(chalk.green(`Synced to ${outputPath}`));
console.log(chalk.dim(`Agent: ${adapter.name}`));
return 0;
} catch (error) {
console.error(chalk.red('Sync failed'));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
return 1;
}
}
}
function updateConfigContent(existing: string, newConfig: string, agentType: AgentType): string {
const markers: Record<string, { start: string; end: string }> = {
'claude-code': {
start: '<!-- SKILLS_TABLE_START -->',
end: '<!-- SKILLS_TABLE_END -->',
},
cursor: {
start: '<!-- SKILLS_DATA_START -->',
end: '<!-- SKILLS_DATA_END -->',
},
universal: {
start: '<!-- SKILLKIT_SKILLS_START -->',
end: '<!-- SKILLKIT_SKILLS_END -->',
},
};
const agentMarkers = markers[agentType] || markers.universal;
const startIdx = existing.indexOf(agentMarkers.start);
const endIdx = existing.indexOf(agentMarkers.end);
if (startIdx !== -1 && endIdx !== -1) {
return (
existing.slice(0, startIdx) +
newConfig.slice(newConfig.indexOf(agentMarkers.start)) +
existing.slice(endIdx + agentMarkers.end.length)
);
}
const genericStart = '<!-- SKILLKIT_SKILLS_START -->';
const genericEnd = '<!-- SKILLKIT_SKILLS_END -->';
const gStartIdx = existing.indexOf(genericStart);
const gEndIdx = existing.indexOf(genericEnd);
if (gStartIdx !== -1 && gEndIdx !== -1) {
return (
existing.slice(0, gStartIdx) + newConfig + existing.slice(gEndIdx + genericEnd.length)
);
}
if (existing.trim()) {
return existing + '\n\n' + newConfig;
}
return newConfig;
}
+288
View File
@@ -0,0 +1,288 @@
import { Command, Option } from 'clipanion';
import { resolve, join } from 'node:path';
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import chalk from 'chalk';
import {
runTestSuite,
createTestSuiteFromFrontmatter,
type SkillTestSuite,
type TestSuiteResult,
} from '@skillkit/core';
import { parse as parseYaml } from 'yaml';
/**
* Test command - run skill tests
*/
export class TestCommand extends Command {
static override paths = [['test']];
static override usage = Command.Usage({
description: 'Run skill tests',
details: `
The test command runs test cases defined in skill frontmatter.
Tests are defined in the skill's YAML frontmatter using the 'tests' key.
Example skill with tests:
\`\`\`yaml
---
name: my-skill
tests:
- name: "Creates config file"
assertions:
- type: file_exists
target: config.json
- name: "Types check"
assertions:
- type: type_check
---
\`\`\`
`,
examples: [
['Run all skill tests', '$0 test'],
['Run tests for a specific skill', '$0 test my-skill'],
['Run with verbose output', '$0 test --verbose'],
['Stop on first failure', '$0 test --bail'],
['Run tests with specific tags', '$0 test --tags unit,integration'],
],
});
skill = Option.String({ required: false });
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Verbose output',
});
bail = Option.Boolean('--bail,-b', false, {
description: 'Stop on first failure',
});
tags = Option.String('--tags,-t', {
description: 'Only run tests with these tags (comma-separated)',
});
skipTags = Option.String('--skip-tags', {
description: 'Skip tests with these tags (comma-separated)',
});
json = Option.Boolean('--json,-j', false, {
description: 'Output results as JSON',
});
projectPath = Option.String('--path,-p', {
description: 'Project path',
});
timeout = Option.String('--timeout', {
description: 'Test timeout in milliseconds',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
// Find skills to test
const skillFiles = this.findSkillFiles(targetPath);
if (skillFiles.length === 0) {
if (!this.json) {
console.log(chalk.yellow('No skills found with tests.'));
console.log(chalk.dim('Add tests to your skills using YAML frontmatter.'));
} else {
console.log(JSON.stringify({ results: [], passed: true, total: 0 }));
}
return 0;
}
// Filter by skill name if provided
const filesToTest = this.skill
? skillFiles.filter((f) => f.name.includes(this.skill!))
: skillFiles;
if (filesToTest.length === 0) {
if (!this.json) {
console.log(chalk.yellow(`No skills found matching "${this.skill}"`));
}
return 1;
}
if (!this.json) {
console.log(chalk.bold('Running skill tests...\n'));
}
// Parse tags
const tags = this.tags?.split(',').map((t) => t.trim());
const skipTags = this.skipTags?.split(',').map((t) => t.trim());
const timeout = this.timeout ? parseInt(this.timeout, 10) : undefined;
// Run tests for each skill
const results: TestSuiteResult[] = [];
let allPassed = true;
for (const file of filesToTest) {
const suite = this.parseSkillTests(file.path, file.name);
if (!suite || suite.tests.length === 0) {
continue;
}
if (!this.json) {
console.log(chalk.blue(`Testing: ${suite.skillName}`));
}
const result = await runTestSuite(suite, {
cwd: targetPath,
verbose: this.verbose,
bail: this.bail,
tags,
skipTags,
timeout,
onProgress: (event) => {
if (this.json || !this.verbose) return;
switch (event.type) {
case 'test_start':
console.log(chalk.dim(` Running: ${event.testName}`));
break;
case 'test_end':
if (event.passed) {
console.log(chalk.green(` ✓ ${event.testName}`));
} else {
console.log(chalk.red(` ✗ ${event.testName}`));
if (event.error) {
console.log(chalk.red(` ${event.error}`));
}
}
break;
case 'assertion_end':
if (this.verbose && !event.passed) {
console.log(chalk.red(` - ${event.assertionType}: ${event.error}`));
}
break;
}
},
});
results.push(result);
if (!result.passed) {
allPassed = false;
}
if (!this.json) {
const icon = result.passed ? chalk.green('✓') : chalk.red('✗');
const status = result.passed ? 'PASSED' : 'FAILED';
console.log(
`${icon} ${suite.skillName}: ${result.passedCount}/${result.tests.length} tests ${status} (${result.duration}ms)\n`
);
}
if (this.bail && !result.passed) {
break;
}
}
// Summary
if (this.json) {
console.log(
JSON.stringify({
results: results.map((r) => ({
skill: r.skillName,
passed: r.passed,
tests: r.passedCount,
failed: r.failedCount,
skipped: r.skippedCount,
duration: r.duration,
})),
passed: allPassed,
total: results.length,
})
);
} else {
const totalTests = results.reduce((acc, r) => acc + r.tests.length, 0);
const passedTests = results.reduce((acc, r) => acc + r.passedCount, 0);
const failedTests = results.reduce((acc, r) => acc + r.failedCount, 0);
const skippedTests = results.reduce((acc, r) => acc + r.skippedCount, 0);
console.log(chalk.bold('Summary:'));
console.log(` Skills tested: ${results.length}`);
console.log(` Total tests: ${totalTests}`);
console.log(chalk.green(` Passed: ${passedTests}`));
if (failedTests > 0) {
console.log(chalk.red(` Failed: ${failedTests}`));
}
if (skippedTests > 0) {
console.log(chalk.yellow(` Skipped: ${skippedTests}`));
}
if (allPassed) {
console.log(chalk.green('\n✓ All tests passed!'));
} else {
console.log(chalk.red('\n✗ Some tests failed.'));
}
}
return allPassed ? 0 : 1;
}
/**
* Find skill files with tests
*/
private findSkillFiles(projectPath: string): { name: string; path: string }[] {
const files: { name: string; path: string }[] = [];
// Check common skill directories
const skillDirs = [
'.claude/skills',
'.cursor/skills',
'.skillkit/skills',
'skills',
];
for (const dir of skillDirs) {
const fullDir = join(projectPath, dir);
if (!existsSync(fullDir)) continue;
try {
const entries = readdirSync(fullDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isFile() && (entry.name.endsWith('.md') || entry.name.endsWith('.mdc'))) {
files.push({
name: entry.name.replace(/\.(md|mdc)$/, ''),
path: join(fullDir, entry.name),
});
}
}
} catch {
// Directory not readable
}
}
return files;
}
/**
* Parse skill file for tests
*/
private parseSkillTests(filePath: string, skillName: string): SkillTestSuite | null {
try {
const content = readFileSync(filePath, 'utf-8');
// Extract frontmatter
const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
if (!frontmatterMatch) {
return null;
}
const frontmatter = parseYaml(frontmatterMatch[1]) as Record<string, unknown>;
if (!frontmatter.tests) {
return null;
}
return createTestSuiteFromFrontmatter(skillName, frontmatter);
} catch {
return null;
}
}
}
+410
View File
@@ -0,0 +1,410 @@
import { Command, Option } from 'clipanion';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join, basename, dirname } from 'node:path';
import chalk from 'chalk';
import {
type AgentType,
translateSkill,
translateSkillFile,
getSupportedTranslationAgents,
translatorRegistry,
findAllSkills,
} from '@skillkit/core';
import { getAdapter, getAllAdapters } from '@skillkit/agents';
import { getSearchDirs } from '../helpers.js';
/**
* Translate skills between different AI agent formats
*/
export class TranslateCommand extends Command {
static override paths = [['translate']];
static override usage = Command.Usage({
description: 'Translate skills between different AI agent formats',
details: `
This command translates skills from one AI agent format to another.
Supported formats:
- SKILL.md (Claude Code, Codex, Gemini CLI, and 10+ more)
- Cursor MDC (.mdc files with globs)
- Windsurf rules (.windsurfrules)
- GitHub Copilot instructions (copilot-instructions.md)
Translation is bidirectional - you can translate from any format to any other.
`,
examples: [
['Translate a skill to Cursor format', '$0 translate my-skill --to cursor'],
['Translate all skills to Windsurf', '$0 translate --all --to windsurf'],
['Translate a file directly', '$0 translate ./SKILL.md --to cursor --output ./my-skill.mdc'],
['List all supported agents', '$0 translate --list'],
['Preview translation without writing', '$0 translate my-skill --to cursor --dry-run'],
],
});
// Skill name or path
source = Option.String({ required: false });
// Target agent
to = Option.String('--to,-t', {
description: 'Target agent to translate to',
});
// Source agent (auto-detected if not specified)
from = Option.String('--from,-f', {
description: 'Source agent format (auto-detected if not specified)',
});
// Output path
output = Option.String('--output,-o', {
description: 'Output file path (default: agent skills directory)',
});
// Translate all installed skills
all = Option.Boolean('--all,-a', false, {
description: 'Translate all installed skills',
});
// Dry run (preview without writing)
dryRun = Option.Boolean('--dry-run,-n', false, {
description: 'Preview translation without writing files',
});
// Add metadata comments
metadata = Option.Boolean('--metadata,-m', false, {
description: 'Add translation metadata to output',
});
// Force overwrite
force = Option.Boolean('--force', false, {
description: 'Overwrite existing files',
});
// List supported agents
list = Option.Boolean('--list,-l', false, {
description: 'List all supported agents and formats',
});
// Show compatibility info
compat = Option.Boolean('--compat,-c', false, {
description: 'Show compatibility info between agents',
});
async execute(): Promise<number> {
// List supported agents
if (this.list) {
return this.listAgents();
}
// Show compatibility info
if (this.compat) {
return this.showCompatibility();
}
// Validate target agent
if (!this.to) {
console.error(chalk.red('Error: --to/-t target agent is required'));
console.log(chalk.gray('Use --list to see all supported agents'));
return 1;
}
const targetAgent = this.to as AgentType;
if (!getSupportedTranslationAgents().includes(targetAgent)) {
console.error(chalk.red(`Error: Unknown target agent "${this.to}"`));
console.log(chalk.gray('Use --list to see all supported agents'));
return 1;
}
// Translate all skills
if (this.all) {
return this.translateAll(targetAgent);
}
// Translate single skill
if (!this.source) {
console.error(chalk.red('Error: Please specify a skill name or path, or use --all'));
return 1;
}
return this.translateSingle(this.source, targetAgent);
}
/**
* List all supported agents and their formats
*/
private listAgents(): number {
console.log(chalk.bold('\nSupported Agents for Translation:\n'));
const agents = getSupportedTranslationAgents();
const adapters = getAllAdapters();
// Group by format
const byFormat: Record<string, AgentType[]> = {};
for (const agent of agents) {
const format = translatorRegistry.getFormatForAgent(agent);
if (!byFormat[format]) byFormat[format] = [];
byFormat[format].push(agent);
}
// Display by format
const formatNames: Record<string, string> = {
'skill-md': 'SKILL.md Format (Standard)',
'cursor-mdc': 'Cursor MDC Format',
'markdown-rules': 'Markdown Rules Format',
'external': 'External Systems',
};
for (const [format, formatAgents] of Object.entries(byFormat)) {
console.log(chalk.cyan(` ${formatNames[format] || format}:`));
for (const agent of formatAgents) {
const adapter = adapters.find(a => a.type === agent);
const name = adapter?.name || agent;
console.log(` ${chalk.green(agent.padEnd(16))} ${chalk.gray(name)}`);
}
console.log();
}
console.log(chalk.gray('All formats can translate to any other format.'));
console.log(chalk.gray('Use --compat to see compatibility details.\n'));
return 0;
}
/**
* Show compatibility between agents
*/
private showCompatibility(): number {
if (!this.from || !this.to) {
console.error(chalk.red('Error: Both --from and --to are required for compatibility check'));
return 1;
}
const fromAgent = this.from as AgentType;
const toAgent = this.to as AgentType;
const info = translatorRegistry.getCompatibilityInfo(fromAgent, toAgent);
console.log(chalk.bold(`\nTranslation: ${fromAgent} → ${toAgent}\n`));
if (info.supported) {
console.log(chalk.green(' ✓ Translation supported'));
} else {
console.log(chalk.red(' ✗ Translation not supported'));
return 1;
}
if (info.warnings.length > 0) {
console.log(chalk.yellow('\n Warnings:'));
for (const warning of info.warnings) {
console.log(chalk.yellow(` • ${warning}`));
}
}
if (info.lossyFields.length > 0) {
console.log(chalk.gray('\n Fields with reduced functionality:'));
for (const field of info.lossyFields) {
console.log(chalk.gray(` • ${field}`));
}
}
console.log();
return 0;
}
/**
* Translate all installed skills
*/
private async translateAll(targetAgent: AgentType): Promise<number> {
const searchDirs = getSearchDirs();
const skills = findAllSkills(searchDirs);
if (skills.length === 0) {
console.log(chalk.yellow('No skills found to translate'));
return 0;
}
console.log(chalk.bold(`\nTranslating ${skills.length} skill(s) to ${targetAgent}...\n`));
let success = 0;
let failed = 0;
for (const skill of skills) {
const skillMdPath = join(skill.path, 'SKILL.md');
if (!existsSync(skillMdPath)) {
console.log(chalk.yellow(` ⚠ ${skill.name}: No SKILL.md found`));
failed++;
continue;
}
const result = translateSkillFile(skillMdPath, targetAgent, {
addMetadata: this.metadata,
});
if (result.success) {
if (this.dryRun) {
console.log(chalk.green(` ✓ ${skill.name} → ${result.filename} (dry run)`));
if (result.warnings.length > 0) {
for (const warning of result.warnings) {
console.log(chalk.gray(` ${warning}`));
}
}
} else {
// Determine output path
const targetAdapter = getAdapter(targetAgent);
const outputDir = this.output || join(process.cwd(), targetAdapter.skillsDir, skill.name);
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
const outputPath = join(outputDir, result.filename);
if (existsSync(outputPath) && !this.force) {
console.log(chalk.yellow(` ⚠ ${skill.name}: ${outputPath} exists (use --force)`));
failed++;
continue;
}
writeFileSync(outputPath, result.content, 'utf-8');
console.log(chalk.green(` ✓ ${skill.name} → ${outputPath}`));
}
if (result.incompatible.length > 0) {
for (const item of result.incompatible) {
console.log(chalk.gray(` ⚠ ${item}`));
}
}
success++;
} else {
console.log(chalk.red(` ✗ ${skill.name}: Translation failed`));
for (const item of result.incompatible) {
console.log(chalk.red(` ${item}`));
}
failed++;
}
}
console.log();
console.log(chalk.bold(`Translated: ${success}, Failed: ${failed}`));
return failed > 0 ? 1 : 0;
}
/**
* Translate a single skill
*/
private async translateSingle(source: string, targetAgent: AgentType): Promise<number> {
let sourcePath: string;
let skillName: string;
// Check if source is a file path
if (existsSync(source)) {
sourcePath = source;
skillName = basename(dirname(source));
if (skillName === '.') {
skillName = basename(source).replace(/\.(md|mdc)$/i, '');
}
} else {
// Search for skill by name
const searchDirs = getSearchDirs();
let found = false;
for (const dir of searchDirs) {
const skillPath = join(dir, source);
const skillMdPath = join(skillPath, 'SKILL.md');
if (existsSync(skillMdPath)) {
sourcePath = skillMdPath;
skillName = source;
found = true;
break;
}
}
if (!found) {
console.error(chalk.red(`Error: Skill "${source}" not found`));
console.log(chalk.gray('Searched in:'));
for (const dir of searchDirs) {
console.log(chalk.gray(` ${dir}`));
}
return 1;
}
}
// Read and translate
const content = readFileSync(sourcePath!, 'utf-8');
const result = translateSkill(content, targetAgent, {
addMetadata: this.metadata,
sourceFilename: basename(sourcePath!),
});
if (!result.success) {
console.error(chalk.red('Translation failed:'));
for (const item of result.incompatible) {
console.error(chalk.red(` ${item}`));
}
return 1;
}
// Show warnings
if (result.warnings.length > 0) {
console.log(chalk.yellow('\nWarnings:'));
for (const warning of result.warnings) {
console.log(chalk.yellow(` • ${warning}`));
}
}
// Show incompatible features
if (result.incompatible.length > 0) {
console.log(chalk.gray('\nIncompatible features:'));
for (const item of result.incompatible) {
console.log(chalk.gray(` • ${item}`));
}
}
// Dry run - just show preview
if (this.dryRun) {
console.log(chalk.bold(`\nTranslated content (${result.filename}):\n`));
console.log(chalk.gray('─'.repeat(60)));
console.log(result.content);
console.log(chalk.gray('─'.repeat(60)));
return 0;
}
// Determine output path
let outputPath: string;
if (this.output) {
outputPath = this.output;
} else {
const targetAdapter = getAdapter(targetAgent);
const outputDir = join(process.cwd(), targetAdapter.skillsDir, skillName!);
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
outputPath = join(outputDir, result.filename);
}
// Check for existing file
if (existsSync(outputPath) && !this.force) {
console.error(chalk.red(`Error: ${outputPath} already exists`));
console.log(chalk.gray('Use --force to overwrite'));
return 1;
}
// Write output
const outputDir = dirname(outputPath);
if (!existsSync(outputDir)) {
mkdirSync(outputDir, { recursive: true });
}
writeFileSync(outputPath, result.content, 'utf-8');
console.log(chalk.green(`\n✓ Translated to ${outputPath}`));
console.log(chalk.gray(` Format: ${result.targetFormat}`));
console.log(chalk.gray(` Agent: ${result.targetAgent}`));
return 0;
}
}
+19
View File
@@ -0,0 +1,19 @@
import { Command } from 'clipanion';
export class UICommand extends Command {
static override paths = [['ui'], ['tui']];
static override usage = Command.Usage({
description: 'Launch the interactive TUI (Terminal User Interface)',
examples: [
['Open interactive TUI', '$0 ui'],
['Alias for TUI', '$0 tui'],
],
});
async execute(): Promise<number> {
const { startTUI } = await import('@skillkit/tui');
await startTUI();
return 0;
}
}
+151
View File
@@ -0,0 +1,151 @@
import { existsSync, rmSync, cpSync } from 'node:fs';
import { join } from 'node:path';
import chalk from 'chalk';
import ora from 'ora';
import { Command, Option } from 'clipanion';
import { findAllSkills, findSkill, detectProvider, isLocalPath } from '@skillkit/core';
import { getSearchDirs, loadSkillMetadata, saveSkillMetadata } from '../helpers.js';
export class UpdateCommand extends Command {
static override paths = [['update'], ['u']];
static override usage = Command.Usage({
description: 'Update skills from their original sources',
examples: [
['Update all skills', '$0 update'],
['Update specific skills', '$0 update pdf xlsx'],
['Force update (overwrite local changes)', '$0 update --force'],
],
});
skills = Option.Rest();
force = Option.Boolean('--force,-f', false, {
description: 'Force update even if local changes exist',
});
async execute(): Promise<number> {
const spinner = ora();
const searchDirs = getSearchDirs();
let skillsToUpdate;
if (this.skills.length > 0) {
skillsToUpdate = this.skills
.map(name => findSkill(name, searchDirs))
.filter((s): s is NonNullable<typeof s> => s !== null);
const notFound = this.skills.filter(name => !findSkill(name, searchDirs));
if (notFound.length > 0) {
console.log(chalk.yellow(`Skills not found: ${notFound.join(', ')}`));
}
} else {
skillsToUpdate = findAllSkills(searchDirs);
}
if (skillsToUpdate.length === 0) {
console.log(chalk.yellow('No skills to update'));
return 0;
}
console.log(chalk.cyan(`Updating ${skillsToUpdate.length} skill(s)...\n`));
let updated = 0;
let skipped = 0;
let failed = 0;
for (const skill of skillsToUpdate) {
const metadata = loadSkillMetadata(skill.path);
if (!metadata) {
console.log(chalk.dim(`Skipping ${skill.name} (no metadata, reinstall needed)`));
skipped++;
continue;
}
spinner.start(`Updating ${skill.name}...`);
try {
if (isLocalPath(metadata.source)) {
const localPath = metadata.subpath
? join(metadata.source, metadata.subpath)
: metadata.source;
if (!existsSync(localPath)) {
spinner.warn(chalk.yellow(`${skill.name}: local source missing`));
skipped++;
continue;
}
const skillMdPath = join(localPath, 'SKILL.md');
if (!existsSync(skillMdPath)) {
spinner.warn(chalk.yellow(`${skill.name}: no SKILL.md at source`));
skipped++;
continue;
}
rmSync(skill.path, { recursive: true, force: true });
cpSync(localPath, skill.path, { recursive: true, dereference: true });
metadata.updatedAt = new Date().toISOString();
saveSkillMetadata(skill.path, metadata);
spinner.succeed(chalk.green(`Updated ${skill.name}`));
updated++;
} else {
const provider = detectProvider(metadata.source);
if (!provider) {
spinner.warn(chalk.yellow(`${skill.name}: unknown provider`));
skipped++;
continue;
}
const result = await provider.clone(metadata.source, '', { depth: 1 });
if (!result.success || !result.path) {
spinner.fail(chalk.red(`${skill.name}: ${result.error || 'clone failed'}`));
failed++;
continue;
}
const sourcePath = metadata.subpath
? join(result.path, metadata.subpath)
: result.path;
const skillMdPath = join(sourcePath, 'SKILL.md');
if (!existsSync(skillMdPath)) {
spinner.warn(chalk.yellow(`${skill.name}: no SKILL.md in source`));
rmSync(result.path, { recursive: true, force: true });
skipped++;
continue;
}
rmSync(skill.path, { recursive: true, force: true });
cpSync(sourcePath, skill.path, { recursive: true, dereference: true });
rmSync(result.path, { recursive: true, force: true });
metadata.updatedAt = new Date().toISOString();
saveSkillMetadata(skill.path, metadata);
spinner.succeed(chalk.green(`Updated ${skill.name}`));
updated++;
}
} catch (error) {
spinner.fail(chalk.red(`Failed to update ${skill.name}`));
console.error(chalk.dim(error instanceof Error ? error.message : String(error)));
failed++;
}
}
console.log();
console.log(
chalk.cyan(
`Updated: ${updated}, Skipped: ${skipped}, Failed: ${failed}`
)
);
return failed > 0 ? 1 : 0;
}
}
+87
View File
@@ -0,0 +1,87 @@
import { existsSync, readdirSync } from 'node:fs';
import { join, basename } from 'node:path';
import chalk from 'chalk';
import { Command, Option } from 'clipanion';
import { validateSkill } from '@skillkit/core';
export class ValidateCommand extends Command {
static override paths = [['validate'], ['v']];
static override usage = Command.Usage({
description: 'Validate skill(s) against the Agent Skills specification (agentskills.io)',
examples: [
['Validate a skill directory', '$0 validate ./my-skill'],
['Validate all skills in a directory', '$0 validate ./skills --all'],
],
});
skillPath = Option.String({ required: true });
all = Option.Boolean('--all,-a', false, {
description: 'Validate all skills in the directory',
});
async execute(): Promise<number> {
const targetPath = this.skillPath;
if (!existsSync(targetPath)) {
console.error(chalk.red(`Path does not exist: ${targetPath}`));
return 1;
}
const skillPaths: string[] = [];
if (this.all) {
const entries = readdirSync(targetPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const skillPath = join(targetPath, entry.name);
if (existsSync(join(skillPath, 'SKILL.md'))) {
skillPaths.push(skillPath);
}
}
}
if (skillPaths.length === 0) {
console.error(chalk.yellow('No skills found in directory'));
return 1;
}
} else {
skillPaths.push(targetPath);
}
let hasErrors = false;
for (const skillPath of skillPaths) {
const skillName = basename(skillPath);
const result = validateSkill(skillPath);
if (result.valid) {
console.log(chalk.green(`✓ ${skillName}`));
if (result.warnings && result.warnings.length > 0) {
result.warnings.forEach(w => {
console.log(chalk.yellow(` ⚠ ${w}`));
});
}
} else {
console.log(chalk.red(`✗ ${skillName}`));
result.errors.forEach(e => {
console.log(chalk.red(` • ${e}`));
});
hasErrors = true;
}
}
console.log();
if (hasErrors) {
console.log(chalk.red('Validation failed'));
console.log(chalk.dim('See https://agentskills.io/specification for the complete format'));
return 1;
}
console.log(chalk.green(`Validated ${skillPaths.length} skill(s) successfully`));
return 0;
}
}
@@ -0,0 +1,63 @@
import { Command, Option } from 'clipanion';
import { resolve } from 'node:path';
import chalk from 'chalk';
import { createWorkflowTemplate, saveWorkflow, serializeWorkflow } from '@skillkit/core';
/**
* Workflow Create command - create a new workflow
*/
export class WorkflowCreateCommand extends Command {
static override paths = [['workflow', 'create'], ['wf', 'create'], ['workflow', 'new'], ['wf', 'new']];
static override usage = Command.Usage({
description: 'Create a new workflow',
details: `
The workflow create command creates a new workflow template
that you can customize with your skill composition.
`,
examples: [
['Create a new workflow', '$0 workflow create my-workflow'],
['Create with description', '$0 workflow create setup-project --description "Project setup workflow"'],
['Print to stdout', '$0 workflow create my-workflow --stdout'],
],
});
// Workflow name
workflowName = Option.String({ required: true });
// Description
description = Option.String('--description,-d', {
description: 'Workflow description',
});
// Print to stdout instead of saving
stdout = Option.Boolean('--stdout', false, {
description: 'Print workflow YAML to stdout instead of saving',
});
// Project path
projectPath = Option.String('--path,-p', {
description: 'Project path (default: current directory)',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
const workflow = createWorkflowTemplate(this.workflowName, this.description);
if (this.stdout) {
console.log(serializeWorkflow(workflow));
return 0;
}
const filePath = saveWorkflow(targetPath, workflow);
console.log(chalk.green(`✓ Created workflow: ${chalk.bold(this.workflowName)}`));
console.log(chalk.dim(` File: ${filePath}`));
console.log();
console.log(chalk.dim('Edit the workflow file to add skills and configure waves.'));
console.log(chalk.dim('Run with: skillkit workflow run ' + this.workflowName));
return 0;
}
}
@@ -0,0 +1,4 @@
// Workflow command exports
export { WorkflowRunCommand } from './run.js';
export { WorkflowListCommand } from './list.js';
export { WorkflowCreateCommand } from './create.js';
@@ -0,0 +1,94 @@
import { Command, Option } from 'clipanion';
import { resolve } from 'node:path';
import chalk from 'chalk';
import { listWorkflows } from '@skillkit/core';
/**
* Workflow List command - list available workflows
*/
export class WorkflowListCommand extends Command {
static override paths = [['workflow', 'list'], ['wf', 'list'], ['workflow', 'ls'], ['wf', 'ls']];
static override usage = Command.Usage({
description: 'List available workflows',
details: `
The workflow list command shows all available workflows
defined in .skillkit/workflows/
`,
examples: [
['List all workflows', '$0 workflow list'],
['List with details', '$0 workflow list --verbose'],
],
});
// Verbose output
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed workflow information',
});
// JSON output
json = Option.Boolean('--json,-j', false, {
description: 'Output in JSON format',
});
// Project path
projectPath = Option.String('--path,-p', {
description: 'Project path (default: current directory)',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
let workflows: ReturnType<typeof listWorkflows>;
try {
workflows = listWorkflows(targetPath);
} catch (err) {
console.log(chalk.red('Failed to list workflows.'));
console.log(chalk.dim(String(err)));
return 1;
}
if (this.json) {
console.log(JSON.stringify(workflows, null, 2));
return 0;
}
if (workflows.length === 0) {
console.log(chalk.yellow('No workflows found.'));
console.log(chalk.dim('Create a workflow with: skillkit workflow create'));
console.log(chalk.dim('Or add YAML files to .skillkit/workflows/'));
return 0;
}
console.log(chalk.cyan(`Available Workflows (${workflows.length}):\n`));
for (const workflow of workflows) {
console.log(` ${chalk.bold(workflow.name)}`);
if (workflow.description) {
console.log(` ${chalk.dim(workflow.description)}`);
}
if (this.verbose) {
console.log(` Version: ${chalk.dim(workflow.version || 'N/A')}`);
console.log(` Waves: ${chalk.dim(workflow.waves.length.toString())}`);
const totalSkills = workflow.waves.reduce(
(sum, wave) => sum + wave.skills.length,
0
);
console.log(` Total Skills: ${chalk.dim(totalSkills.toString())}`);
if (workflow.tags && workflow.tags.length > 0) {
console.log(` Tags: ${chalk.dim(workflow.tags.join(', '))}`);
}
}
console.log();
}
console.log(chalk.dim('Run a workflow with: skillkit workflow run <name>'));
return 0;
}
}
+204
View File
@@ -0,0 +1,204 @@
import { Command, Option } from 'clipanion';
import { resolve } from 'node:path';
import chalk from 'chalk';
import ora from 'ora';
import {
loadWorkflowByName,
loadWorkflow,
validateWorkflow,
createWorkflowOrchestrator,
} from '@skillkit/core';
/**
* Workflow Run command - execute a workflow
*/
export class WorkflowRunCommand extends Command {
static override paths = [['workflow', 'run'], ['wf', 'run']];
static override usage = Command.Usage({
description: 'Execute a skill workflow',
details: `
The workflow run command executes a workflow definition,
running skills in waves with parallel or sequential execution.
Workflows are defined in YAML files in .skillkit/workflows/
`,
examples: [
['Run a workflow by name', '$0 workflow run setup-project'],
['Run a workflow from file', '$0 workflow run --file my-workflow.yaml'],
['Dry run (no execution)', '$0 workflow run setup-project --dry-run'],
],
});
// Workflow name
workflowName = Option.String({ required: false });
// Workflow file path
file = Option.String('--file,-f', {
description: 'Path to workflow YAML file',
});
// Dry run
dryRun = Option.Boolean('--dry-run,-n', false, {
description: 'Show what would be executed without running',
});
// Verbose output
verbose = Option.Boolean('--verbose,-v', false, {
description: 'Show detailed execution progress',
});
// Continue on error
continueOnError = Option.Boolean('--continue-on-error', false, {
description: 'Continue execution even if a skill fails',
});
// JSON output
json = Option.Boolean('--json,-j', false, {
description: 'Output in JSON format',
});
// Project path
projectPath = Option.String('--path,-p', {
description: 'Project path (default: current directory)',
});
async execute(): Promise<number> {
const targetPath = resolve(this.projectPath || process.cwd());
// Load workflow
let workflow;
try {
if (this.file) {
workflow = loadWorkflow(resolve(this.file));
} else if (this.workflowName) {
workflow = loadWorkflowByName(targetPath, this.workflowName);
if (!workflow) {
console.error(chalk.red(`Workflow "${this.workflowName}" not found`));
console.log(chalk.dim('List available workflows: skillkit workflow list'));
return 1;
}
} else {
console.error(chalk.red('Please specify a workflow name or --file'));
return 1;
}
} catch (error) {
console.error(chalk.red(`Failed to load workflow: ${error}`));
return 1;
}
// Validate workflow
const validation = validateWorkflow(workflow);
if (!validation.valid) {
console.error(chalk.red('Invalid workflow:'));
for (const error of validation.errors) {
console.error(chalk.red(` • ${error}`));
}
return 1;
}
// Dry run mode
if (this.dryRun) {
this.showDryRun(workflow);
return 0;
}
// Execute workflow
console.log(chalk.cyan(`Executing workflow: ${chalk.bold(workflow.name)}`));
if (workflow.description) {
console.log(chalk.dim(workflow.description));
}
console.log();
const spinner = ora();
let currentWave = -1;
// Create orchestrator with mock executor (for now)
const orchestrator = createWorkflowOrchestrator(
async (_skillName, _config) => {
// TODO: Integrate with actual skill execution
// For now, simulate execution
await new Promise((resolve) => setTimeout(resolve, 500));
return { success: true };
},
(event) => {
if (this.json) return;
switch (event.type) {
case 'wave_start':
currentWave = event.waveIndex || 0;
spinner.start(`Wave ${currentWave + 1}: ${event.waveName || 'Executing...'}`);
break;
case 'skill_start':
if (this.verbose) {
spinner.text = `Wave ${currentWave + 1}: Running ${event.skillName}...`;
}
break;
case 'skill_complete':
if (this.verbose) {
const icon = event.status === 'completed' ? chalk.green('✓') : chalk.red('✗');
console.log(` ${icon} ${event.skillName}`);
}
break;
case 'wave_complete':
const waveIcon = event.status === 'completed' ? chalk.green('✓') : chalk.red('✗');
spinner.stopAndPersist({
symbol: waveIcon,
text: `Wave ${(event.waveIndex || 0) + 1}: ${event.waveName || 'Complete'}`,
});
break;
case 'workflow_complete':
console.log();
if (event.status === 'completed') {
console.log(chalk.green('✓ Workflow completed successfully'));
} else {
console.log(chalk.red(`✗ Workflow ${event.status}`));
if (event.error) {
console.log(chalk.red(` Error: ${event.error}`));
}
}
break;
}
}
);
const execution = await orchestrator.execute(workflow);
if (this.json) {
console.log(JSON.stringify(execution, null, 2));
}
return execution.status === 'completed' ? 0 : 1;
}
private showDryRun(workflow: { name: string; description?: string; waves: Array<{ name?: string; parallel: boolean; skills: Array<string | { skill: string }> }> }): void {
console.log(chalk.cyan('Dry Run - Workflow Execution Plan'));
console.log();
console.log(`Workflow: ${chalk.bold(workflow.name)}`);
if (workflow.description) {
console.log(`Description: ${chalk.dim(workflow.description)}`);
}
console.log();
for (let i = 0; i < workflow.waves.length; i++) {
const wave = workflow.waves[i];
const modeLabel = wave.parallel ? chalk.blue('[parallel]') : chalk.yellow('[sequential]');
console.log(`${chalk.cyan(`Wave ${i + 1}`)}: ${wave.name || 'Unnamed'} ${modeLabel}`);
for (const skill of wave.skills) {
const skillName = typeof skill === 'string' ? skill : skill.skill;
console.log(` • ${skillName}`);
}
console.log();
}
console.log(chalk.dim('This is a dry run. No skills were executed.'));
console.log(chalk.dim('Remove --dry-run to execute the workflow.'));
}
}
+64
View File
@@ -0,0 +1,64 @@
// Re-export commonly used functions with proper adapters
import {
loadConfig,
getSearchDirs as coreGetSearchDirs,
getInstallDir as coreGetInstallDir,
getAgentConfigPath as coreGetAgentConfigPath,
initProject as coreInitProject,
loadSkillMetadata as coreLoadSkillMetadata,
saveSkillMetadata as coreSaveSkillMetadata,
} from '@skillkit/core';
import { getAdapter, detectAgent } from '@skillkit/agents';
import type { AgentType, AgentAdapterInfo } from '@skillkit/core';
// Re-export metadata functions directly (they don't need adapter bridging)
export const loadSkillMetadata = coreLoadSkillMetadata;
export const saveSkillMetadata = coreSaveSkillMetadata;
export function getSearchDirs(agentType?: AgentType): string[] {
const type = agentType || loadConfig().agent;
const adapter = getAdapter(type);
const adapterInfo: AgentAdapterInfo = {
type: adapter.type,
name: adapter.name,
skillsDir: adapter.skillsDir,
configFile: adapter.configFile,
};
return coreGetSearchDirs(adapterInfo);
}
export function getInstallDir(global = false, agentType?: AgentType): string {
const type = agentType || loadConfig().agent;
const adapter = getAdapter(type);
const adapterInfo: AgentAdapterInfo = {
type: adapter.type,
name: adapter.name,
skillsDir: adapter.skillsDir,
configFile: adapter.configFile,
};
return coreGetInstallDir(adapterInfo, global);
}
export function getAgentConfigPath(agentType?: AgentType): string {
const type = agentType || loadConfig().agent;
const adapter = getAdapter(type);
const adapterInfo: AgentAdapterInfo = {
type: adapter.type,
name: adapter.name,
skillsDir: adapter.skillsDir,
configFile: adapter.configFile,
};
return coreGetAgentConfigPath(adapterInfo);
}
export async function initProject(agentType?: AgentType): Promise<void> {
const type = agentType || (await detectAgent());
const adapter = getAdapter(type);
const adapterInfo: AgentAdapterInfo = {
type: adapter.type,
name: adapter.name,
skillsDir: adapter.skillsDir,
configFile: adapter.configFile,
};
return coreInitProject(type, adapterInfo);
}
+8
View File
@@ -0,0 +1,8 @@
// Export all commands
export * from './commands/index.js';
// Export helper functions
export * from './helpers.js';
// Re-export commonly used types from core
export type { AgentType, Skill, SkillMetadata, SkillkitConfig } from '@skillkit/core';
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"composite": false
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
+14
View File
@@ -0,0 +1,14 @@
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',
});
+47
View File
@@ -0,0 +1,47 @@
# @skillkit/core
Core functionality for SkillKit - skill discovery, parsing, translation, and context management.
## Installation
```bash
npm install @skillkit/core
```
## Features
- **Skill Discovery**: Find and parse SKILL.md files
- **Skill Translation**: Convert between agent formats (Claude Code, Cursor, Windsurf, etc.)
- **Project Context Detection**: Analyze project stack and dependencies
- **Recommendation Engine**: Smart skill suggestions based on project profile
## Usage
```typescript
import {
loadConfig,
getSearchDirs,
translateSkill,
ProjectDetector,
RecommendationEngine
} from '@skillkit/core';
// Load skillkit config
const config = loadConfig();
// Detect project context
const detector = new ProjectDetector();
const profile = await detector.analyze('./my-project');
// Get skill recommendations
const engine = new RecommendationEngine();
const recommendations = await engine.recommend(profile);
```
## Documentation
Full documentation: https://github.com/rohitg00/skillkit
## License
Apache-2.0
+59
View File
@@ -0,0 +1,59 @@
{
"name": "@skillkit/core",
"version": "1.4.0",
"description": "Core functionality for SkillKit - skill discovery, parsing, and translation",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"import": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./types": {
"import": "./dist/types/index.js",
"types": "./dist/types/index.d.ts"
},
"./discovery": {
"import": "./dist/discovery/index.js",
"types": "./dist/discovery/index.d.ts"
},
"./parser": {
"import": "./dist/parser/index.js",
"types": "./dist/parser/index.d.ts"
},
"./translator": {
"import": "./dist/translator/index.js",
"types": "./dist/translator/index.d.ts"
},
"./context": {
"import": "./dist/context/index.js",
"types": "./dist/context/index.d.ts"
},
"./recommend": {
"import": "./dist/recommend/index.js",
"types": "./dist/recommend/index.d.ts"
}
},
"files": ["dist"],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"yaml": "^2.6.1",
"zod": "^3.24.1"
},
"devDependencies": {
"@types/node": "^22.10.5",
"tsup": "^8.3.5",
"typescript": "^5.7.2",
"vitest": "^2.1.8"
},
"engines": {
"node": ">=18.0.0"
},
"license": "Apache-2.0"
}
+18
View File
@@ -0,0 +1,18 @@
/**
* CI/CD Integration Module
*
* Provides templates and utilities for integrating skill validation
* into CI/CD pipelines.
*/
export * from './templates.js';
export {
GITHUB_ACTION_TEMPLATE,
PRE_COMMIT_HOOK_TEMPLATE,
PRE_COMMIT_CONFIG_TEMPLATE,
GITLAB_CI_TEMPLATE,
CIRCLECI_CONFIG_TEMPLATE,
getCICDTemplate,
listCICDTemplates,
} from './templates.js';
+238
View File
@@ -0,0 +1,238 @@
/**
* CI/CD Templates
*
* Provides templates for GitHub Actions, pre-commit hooks, and other CI/CD integrations.
*/
/**
* GitHub Action workflow for skill validation
*/
export const GITHUB_ACTION_TEMPLATE = `# Skill Validation Workflow
# This workflow validates skills in your repository
name: Validate Skills
on:
push:
paths:
- '.claude/skills/**'
- '.cursor/skills/**'
- 'skills/**'
pull_request:
paths:
- '.claude/skills/**'
- '.cursor/skills/**'
- 'skills/**'
jobs:
validate:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install SkillKit
run: npm install -g skillkit
- name: Validate Skills
run: skillkit validate
- name: Run Skill Tests
run: skillkit test --json > test-results.json
continue-on-error: true
- name: Upload Test Results
uses: actions/upload-artifact@v4
with:
name: skill-test-results
path: test-results.json
retention-days: 30
- name: Check Test Results
run: |
if [ -f test-results.json ]; then
passed=$(cat test-results.json | jq -r '.passed')
if [ "$passed" = "false" ]; then
echo "Some skill tests failed"
exit 1
fi
fi
`;
/**
* Pre-commit hook script for skill validation
*/
export const PRE_COMMIT_HOOK_TEMPLATE = `#!/bin/bash
# SkillKit Pre-commit Hook
# Validates skills before commit
# Colors for output
RED='\\033[0;31m'
GREEN='\\033[0;32m'
YELLOW='\\033[0;33m'
NC='\\033[0m' # No Color
echo -e "\${YELLOW}Running SkillKit validation...\${NC}"
# Check if skillkit is installed
if ! command -v skillkit &> /dev/null; then
echo -e "\${RED}SkillKit not found. Install with: npm install -g skillkit\${NC}"
exit 1
fi
# Get list of staged skill files
SKILL_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\\.(md|mdc)$' | grep -E '(skills|.claude|.cursor)')
if [ -z "$SKILL_FILES" ]; then
echo -e "\${GREEN}No skill files staged, skipping validation.\${NC}"
exit 0
fi
echo "Validating skill files:"
echo "$SKILL_FILES"
# Run validation
if ! skillkit validate; then
echo -e "\${RED}Skill validation failed. Please fix the errors and try again.\${NC}"
exit 1
fi
# Run tests if any
if skillkit test --json 2>/dev/null | jq -e '.passed == false' > /dev/null 2>&1; then
echo -e "\${RED}Skill tests failed. Please fix the failing tests.\${NC}"
exit 1
fi
echo -e "\${GREEN}All skills validated successfully!\${NC}"
exit 0
`;
/**
* Pre-commit config for .pre-commit-config.yaml
*/
export const PRE_COMMIT_CONFIG_TEMPLATE = `# SkillKit Pre-commit Configuration
# Add this to your .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: skillkit-validate
name: SkillKit Validate
entry: skillkit validate
language: system
files: \\.(md|mdc)$
pass_filenames: false
- id: skillkit-test
name: SkillKit Test
entry: skillkit test
language: system
files: \\.(md|mdc)$
pass_filenames: false
`;
/**
* GitLab CI template
*/
export const GITLAB_CI_TEMPLATE = `# SkillKit GitLab CI Configuration
# Add this to your .gitlab-ci.yml
skill-validation:
image: node:20
stage: test
before_script:
- npm install -g skillkit
script:
- skillkit validate
- skillkit test --json > test-results.json
artifacts:
# Note: test-results.json is JSON format, not JUnit XML
paths:
- test-results.json
expire_in: 30 days
rules:
- changes:
- ".claude/skills/**"
- ".cursor/skills/**"
- "skills/**"
`;
/**
* CircleCI config template
*/
export const CIRCLECI_CONFIG_TEMPLATE = `# SkillKit CircleCI Configuration
# Add this to your .circleci/config.yml
version: 2.1
jobs:
validate-skills:
docker:
- image: cimg/node:20.0
steps:
- checkout
- run:
name: Install SkillKit
command: npm install -g skillkit
- run:
name: Validate Skills
command: skillkit validate
- run:
name: Run Skill Tests
command: skillkit test --json > test-results.json
- store_artifacts:
path: test-results.json
destination: skill-tests
workflows:
skill-validation:
jobs:
- validate-skills:
filters:
branches:
only: /.*/
`;
/**
* Get a CI/CD template by name
*/
export function getCICDTemplate(name: string): string | null {
switch (name.toLowerCase()) {
case 'github':
case 'github-action':
case 'github-actions':
return GITHUB_ACTION_TEMPLATE;
case 'pre-commit':
case 'pre-commit-hook':
return PRE_COMMIT_HOOK_TEMPLATE;
case 'pre-commit-config':
return PRE_COMMIT_CONFIG_TEMPLATE;
case 'gitlab':
case 'gitlab-ci':
return GITLAB_CI_TEMPLATE;
case 'circleci':
case 'circle-ci':
return CIRCLECI_CONFIG_TEMPLATE;
default:
return null;
}
}
/**
* List available CI/CD templates
*/
export function listCICDTemplates(): { name: string; description: string }[] {
return [
{ name: 'github-action', description: 'GitHub Actions workflow for skill validation' },
{ name: 'pre-commit-hook', description: 'Git pre-commit hook script' },
{ name: 'pre-commit-config', description: 'pre-commit framework configuration' },
{ name: 'gitlab-ci', description: 'GitLab CI configuration' },
{ name: 'circleci', description: 'CircleCI configuration' },
];
}
+144
View File
@@ -0,0 +1,144 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { homedir } from 'node:os';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { SkillkitConfig, type AgentType, type SkillMetadata, type AgentAdapterInfo } from './types.js';
const CONFIG_FILE = 'skillkit.yaml';
const METADATA_FILE = '.skillkit.json';
export function getProjectConfigPath(): string {
return join(process.cwd(), CONFIG_FILE);
}
export function getGlobalConfigPath(): string {
return join(homedir(), '.config', 'skillkit', CONFIG_FILE);
}
export function loadConfig(): SkillkitConfig {
const projectPath = getProjectConfigPath();
const globalPath = getGlobalConfigPath();
if (existsSync(projectPath)) {
try {
const content = readFileSync(projectPath, 'utf-8');
const data = parseYaml(content);
const parsed = SkillkitConfig.safeParse(data);
if (parsed.success) {
return parsed.data;
}
} catch {
// Ignore parse errors
}
}
if (existsSync(globalPath)) {
try {
const content = readFileSync(globalPath, 'utf-8');
const data = parseYaml(content);
const parsed = SkillkitConfig.safeParse(data);
if (parsed.success) {
return parsed.data;
}
} catch {
// Ignore parse errors
}
}
return {
version: 1,
agent: 'universal',
autoSync: true,
};
}
export function saveConfig(config: SkillkitConfig, global = false): void {
const configPath = global ? getGlobalConfigPath() : getProjectConfigPath();
const dir = dirname(configPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
const content = stringifyYaml(config);
writeFileSync(configPath, content, 'utf-8');
}
export function getSearchDirs(adapter: AgentAdapterInfo): string[] {
const dirs: string[] = [];
dirs.push(join(process.cwd(), adapter.skillsDir));
dirs.push(join(process.cwd(), '.agent', 'skills'));
dirs.push(join(homedir(), adapter.skillsDir));
dirs.push(join(homedir(), '.agent', 'skills'));
return dirs;
}
export function getInstallDir(adapter: AgentAdapterInfo, global = false): string {
if (global) {
return join(homedir(), adapter.skillsDir);
}
return join(process.cwd(), adapter.skillsDir);
}
export function getAgentConfigPath(adapter: AgentAdapterInfo): string {
return join(process.cwd(), adapter.configFile);
}
export function saveSkillMetadata(skillPath: string, metadata: SkillMetadata): void {
const metadataPath = join(skillPath, METADATA_FILE);
writeFileSync(metadataPath, JSON.stringify(metadata, null, 2), 'utf-8');
}
export function loadSkillMetadata(skillPath: string): SkillMetadata | null {
const metadataPath = join(skillPath, METADATA_FILE);
if (!existsSync(metadataPath)) {
return null;
}
try {
const content = readFileSync(metadataPath, 'utf-8');
return JSON.parse(content) as SkillMetadata;
} catch {
return null;
}
}
export function setSkillEnabled(skillPath: string, enabled: boolean): boolean {
const metadata = loadSkillMetadata(skillPath);
if (!metadata) {
return false;
}
metadata.enabled = enabled;
metadata.updatedAt = new Date().toISOString();
saveSkillMetadata(skillPath, metadata);
return true;
}
export async function initProject(
type: AgentType,
adapter: AgentAdapterInfo
): Promise<void> {
const skillsDir = join(process.cwd(), adapter.skillsDir);
if (!existsSync(skillsDir)) {
mkdirSync(skillsDir, { recursive: true });
}
const config: SkillkitConfig = {
version: 1,
agent: type,
autoSync: true,
};
saveConfig(config);
const agentConfigPath = join(process.cwd(), adapter.configFile);
if (!existsSync(agentConfigPath)) {
writeFileSync(agentConfigPath, `# ${adapter.name} Configuration\n\n`, 'utf-8');
}
}
@@ -0,0 +1,795 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { ProjectDetector, analyzeProject, getStackTags } from '../detector.js';
import type { ProjectStack } from '../types.js';
// Mock the fs module
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
readFileSync: vi.fn(),
readdirSync: vi.fn(),
}));
describe('ProjectDetector', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.resetAllMocks();
});
describe('language detection', () => {
it('should detect TypeScript from tsconfig.json', () => {
const mockPackageJson = {
name: 'test-project',
devDependencies: {
typescript: '5.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('package.json')) return true;
if (path.includes('tsconfig.json')) return true;
}
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
// Return files including tsconfig.json for file scanning
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
{ name: 'tsconfig.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.languages).toContainEqual(
expect.objectContaining({
name: 'typescript',
confidence: 100,
})
);
});
it('should detect JavaScript when no TypeScript config', () => {
const mockPackageJson = {
name: 'js-project',
dependencies: {
lodash: '4.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('package.json')) return true;
if (path.includes('tsconfig.json')) return false;
}
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.languages).toContainEqual(
expect.objectContaining({
name: 'javascript',
})
);
});
it('should detect Python from pyproject.toml', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('pyproject.toml')) return true;
}
return false;
});
vi.mocked(readFileSync).mockReturnValue('');
vi.mocked(readdirSync).mockReturnValue([
{ name: 'pyproject.toml', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.languages).toContainEqual(
expect.objectContaining({
name: 'python',
confidence: 100,
})
);
});
it('should detect Rust from Cargo.toml', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('Cargo.toml')) return true;
}
return false;
});
vi.mocked(readFileSync).mockReturnValue('');
vi.mocked(readdirSync).mockReturnValue([
{ name: 'Cargo.toml', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.languages).toContainEqual(
expect.objectContaining({
name: 'rust',
confidence: 100,
})
);
});
it('should detect Go from go.mod', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('go.mod')) return true;
}
return false;
});
vi.mocked(readFileSync).mockReturnValue('');
vi.mocked(readdirSync).mockReturnValue([
{ name: 'go.mod', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.languages).toContainEqual(
expect.objectContaining({
name: 'go',
confidence: 100,
})
);
});
});
describe('framework detection', () => {
it('should detect React from package.json', () => {
const mockPackageJson = {
name: 'react-project',
dependencies: {
react: '18.2.0',
'react-dom': '18.2.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.frameworks).toContainEqual(
expect.objectContaining({
name: 'react',
version: '18.2.0',
})
);
});
it('should detect Next.js from package.json', () => {
const mockPackageJson = {
name: 'nextjs-project',
dependencies: {
next: '14.0.0',
react: '18.2.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.frameworks).toContainEqual(
expect.objectContaining({
name: 'nextjs',
version: '14.0.0',
})
);
});
it('should detect Vue from package.json', () => {
const mockPackageJson = {
name: 'vue-project',
dependencies: {
vue: '3.4.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.frameworks).toContainEqual(
expect.objectContaining({
name: 'vue',
version: '3.4.0',
})
);
});
it('should detect Express from package.json', () => {
const mockPackageJson = {
name: 'express-project',
dependencies: {
express: '4.18.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.frameworks).toContainEqual(
expect.objectContaining({
name: 'express',
})
);
});
});
describe('library detection', () => {
it('should detect state management libraries', () => {
const mockPackageJson = {
name: 'state-project',
dependencies: {
zustand: '4.0.0',
jotai: '2.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.libraries).toContainEqual(
expect.objectContaining({
name: 'zustand',
})
);
expect(stack.libraries).toContainEqual(
expect.objectContaining({
name: 'jotai',
})
);
});
it('should detect data fetching libraries', () => {
const mockPackageJson = {
name: 'fetch-project',
dependencies: {
'@tanstack/react-query': '5.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.libraries).toContainEqual(
expect.objectContaining({
name: 'tanstack',
})
);
});
});
describe('styling detection', () => {
it('should detect Tailwind CSS', () => {
const mockPackageJson = {
name: 'tailwind-project',
devDependencies: {
tailwindcss: '3.4.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.styling).toContainEqual(
expect.objectContaining({
name: 'tailwindcss',
})
);
});
it('should detect styled-components', () => {
const mockPackageJson = {
name: 'styled-project',
dependencies: {
'styled-components': '6.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.styling).toContainEqual(
expect.objectContaining({
name: 'styled-components',
})
);
});
});
describe('testing detection', () => {
it('should detect Vitest', () => {
const mockPackageJson = {
name: 'test-project',
devDependencies: {
vitest: '1.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.testing).toContainEqual(
expect.objectContaining({
name: 'vitest',
})
);
});
it('should detect Playwright', () => {
const mockPackageJson = {
name: 'e2e-project',
devDependencies: {
'@playwright/test': '1.40.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.testing).toContainEqual(
expect.objectContaining({
name: 'playwright',
})
);
});
});
describe('database detection', () => {
it('should detect Prisma', () => {
const mockPackageJson = {
name: 'db-project',
dependencies: {
'@prisma/client': '5.0.0',
},
devDependencies: {
prisma: '5.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.databases).toContainEqual(
expect.objectContaining({
name: 'prisma',
})
);
});
it('should detect Supabase', () => {
const mockPackageJson = {
name: 'supabase-project',
dependencies: {
'@supabase/supabase-js': '2.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.databases).toContainEqual(
expect.objectContaining({
name: 'supabase',
})
);
});
});
describe('tool detection', () => {
it('should detect ESLint', () => {
const mockPackageJson = {
name: 'lint-project',
devDependencies: {
eslint: '8.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.tools).toContainEqual(
expect.objectContaining({
name: 'eslint',
})
);
});
it('should detect Prettier', () => {
const mockPackageJson = {
name: 'format-project',
devDependencies: {
prettier: '3.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const stack = detector.analyze();
expect(stack.tools).toContainEqual(
expect.objectContaining({
name: 'prettier',
})
);
});
});
describe('project type detection', () => {
it('should return unknown for projects without specific dependencies', () => {
const mockPackageJson = {
name: 'generic-project',
dependencies: {},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
const projectType = detector.detectProjectType();
expect(projectType).toBe('unknown');
});
it('should detect library from build config', () => {
const mockPackageJson = {
name: 'my-library',
dependencies: {},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('package.json')) return true;
// hasFile('tsup.config.ts') needs this to return true
if (path.includes('tsup.config.ts')) return true;
}
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
{ name: 'tsup.config.ts', isDirectory: () => false },
] as any);
const detector = new ProjectDetector('/test/project');
// Must call analyze() first to populate the files set
// detectProjectType() relies on hasFile() which checks the files set
detector.analyze();
const projectType = detector.detectProjectType();
expect(projectType).toBe('library');
});
});
});
describe('analyzeProject', () => {
it('should return project stack', () => {
const mockPackageJson = {
name: 'full-project',
dependencies: {
react: '18.0.0',
},
};
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify(mockPackageJson);
}
return '';
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'package.json', isDirectory: () => false },
] as any);
const stack = analyzeProject('/test/project');
expect(stack).toHaveProperty('languages');
expect(stack).toHaveProperty('frameworks');
expect(stack).toHaveProperty('libraries');
});
});
describe('getStackTags', () => {
it('should generate tags from stack', () => {
const stack: ProjectStack = {
languages: [{ name: 'typescript', confidence: 100 }],
frameworks: [{ name: 'react', confidence: 100 }],
libraries: [],
styling: [{ name: 'tailwindcss', confidence: 100 }],
testing: [],
databases: [],
tools: [],
runtime: [],
};
const tags = getStackTags(stack);
expect(tags).toContain('typescript');
expect(tags).toContain('react');
// tailwindcss gets tags from STYLING_PATTERNS
expect(tags.some(t => t === 'tailwind' || t === 'tailwindcss')).toBe(true);
});
});
@@ -0,0 +1,607 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { ContextManager, createContextManager, loadContext, initContext } from '../manager.js';
import type { ProjectContext } from '../types.js';
// Mock fs module
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
}));
// Mock the detector module with a class
vi.mock('../detector.js', () => ({
ProjectDetector: class MockProjectDetector {
analyze() {
return {
languages: [{ name: 'typescript', version: '5.0.0', confidence: 100 }],
frameworks: [{ name: 'react', version: '18.0.0', confidence: 100 }],
libraries: [],
styling: [],
testing: [],
databases: [],
tools: [],
runtime: [],
};
}
detectPatterns() {
return {};
}
detectProjectType() {
return 'web-application';
}
getProjectName() {
return 'test-project';
}
getProjectDescription() {
return 'A test project';
}
},
getStackTags: vi.fn().mockReturnValue(['typescript', 'react']),
}));
describe('ContextManager', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.resetAllMocks();
});
describe('exists', () => {
it('should return true when context file exists', () => {
vi.mocked(existsSync).mockReturnValue(true);
const manager = new ContextManager('/test/project');
expect(manager.exists()).toBe(true);
});
it('should return false when context file does not exist', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new ContextManager('/test/project');
expect(manager.exists()).toBe(false);
});
});
describe('init', () => {
it('should create a new context file', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('package.json')) return true;
if (path.includes('context.yaml')) return false;
}
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify({
name: 'test-project',
description: 'A test project',
});
}
return '';
});
const manager = new ContextManager('/test/project');
const context = manager.init();
expect(context).toBeDefined();
expect(context.version).toBe(1);
expect(context.project.name).toBe('test-project');
expect(vi.mocked(writeFileSync)).toHaveBeenCalled();
expect(vi.mocked(mkdirSync)).toHaveBeenCalled();
});
it('should not overwrite existing context without force flag', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(`
version: 1
project:
name: existing-project
stack:
languages: []
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
`);
const manager = new ContextManager('/test/project');
const context = manager.init();
// Should return existing context
expect(context.project.name).toBe('existing-project');
});
it('should overwrite existing context with force flag', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('context.yaml')) return true;
if (path.includes('package.json')) return true;
}
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify({ name: 'new-project' });
}
if (typeof path === 'string' && path.includes('context.yaml')) {
return `
version: 1
project:
name: old-project
stack:
languages: []
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
`;
}
return '';
});
const manager = new ContextManager('/test/project');
const context = manager.init({ force: true });
// With force flag, a new context is created using ProjectDetector
// The mock returns 'test-project' from getProjectName()
// This validates that force creates new context instead of returning existing
expect(context.project.name).toBe('test-project');
});
});
describe('load', () => {
it('should load existing context', () => {
const existingContext = `
version: 1
project:
name: loaded-project
description: A loaded project
type: library
stack:
languages:
- name: typescript
confidence: 100
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
skills:
installed: []
autoSync: true
`;
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(existingContext);
const manager = new ContextManager('/test/project');
const context = manager.load();
expect(context).not.toBeNull();
expect(context!.project.name).toBe('loaded-project');
expect(context!.project.type).toBe('library');
});
it('should return null when context does not exist', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new ContextManager('/test/project');
const context = manager.load();
expect(context).toBeNull();
});
it('should handle malformed YAML by returning null', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue('invalid: yaml: content: [');
const manager = new ContextManager('/test/project');
// Implementation catches errors and returns null with a warning
const result = manager.load();
expect(result).toBeNull();
});
});
describe('save', () => {
it('should save context to file', () => {
vi.mocked(existsSync).mockReturnValue(true);
const context: ProjectContext = {
version: 1,
project: {
name: 'saved-project',
},
stack: {
languages: [],
frameworks: [],
libraries: [],
styling: [],
testing: [],
databases: [],
tools: [],
runtime: [],
},
};
const manager = new ContextManager('/test/project');
manager.save(context);
expect(vi.mocked(writeFileSync)).toHaveBeenCalled();
const [, content] = vi.mocked(writeFileSync).mock.calls[0];
expect(content).toContain('name: saved-project');
});
it('should create directory if it does not exist', () => {
vi.mocked(existsSync).mockReturnValue(false);
const context: ProjectContext = {
version: 1,
project: { name: 'test' },
stack: {
languages: [],
frameworks: [],
libraries: [],
styling: [],
testing: [],
databases: [],
tools: [],
runtime: [],
},
};
const manager = new ContextManager('/test/project');
manager.save(context);
expect(vi.mocked(mkdirSync)).toHaveBeenCalled();
});
});
describe('get', () => {
it('should return cached context', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(`
version: 1
project:
name: cached-project
stack:
languages: []
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
`);
const manager = new ContextManager('/test/project');
// First call loads from file
const first = manager.get();
expect(first?.project.name).toBe('cached-project');
// Second call should use cache (readFileSync should only be called once)
const second = manager.get();
expect(second?.project.name).toBe('cached-project');
});
it('should return null when no context exists', () => {
vi.mocked(existsSync).mockReturnValue(false);
const manager = new ContextManager('/test/project');
const context = manager.get();
expect(context).toBeNull();
});
});
describe('export', () => {
it('should export context as YAML', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(`
version: 1
project:
name: export-test
stack:
languages: []
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
`);
const manager = new ContextManager('/test/project');
const exported = manager.export({ format: 'yaml' });
expect(exported).toContain('version: 1');
expect(exported).toContain('name: export-test');
});
it('should export context as JSON', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(`
version: 1
project:
name: json-export
stack:
languages: []
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
`);
const manager = new ContextManager('/test/project');
const exported = manager.export({ format: 'json' });
const parsed = JSON.parse(exported);
expect(parsed.project.name).toBe('json-export');
});
});
describe('import', () => {
it('should import YAML context', () => {
vi.mocked(existsSync).mockReturnValue(false);
const importContent = `
version: 1
project:
name: imported-project
stack:
languages:
- name: python
confidence: 100
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
`;
const manager = new ContextManager('/test/project');
const context = manager.import(importContent, { overwrite: true });
expect(context.project.name).toBe('imported-project');
expect(vi.mocked(writeFileSync)).toHaveBeenCalled();
});
it('should import JSON context', () => {
vi.mocked(existsSync).mockReturnValue(false);
const importContent = JSON.stringify({
version: 1,
project: { name: 'json-imported' },
stack: {
languages: [],
frameworks: [],
libraries: [],
styling: [],
testing: [],
databases: [],
tools: [],
runtime: [],
},
});
const manager = new ContextManager('/test/project');
const context = manager.import(importContent, { overwrite: true });
expect(context.project.name).toBe('json-imported');
});
it('should merge with existing context', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(`
version: 1
project:
name: existing
stack:
languages:
- name: typescript
confidence: 100
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
`);
const importContent = `
version: 1
project:
name: imported
stack:
languages:
- name: python
confidence: 100
frameworks:
- name: django
confidence: 100
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
`;
const manager = new ContextManager('/test/project');
const context = manager.import(importContent, { merge: true });
// Should merge languages
expect(context.stack.languages).toHaveLength(2);
expect(context.stack.frameworks).toHaveLength(1);
});
});
describe('updateSkills', () => {
it('should update installed skills', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(`
version: 1
project:
name: skills-test
stack:
languages: []
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
skills:
installed: []
`);
const manager = new ContextManager('/test/project');
manager.updateSkills({
installed: ['skill-1', 'skill-2'],
});
expect(vi.mocked(writeFileSync)).toHaveBeenCalled();
const [, content] = vi.mocked(writeFileSync).mock.calls[0];
expect(content).toContain('skill-1');
expect(content).toContain('skill-2');
});
});
describe('updateAgents', () => {
it('should update agent configuration', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(`
version: 1
project:
name: agents-test
stack:
languages: []
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
agents:
detected: []
synced: []
`);
const manager = new ContextManager('/test/project');
manager.updateAgents({
primary: 'claude-code',
detected: ['claude-code', 'cursor'],
synced: ['claude-code', 'cursor'],
});
expect(vi.mocked(writeFileSync)).toHaveBeenCalled();
const [, content] = vi.mocked(writeFileSync).mock.calls[0];
expect(content).toContain('claude-code');
expect(content).toContain('cursor');
});
});
});
describe('convenience functions', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('createContextManager', () => {
it('should create a ContextManager instance', () => {
const manager = createContextManager('/test/project');
expect(manager).toBeInstanceOf(ContextManager);
});
it('should use current directory if no path provided', () => {
const manager = createContextManager();
expect(manager).toBeInstanceOf(ContextManager);
});
});
describe('loadContext', () => {
it('should load context from path', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(`
version: 1
project:
name: load-test
stack:
languages: []
frameworks: []
libraries: []
styling: []
testing: []
databases: []
tools: []
runtime: []
`);
const context = loadContext('/test/project');
expect(context).not.toBeNull();
expect(context?.project.name).toBe('load-test');
});
it('should return null if context does not exist', () => {
vi.mocked(existsSync).mockReturnValue(false);
const context = loadContext('/test/project');
expect(context).toBeNull();
});
});
describe('initContext', () => {
it('should initialize context', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) return true;
return false;
});
vi.mocked(readFileSync).mockImplementation((path) => {
if (typeof path === 'string' && path.includes('package.json')) {
return JSON.stringify({ name: 'init-test' });
}
return '';
});
const context = initContext('/test/project');
// The mock's getProjectName() returns 'test-project'
// This validates that initContext creates a new context using ProjectDetector
expect(context.project.name).toBe('test-project');
});
});
});
@@ -0,0 +1,510 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { existsSync, writeFileSync, mkdirSync, copyFileSync, readdirSync } from 'node:fs';
import { ContextSync, createContextSync, syncToAllAgents, syncToAgent } from '../sync.js';
import type { AgentType } from '../../types.js';
// Mock fs module
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
copyFileSync: vi.fn(),
readdirSync: vi.fn(),
}));
// Mock ContextManager with a class
vi.mock('../manager.js', () => ({
ContextManager: class MockContextManager {
get() {
return {
version: 1,
project: { name: 'test-project' },
stack: {
languages: [],
frameworks: [],
libraries: [],
styling: [],
testing: [],
databases: [],
tools: [],
runtime: [],
},
agents: {
detected: ['claude-code', 'cursor'],
synced: ['claude-code', 'cursor'],
},
};
}
init() {}
updateAgents() {}
},
}));
// Hoisted mocks - these are defined before vi.mock calls are hoisted
const { mockTranslateSkillFile, mockFindAllSkills } = vi.hoisted(() => {
return {
mockTranslateSkillFile: vi.fn().mockReturnValue({
success: true,
content: 'translated content',
filename: 'skill.md',
format: 'skill-md',
warnings: [],
incompatible: [],
errors: [],
}),
mockFindAllSkills: vi.fn().mockReturnValue([
{
name: 'test-skill',
path: '/test/project/.claude/skills/test-skill',
filename: 'test-skill.md',
},
]),
};
});
// Mock translator
vi.mock('../../translator/index', () => ({
translateSkillFile: mockTranslateSkillFile,
}));
// Mock skills module
vi.mock('../../skills', () => ({
findAllSkills: mockFindAllSkills,
}));
describe('ContextSync', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.resetAllMocks();
});
describe('detectAgents', () => {
it('should detect Claude Code agent', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('.claude')) return true;
}
return false;
});
const sync = new ContextSync('/test/project');
const agents = sync.detectAgents();
expect(agents).toContain('claude-code');
});
it('should detect Cursor agent', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('.cursor')) return true;
if (path.includes('.cursorrules')) return true;
}
return false;
});
const sync = new ContextSync('/test/project');
const agents = sync.detectAgents();
expect(agents).toContain('cursor');
});
it('should detect multiple agents', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('.claude')) return true;
if (path.includes('.cursor')) return true;
if (path.includes('.codex')) return true;
}
return false;
});
const sync = new ContextSync('/test/project');
const agents = sync.detectAgents();
expect(agents).toContain('claude-code');
expect(agents).toContain('cursor');
expect(agents).toContain('codex');
});
it('should detect Windsurf agent', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('.windsurfrules')) return true;
if (path.includes('.windsurf')) return true;
}
return false;
});
const sync = new ContextSync('/test/project');
const agents = sync.detectAgents();
expect(agents).toContain('windsurf');
});
it('should detect GitHub Copilot agent', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
// github-copilot is detected via .github/skills directory or AGENTS.md
if (path.includes('.github/skills')) return true;
}
return false;
});
const sync = new ContextSync('/test/project');
const agents = sync.detectAgents();
expect(agents).toContain('github-copilot');
});
it('should return empty array when no agents detected', () => {
vi.mocked(existsSync).mockReturnValue(false);
const sync = new ContextSync('/test/project');
const agents = sync.detectAgents();
expect(agents).toEqual([]);
});
});
describe('checkStatus', () => {
it('should return status for all agents', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('.claude/skills')) return true;
}
return false;
});
// readdirSync with withFileTypes returns entries with isDirectory method
vi.mocked(readdirSync).mockReturnValue([
{ name: 'skill-1', isDirectory: () => true },
{ name: 'skill-2', isDirectory: () => true },
] as any);
const sync = new ContextSync('/test/project');
const status = sync.checkStatus();
expect(status).toHaveProperty('claude-code');
expect(status['claude-code'].skillCount).toBe(2);
});
it('should show hasSkills true when skills exist', () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('.claude/skills')) return true;
}
return false;
});
vi.mocked(readdirSync).mockReturnValue([
{ name: 'skill-1', isDirectory: () => true },
] as any);
const sync = new ContextSync('/test/project');
const status = sync.checkStatus();
expect(status['claude-code'].hasSkills).toBe(true);
});
it('should show hasSkills false when no skills exist', () => {
vi.mocked(existsSync).mockReturnValue(false);
vi.mocked(readdirSync).mockReturnValue([]);
const sync = new ContextSync('/test/project');
const status = sync.checkStatus();
expect(status['claude-code'].hasSkills).toBe(false);
expect(status['claude-code'].skillCount).toBe(0);
});
});
describe('syncToAgent', () => {
it('should sync skills to an agent', async () => {
vi.mocked(existsSync).mockReturnValue(false);
const sync = new ContextSync('/test/project');
const result = await sync.syncToAgent('cursor', [
{ name: 'skill-1', path: '/test/skill-1' },
]);
expect(result.success).toBe(true);
expect(result.agent).toBe('cursor');
expect(result.skillsSynced).toBeGreaterThanOrEqual(0);
});
it('should skip existing skills without force flag', async () => {
vi.mocked(existsSync).mockReturnValue(true);
const sync = new ContextSync('/test/project');
const result = await sync.syncToAgent('cursor', [
{ name: 'existing-skill', path: '/test/existing-skill' },
]);
expect(result.skillsSkipped).toBeGreaterThanOrEqual(0);
expect(result.warnings.length).toBeGreaterThanOrEqual(0);
});
it('should overwrite existing skills with force flag', async () => {
vi.mocked(existsSync).mockReturnValue(true);
const sync = new ContextSync('/test/project');
const result = await sync.syncToAgent(
'cursor',
[{ name: 'existing-skill', path: '/test/existing-skill' }],
{ force: true }
);
// With force flag, skill should be synced (or skipped if translation fails)
expect(result).toBeDefined();
expect(result.agent).toBe('cursor');
});
it('should handle dry run mode', async () => {
const sync = new ContextSync('/test/project');
const result = await sync.syncToAgent(
'cursor',
[{ name: 'test-skill', path: '/test/test-skill' }],
{ dryRun: true }
);
// In dry run, files should not be written
expect(result.success).toBe(true);
// writeFileSync should not be called with actual writes in dry run
});
it('should return error for invalid agent', async () => {
const sync = new ContextSync('/test/project');
const result = await sync.syncToAgent(
'invalid-agent' as AgentType,
[{ name: 'skill', path: '/test/skill' }]
);
expect(result.errors.length).toBeGreaterThan(0);
});
});
describe('syncAll', () => {
it('should sync to all detected agents', async () => {
vi.mocked(existsSync).mockImplementation((path) => {
if (typeof path === 'string') {
if (path.includes('.claude')) return true;
if (path.includes('.cursor')) return true;
}
return false;
});
vi.mocked(readdirSync).mockReturnValue(['test-skill'] as any);
const sync = new ContextSync('/test/project');
// Mock getSourceSkills to return test skills
vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([
{ name: 'test-skill', path: '/test/project/.claude/skills/test-skill' },
]);
const report = await sync.syncAll();
expect(report.totalAgents).toBeGreaterThan(0);
expect(report.results.length).toBeGreaterThan(0);
});
it('should sync to specific agents when provided', async () => {
const sync = new ContextSync('/test/project');
// Mock getSourceSkills to return test skills
vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([
{ name: 'test-skill', path: '/test/project/.claude/skills/test-skill' },
]);
const report = await sync.syncAll({
agents: ['cursor', 'windsurf'],
});
expect(report.results.some((r) => r.agent === 'cursor')).toBe(true);
expect(report.results.some((r) => r.agent === 'windsurf')).toBe(true);
});
it('should report successful and failed agents', async () => {
const sync = new ContextSync('/test/project');
// Mock getSourceSkills to return test skills
vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([
{ name: 'test-skill', path: '/test/project/.claude/skills/test-skill' },
]);
const report = await sync.syncAll({
agents: ['claude-code', 'cursor'],
});
expect(report.totalAgents).toBe(2);
expect(report.successfulAgents).toBeGreaterThanOrEqual(0);
expect(report.totalSkills).toBeGreaterThanOrEqual(0);
});
it('should respect dry run mode for all agents', async () => {
const sync = new ContextSync('/test/project');
// Mock getSourceSkills to return test skills
vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([
{ name: 'test-skill', path: '/test/project/.claude/skills/test-skill' },
]);
const report = await sync.syncAll({
agents: ['cursor'],
dryRun: true,
});
expect(report.results[0].success).toBe(true);
});
it('should collect warnings from all agents', async () => {
vi.mocked(existsSync).mockReturnValue(true); // Skills already exist
const sync = new ContextSync('/test/project');
// Mock getSourceSkills to return test skills
vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([
{ name: 'test-skill', path: '/test/project/.claude/skills/test-skill' },
]);
const report = await sync.syncAll({
agents: ['cursor'],
});
// Should have warnings about existing skills
expect(report.results[0]).toBeDefined();
});
});
});
describe('convenience functions', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('createContextSync', () => {
it('should create a ContextSync instance', () => {
const sync = createContextSync('/test/project');
expect(sync).toBeInstanceOf(ContextSync);
});
it('should use current directory if no path provided', () => {
const sync = createContextSync();
expect(sync).toBeInstanceOf(ContextSync);
});
});
describe('syncToAllAgents', () => {
it('should sync to all agents', async () => {
vi.mocked(existsSync).mockReturnValue(false);
// Mock ContextSync.prototype.getSourceSkills for convenience function tests
const originalGetSourceSkills = ContextSync.prototype['getSourceSkills'];
ContextSync.prototype['getSourceSkills'] = vi.fn().mockReturnValue([
{ name: 'test-skill', path: '/test/project/.claude/skills/test-skill' },
]);
try {
const report = await syncToAllAgents('/test/project');
expect(report).toHaveProperty('totalAgents');
expect(report).toHaveProperty('successfulAgents');
expect(report).toHaveProperty('results');
} finally {
// Restore original method
ContextSync.prototype['getSourceSkills'] = originalGetSourceSkills;
}
});
});
describe('syncToAgent', () => {
it('should sync to a specific agent', async () => {
vi.mocked(existsSync).mockReturnValue(false);
// Mock ContextSync.prototype.getSourceSkills for convenience function tests
const originalGetSourceSkills = ContextSync.prototype['getSourceSkills'];
ContextSync.prototype['getSourceSkills'] = vi.fn().mockReturnValue([
{ name: 'test-skill', path: '/test/project/.claude/skills/test-skill' },
]);
try {
// syncToAgent(agent, projectPath?, options?)
const result = await syncToAgent('cursor', '/test/project');
expect(result.agent).toBe('cursor');
expect(result).toHaveProperty('success');
expect(result).toHaveProperty('skillsSynced');
} finally {
// Restore original method
ContextSync.prototype['getSourceSkills'] = originalGetSourceSkills;
}
});
});
});
describe('error handling', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('should handle file system errors gracefully', async () => {
// Setup: existsSync must return true for SKILL.md path
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(writeFileSync).mockImplementation(() => {
throw new Error('Permission denied');
});
const sync = new ContextSync('/test/project');
const result = await sync.syncToAgent('cursor', [
{ name: 'skill', path: '/test/skill' },
]);
// Error is caught and added to errors array
expect(result.errors.length).toBeGreaterThan(0);
expect(result.errors[0]).toContain('Failed to sync');
});
it('should continue syncing other agents if one fails', async () => {
vi.mocked(existsSync).mockReturnValue(true);
let callCount = 0;
vi.mocked(writeFileSync).mockImplementation(() => {
callCount++;
if (callCount === 1) {
throw new Error('First agent failed');
}
});
const sync = new ContextSync('/test/project');
// Mock getSourceSkills to return test skills
vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([
{ name: 'test-skill', path: '/test/project/.claude/skills/test-skill' },
]);
const report = await sync.syncAll({
agents: ['cursor', 'windsurf'],
});
// Should have results for both agents
expect(report.results.length).toBe(2);
});
it('should report translation failures as warnings', async () => {
// Setup: existsSync must return true for SKILL.md to be found
vi.mocked(existsSync).mockReturnValue(true);
// Use the hoisted mock directly
mockTranslateSkillFile.mockReturnValue({
success: false,
content: '',
filename: '',
format: 'skill-md',
warnings: [],
incompatible: [],
errors: ['Translation failed'],
});
const sync = new ContextSync('/test/project');
const result = await sync.syncToAgent('cursor', [
{ name: 'untranslatable-skill', path: '/test/skill' },
]);
// Translation failures add warnings, not errors
expect(result.skillsSkipped).toBe(1);
expect(result.warnings.length).toBeGreaterThan(0);
});
});
+784
View File
@@ -0,0 +1,784 @@
import { existsSync, readFileSync, readdirSync } from 'node:fs';
import { join, basename } from 'node:path';
import type { ProjectStack, Detection, ProjectPatterns } from './types.js';
/**
* Framework detection patterns
*/
const FRAMEWORK_PATTERNS = {
// Frontend frameworks
react: {
dependencies: ['react', 'react-dom'],
files: [],
category: 'frameworks' as const,
tags: ['react', 'frontend', 'ui'],
},
nextjs: {
dependencies: ['next'],
files: ['next.config.js', 'next.config.mjs', 'next.config.ts'],
category: 'frameworks' as const,
tags: ['nextjs', 'react', 'ssr', 'frontend'],
},
vue: {
dependencies: ['vue'],
files: [],
category: 'frameworks' as const,
tags: ['vue', 'frontend', 'ui'],
},
nuxt: {
dependencies: ['nuxt'],
files: ['nuxt.config.js', 'nuxt.config.ts'],
category: 'frameworks' as const,
tags: ['nuxt', 'vue', 'ssr', 'frontend'],
},
angular: {
dependencies: ['@angular/core'],
files: ['angular.json'],
category: 'frameworks' as const,
tags: ['angular', 'frontend', 'ui'],
},
svelte: {
dependencies: ['svelte'],
files: ['svelte.config.js'],
category: 'frameworks' as const,
tags: ['svelte', 'frontend', 'ui'],
},
remix: {
dependencies: ['@remix-run/react'],
files: ['remix.config.js'],
category: 'frameworks' as const,
tags: ['remix', 'react', 'ssr', 'frontend'],
},
astro: {
dependencies: ['astro'],
files: ['astro.config.mjs', 'astro.config.ts'],
category: 'frameworks' as const,
tags: ['astro', 'static', 'frontend'],
},
solid: {
dependencies: ['solid-js'],
files: [],
category: 'frameworks' as const,
tags: ['solid', 'frontend', 'ui'],
},
// Backend frameworks
express: {
dependencies: ['express'],
files: [],
category: 'frameworks' as const,
tags: ['express', 'nodejs', 'api', 'backend'],
},
fastify: {
dependencies: ['fastify'],
files: [],
category: 'frameworks' as const,
tags: ['fastify', 'nodejs', 'api', 'backend'],
},
hono: {
dependencies: ['hono'],
files: [],
category: 'frameworks' as const,
tags: ['hono', 'edge', 'api', 'backend'],
},
koa: {
dependencies: ['koa'],
files: [],
category: 'frameworks' as const,
tags: ['koa', 'nodejs', 'api', 'backend'],
},
nestjs: {
dependencies: ['@nestjs/core'],
files: ['nest-cli.json'],
category: 'frameworks' as const,
tags: ['nestjs', 'nodejs', 'api', 'backend'],
},
// Mobile
'react-native': {
dependencies: ['react-native'],
files: ['metro.config.js', 'app.json'],
category: 'frameworks' as const,
tags: ['react-native', 'mobile', 'ios', 'android'],
},
expo: {
dependencies: ['expo'],
files: ['app.json', 'expo.json'],
category: 'frameworks' as const,
tags: ['expo', 'react-native', 'mobile'],
},
// Desktop
electron: {
dependencies: ['electron'],
files: ['electron.js', 'electron-builder.json'],
category: 'frameworks' as const,
tags: ['electron', 'desktop'],
},
tauri: {
dependencies: ['@tauri-apps/api'],
files: ['tauri.conf.json', 'src-tauri'],
category: 'frameworks' as const,
tags: ['tauri', 'desktop', 'rust'],
},
};
/**
* Library detection patterns
*/
const LIBRARY_PATTERNS = {
// State management
redux: {
dependencies: ['redux', '@reduxjs/toolkit'],
category: 'libraries' as const,
tags: ['redux', 'state-management'],
},
zustand: {
dependencies: ['zustand'],
category: 'libraries' as const,
tags: ['zustand', 'state-management'],
},
jotai: {
dependencies: ['jotai'],
category: 'libraries' as const,
tags: ['jotai', 'state-management'],
},
recoil: {
dependencies: ['recoil'],
category: 'libraries' as const,
tags: ['recoil', 'state-management'],
},
mobx: {
dependencies: ['mobx'],
category: 'libraries' as const,
tags: ['mobx', 'state-management'],
},
// Data fetching
tanstack: {
dependencies: ['@tanstack/react-query', '@tanstack/query-core'],
category: 'libraries' as const,
tags: ['tanstack', 'data-fetching', 'caching'],
},
swr: {
dependencies: ['swr'],
category: 'libraries' as const,
tags: ['swr', 'data-fetching'],
},
trpc: {
dependencies: ['@trpc/client', '@trpc/server'],
category: 'libraries' as const,
tags: ['trpc', 'api', 'typescript'],
},
graphql: {
dependencies: ['graphql', '@apollo/client', 'urql'],
category: 'libraries' as const,
tags: ['graphql', 'api'],
},
// UI Components
'shadcn-ui': {
dependencies: ['@radix-ui/react-slot'],
files: ['components.json'],
category: 'libraries' as const,
tags: ['shadcn', 'ui', 'components'],
},
'material-ui': {
dependencies: ['@mui/material'],
category: 'libraries' as const,
tags: ['mui', 'material', 'ui', 'components'],
},
'chakra-ui': {
dependencies: ['@chakra-ui/react'],
category: 'libraries' as const,
tags: ['chakra', 'ui', 'components'],
},
'ant-design': {
dependencies: ['antd'],
category: 'libraries' as const,
tags: ['antd', 'ui', 'components'],
},
// Form handling
'react-hook-form': {
dependencies: ['react-hook-form'],
category: 'libraries' as const,
tags: ['forms', 'validation'],
},
formik: {
dependencies: ['formik'],
category: 'libraries' as const,
tags: ['forms', 'validation'],
},
zod: {
dependencies: ['zod'],
category: 'libraries' as const,
tags: ['validation', 'schema', 'typescript'],
},
// Animation
'framer-motion': {
dependencies: ['framer-motion'],
category: 'libraries' as const,
tags: ['animation', 'motion'],
},
};
/**
* Styling detection patterns
*/
const STYLING_PATTERNS = {
tailwindcss: {
dependencies: ['tailwindcss'],
files: ['tailwind.config.js', 'tailwind.config.ts', 'tailwind.config.cjs'],
category: 'styling' as const,
tags: ['tailwind', 'css', 'utility-first'],
},
'styled-components': {
dependencies: ['styled-components'],
category: 'styling' as const,
tags: ['styled-components', 'css-in-js'],
},
emotion: {
dependencies: ['@emotion/react', '@emotion/styled'],
category: 'styling' as const,
tags: ['emotion', 'css-in-js'],
},
sass: {
dependencies: ['sass', 'node-sass'],
category: 'styling' as const,
tags: ['sass', 'scss', 'css'],
},
less: {
dependencies: ['less'],
category: 'styling' as const,
tags: ['less', 'css'],
},
'css-modules': {
files: ['*.module.css', '*.module.scss'],
category: 'styling' as const,
tags: ['css-modules', 'css'],
},
};
/**
* Testing detection patterns
*/
const TESTING_PATTERNS = {
jest: {
dependencies: ['jest'],
files: ['jest.config.js', 'jest.config.ts'],
category: 'testing' as const,
tags: ['jest', 'testing', 'unit-testing'],
},
vitest: {
dependencies: ['vitest'],
files: ['vitest.config.ts', 'vitest.config.js'],
category: 'testing' as const,
tags: ['vitest', 'testing', 'unit-testing'],
},
playwright: {
dependencies: ['@playwright/test'],
files: ['playwright.config.ts', 'playwright.config.js'],
category: 'testing' as const,
tags: ['playwright', 'e2e', 'testing'],
},
cypress: {
dependencies: ['cypress'],
files: ['cypress.config.ts', 'cypress.config.js', 'cypress.json'],
category: 'testing' as const,
tags: ['cypress', 'e2e', 'testing'],
},
mocha: {
dependencies: ['mocha'],
category: 'testing' as const,
tags: ['mocha', 'testing'],
},
'testing-library': {
dependencies: ['@testing-library/react', '@testing-library/vue'],
category: 'testing' as const,
tags: ['testing-library', 'testing'],
},
};
/**
* Database detection patterns
*/
const DATABASE_PATTERNS = {
prisma: {
dependencies: ['@prisma/client', 'prisma'],
files: ['prisma/schema.prisma'],
category: 'databases' as const,
tags: ['prisma', 'orm', 'database'],
},
drizzle: {
dependencies: ['drizzle-orm'],
files: ['drizzle.config.ts'],
category: 'databases' as const,
tags: ['drizzle', 'orm', 'database'],
},
typeorm: {
dependencies: ['typeorm'],
category: 'databases' as const,
tags: ['typeorm', 'orm', 'database'],
},
mongoose: {
dependencies: ['mongoose'],
category: 'databases' as const,
tags: ['mongoose', 'mongodb', 'database'],
},
supabase: {
dependencies: ['@supabase/supabase-js'],
category: 'databases' as const,
tags: ['supabase', 'postgres', 'database', 'auth'],
},
firebase: {
dependencies: ['firebase', 'firebase-admin'],
category: 'databases' as const,
tags: ['firebase', 'database', 'auth'],
},
};
/**
* Tool detection patterns
*/
const TOOL_PATTERNS = {
eslint: {
dependencies: ['eslint'],
files: ['.eslintrc', '.eslintrc.js', '.eslintrc.json', 'eslint.config.js'],
category: 'tools' as const,
tags: ['eslint', 'linting'],
},
prettier: {
dependencies: ['prettier'],
files: ['.prettierrc', '.prettierrc.js', 'prettier.config.js'],
category: 'tools' as const,
tags: ['prettier', 'formatting'],
},
biome: {
dependencies: ['@biomejs/biome'],
files: ['biome.json'],
category: 'tools' as const,
tags: ['biome', 'linting', 'formatting'],
},
husky: {
dependencies: ['husky'],
files: ['.husky'],
category: 'tools' as const,
tags: ['husky', 'git-hooks'],
},
'lint-staged': {
dependencies: ['lint-staged'],
category: 'tools' as const,
tags: ['lint-staged', 'git-hooks'],
},
turbo: {
dependencies: ['turbo'],
files: ['turbo.json'],
category: 'tools' as const,
tags: ['turbo', 'monorepo', 'build'],
},
nx: {
dependencies: ['nx'],
files: ['nx.json'],
category: 'tools' as const,
tags: ['nx', 'monorepo', 'build'],
},
docker: {
files: ['Dockerfile', 'docker-compose.yml', 'docker-compose.yaml'],
category: 'tools' as const,
tags: ['docker', 'containers'],
},
};
/**
* Project Detector
*
* Analyzes a project directory to detect the technology stack,
* frameworks, libraries, and patterns used.
*/
export class ProjectDetector {
private projectPath: string;
private packageJson: Record<string, unknown> | null = null;
private files: Set<string> = new Set();
constructor(projectPath: string) {
this.projectPath = projectPath;
}
/**
* Analyze the project and return detected stack
*/
analyze(): ProjectStack {
// Load package.json if exists
this.loadPackageJson();
// Scan root files
this.scanFiles();
// Detect everything
const stack: ProjectStack = {
languages: this.detectLanguages(),
frameworks: this.detectFromPatterns(FRAMEWORK_PATTERNS),
libraries: this.detectFromPatterns(LIBRARY_PATTERNS),
styling: this.detectFromPatterns(STYLING_PATTERNS),
testing: this.detectFromPatterns(TESTING_PATTERNS),
databases: this.detectFromPatterns(DATABASE_PATTERNS),
tools: this.detectFromPatterns(TOOL_PATTERNS),
runtime: this.detectRuntime(),
};
return stack;
}
/**
* Detect project patterns and conventions
*/
detectPatterns(): ProjectPatterns {
const patterns: ProjectPatterns = {};
// Detect component style
if (this.hasFile('*.tsx') || this.hasFile('*.jsx')) {
// Check for class components vs functional
patterns.components = 'functional'; // Modern default
}
// Detect state management
const deps = this.getDependencies();
if (deps.has('zustand')) patterns.stateManagement = 'zustand';
else if (deps.has('@reduxjs/toolkit') || deps.has('redux')) patterns.stateManagement = 'redux';
else if (deps.has('jotai')) patterns.stateManagement = 'jotai';
else if (deps.has('recoil')) patterns.stateManagement = 'recoil';
else if (deps.has('mobx')) patterns.stateManagement = 'mobx';
// Detect API style
if (deps.has('@trpc/client')) patterns.apiStyle = 'trpc';
else if (deps.has('graphql') || deps.has('@apollo/client')) patterns.apiStyle = 'graphql';
else if (deps.has('next') && this.hasFile('app/**/actions.ts')) patterns.apiStyle = 'server-actions';
else patterns.apiStyle = 'rest';
// Detect styling
if (deps.has('tailwindcss')) patterns.styling = 'tailwind';
else if (deps.has('styled-components')) patterns.styling = 'styled-components';
else if (deps.has('@emotion/react')) patterns.styling = 'emotion';
else if (this.hasFile('*.module.css')) patterns.styling = 'css-modules';
// Detect testing
if (deps.has('vitest')) patterns.testing = 'vitest';
else if (deps.has('jest')) patterns.testing = 'jest';
else if (deps.has('@playwright/test')) patterns.testing = 'playwright';
else if (deps.has('cypress')) patterns.testing = 'cypress';
// Detect linting
if (deps.has('@biomejs/biome')) patterns.linting = 'biome';
else if (deps.has('eslint')) patterns.linting = 'eslint';
// Detect formatting
if (deps.has('@biomejs/biome')) patterns.formatting = 'biome';
else if (deps.has('prettier')) patterns.formatting = 'prettier';
return patterns;
}
/**
* Detect project type
*/
detectProjectType(): string {
const deps = this.getDependencies();
// Check for specific project types
if (deps.has('react-native') || deps.has('expo')) return 'mobile';
if (deps.has('electron') || deps.has('@tauri-apps/api')) return 'desktop';
if (deps.has('next') || deps.has('nuxt') || deps.has('remix')) return 'web-app';
if (deps.has('express') || deps.has('fastify') || deps.has('hono')) return 'api';
if (deps.has('commander') || deps.has('clipanion') || deps.has('yargs')) return 'cli';
// Check for library indicators
if (this.hasFile('rollup.config.js') || this.hasFile('tsup.config.ts')) return 'library';
// Default
if (deps.has('react') || deps.has('vue') || deps.has('svelte')) return 'web-app';
return 'unknown';
}
/**
* Get project name
*/
getProjectName(): string {
if (this.packageJson && typeof this.packageJson.name === 'string') {
return this.packageJson.name;
}
return basename(this.projectPath);
}
/**
* Get project description
*/
getProjectDescription(): string | undefined {
if (this.packageJson && typeof this.packageJson.description === 'string') {
return this.packageJson.description;
}
return undefined;
}
// Private helpers
private loadPackageJson(): void {
const packageJsonPath = join(this.projectPath, 'package.json');
if (existsSync(packageJsonPath)) {
try {
const content = readFileSync(packageJsonPath, 'utf-8');
this.packageJson = JSON.parse(content);
} catch {
this.packageJson = null;
}
}
}
private scanFiles(): void {
try {
const entries = readdirSync(this.projectPath, { withFileTypes: true });
for (const entry of entries) {
this.files.add(entry.name);
if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
// Scan one level deep for common config locations
try {
const subEntries = readdirSync(join(this.projectPath, entry.name));
for (const subEntry of subEntries) {
this.files.add(`${entry.name}/${subEntry}`);
}
} catch {
// Ignore permission errors
}
}
}
} catch {
// Ignore errors
}
}
private getDependencies(): Set<string> {
const deps = new Set<string>();
if (!this.packageJson) return deps;
const dependencies = this.packageJson.dependencies as Record<string, string> | undefined;
const devDependencies = this.packageJson.devDependencies as Record<string, string> | undefined;
if (dependencies) {
for (const dep of Object.keys(dependencies)) {
deps.add(dep);
}
}
if (devDependencies) {
for (const dep of Object.keys(devDependencies)) {
deps.add(dep);
}
}
return deps;
}
private getVersion(depName: string): string | undefined {
if (!this.packageJson) return undefined;
const dependencies = this.packageJson.dependencies as Record<string, string> | undefined;
const devDependencies = this.packageJson.devDependencies as Record<string, string> | undefined;
const version = dependencies?.[depName] || devDependencies?.[depName];
if (version) {
// Clean version string (remove ^, ~, etc.)
return version.replace(/^[\^~>=<]+/, '');
}
return undefined;
}
private hasFile(pattern: string): boolean {
if (pattern.includes('*')) {
// Simple glob matching
const regex = new RegExp(pattern.replace(/\*/g, '.*'));
for (const file of this.files) {
if (regex.test(file)) return true;
}
return false;
}
return this.files.has(pattern);
}
private detectLanguages(): Detection[] {
const languages: Detection[] = [];
// TypeScript
if (this.hasFile('tsconfig.json') || this.files.has('*.ts')) {
const tsVersion = this.getVersion('typescript');
languages.push({
name: 'typescript',
version: tsVersion,
confidence: 100,
source: 'tsconfig.json',
});
}
// JavaScript (if no TypeScript, or alongside)
if (this.hasFile('jsconfig.json') || (this.packageJson && !this.hasFile('tsconfig.json'))) {
languages.push({
name: 'javascript',
confidence: 90,
source: 'package.json',
});
}
// Python
if (this.hasFile('pyproject.toml') || this.hasFile('requirements.txt')) {
languages.push({
name: 'python',
confidence: 100,
source: 'pyproject.toml',
});
}
// Rust
if (this.hasFile('Cargo.toml')) {
languages.push({
name: 'rust',
confidence: 100,
source: 'Cargo.toml',
});
}
// Go
if (this.hasFile('go.mod')) {
languages.push({
name: 'go',
confidence: 100,
source: 'go.mod',
});
}
return languages;
}
private detectRuntime(): Detection[] {
const runtime: Detection[] = [];
// Node.js
if (this.packageJson) {
const engines = this.packageJson.engines as Record<string, string> | undefined;
const nodeVersion = engines?.node;
runtime.push({
name: 'nodejs',
version: nodeVersion?.replace(/[>=<^~]+/g, ''),
confidence: 100,
source: 'package.json',
});
}
// Bun
if (this.hasFile('bun.lockb') || this.hasFile('bunfig.toml')) {
runtime.push({
name: 'bun',
confidence: 100,
source: 'bun.lockb',
});
}
// Deno
if (this.hasFile('deno.json') || this.hasFile('deno.jsonc')) {
runtime.push({
name: 'deno',
confidence: 100,
source: 'deno.json',
});
}
return runtime;
}
private detectFromPatterns(
patterns: Record<string, { dependencies?: string[]; files?: string[]; category: keyof ProjectStack; tags?: string[] }>
): Detection[] {
const detected: Detection[] = [];
const deps = this.getDependencies();
for (const [name, pattern] of Object.entries(patterns)) {
let found = false;
let source: string | undefined;
// Check dependencies
if (pattern.dependencies) {
for (const dep of pattern.dependencies) {
if (deps.has(dep)) {
found = true;
source = 'package.json';
break;
}
}
}
// Check files
if (!found && pattern.files) {
for (const file of pattern.files) {
if (this.hasFile(file)) {
found = true;
source = file;
break;
}
}
}
if (found) {
const version = pattern.dependencies ? this.getVersion(pattern.dependencies[0]) : undefined;
detected.push({
name,
version,
confidence: 100,
source,
});
}
}
return detected;
}
}
/**
* Analyze a project and return the detected stack
*/
export function analyzeProject(projectPath: string): ProjectStack {
const detector = new ProjectDetector(projectPath);
return detector.analyze();
}
/**
* Get all relevant tags from a project stack
*/
export function getStackTags(stack: ProjectStack): string[] {
const tags = new Set<string>();
const addTags = (detections: Detection[], patterns: Record<string, { tags?: string[] }>) => {
for (const detection of detections) {
const pattern = patterns[detection.name];
if (pattern?.tags) {
for (const tag of pattern.tags) {
tags.add(tag);
}
} else {
tags.add(detection.name);
}
}
};
// Add language tags
for (const lang of stack.languages) {
tags.add(lang.name);
}
// Add framework tags
addTags(stack.frameworks, FRAMEWORK_PATTERNS);
addTags(stack.libraries, LIBRARY_PATTERNS);
addTags(stack.styling, STYLING_PATTERNS);
addTags(stack.testing, TESTING_PATTERNS);
addTags(stack.databases, DATABASE_PATTERNS);
return Array.from(tags);
}
+53
View File
@@ -0,0 +1,53 @@
// Types
export {
type DependencyInfo,
type Detection,
type ProjectStack,
type ProjectPatterns,
type SkillPreferences,
type AgentConfig,
type ProjectContext,
type DetectionSource,
type ContextSyncOptions,
type ContextExportOptions,
type ContextImportOptions,
CONTEXT_FILE,
CONTEXT_DIR,
PROJECT_TYPE_HINTS,
} from './types.js';
// Detector
export {
ProjectDetector,
analyzeProject,
getStackTags,
} from './detector.js';
// Manager
export {
ContextManager,
createContextManager,
loadContext,
initContext,
} from './manager.js';
// Sync
export {
ContextSync,
createContextSync,
syncToAllAgents,
syncToAgent,
type SyncResult,
type SyncReport,
} from './sync.js';
// Loader (Smart Context Loading)
export {
ContextLoader,
createContextLoader,
estimateTokens,
DEFAULT_CONTEXT_CATEGORIES,
type ContextCategory,
type ContextLoadOptions,
type LoadedContext,
} from './loader.js';
+331
View File
@@ -0,0 +1,331 @@
/**
* Context Loader
*
* Smart context loading with token budgets and category-based loading.
*/
import { existsSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
/**
* Context category with size limits
*/
export interface ContextCategory {
/** Category name */
name: string;
/** Maximum tokens for this category */
maxTokens: number;
/** Whether to always load this category */
alwaysLoad: boolean;
/** File path (relative to project) */
file?: string;
/** Inline content */
content?: string;
}
/**
* Context loading options
*/
export interface ContextLoadOptions {
/** Total token budget */
totalBudget?: number;
/** Categories to load (load all if not specified) */
categories?: string[];
/** Whether to warn when approaching budget limits */
warnOnBudgetLimit?: boolean;
}
/**
* Loaded context result
*/
export interface LoadedContext {
/** All loaded content combined */
content: string;
/** Total tokens used */
totalTokens: number;
/** Budget remaining */
budgetRemaining: number;
/** Categories loaded */
categoriesLoaded: string[];
/** Categories skipped (due to budget or not found) */
categoriesSkipped: string[];
/** Warnings generated */
warnings: string[];
/** Whether budget is near limit (>50% used) */
nearBudgetLimit: boolean;
/** Whether context is degraded (>70% used) */
contextDegraded: boolean;
}
/**
* Default context categories
*/
export const DEFAULT_CONTEXT_CATEGORIES: ContextCategory[] = [
{
name: 'project',
maxTokens: 2000,
alwaysLoad: true,
file: '.skillkit/context.yaml',
},
{
name: 'requirements',
maxTokens: 5000,
alwaysLoad: false,
file: 'REQUIREMENTS.md',
},
{
name: 'decisions',
maxTokens: 1000,
alwaysLoad: false,
file: '.skillkit/decisions.yaml',
},
{
name: 'readme',
maxTokens: 3000,
alwaysLoad: false,
file: 'README.md',
},
];
/**
* Rough estimate of tokens from text
* (approximation: ~4 characters per token for English text)
*/
export function estimateTokens(text: string): number {
return Math.ceil(text.length / 4);
}
/**
* Context Loader class
*/
export class ContextLoader {
private projectPath: string;
private categories: ContextCategory[];
private defaultBudget: number;
constructor(projectPath: string, options?: { categories?: ContextCategory[]; defaultBudget?: number }) {
this.projectPath = projectPath;
this.categories = options?.categories || DEFAULT_CONTEXT_CATEGORIES;
this.defaultBudget = options?.defaultBudget || 32000; // Default ~32k tokens
}
/**
* Load context based on options
*/
load(options: ContextLoadOptions = {}): LoadedContext {
const totalBudget = options.totalBudget || this.defaultBudget;
const requestedCategories = options.categories;
const result: LoadedContext = {
content: '',
totalTokens: 0,
budgetRemaining: totalBudget,
categoriesLoaded: [],
categoriesSkipped: [],
warnings: [],
nearBudgetLimit: false,
contextDegraded: false,
};
const contentParts: string[] = [];
// First pass: load alwaysLoad categories
for (const category of this.categories) {
if (!category.alwaysLoad) continue;
if (requestedCategories && !requestedCategories.includes(category.name)) continue;
this.loadCategory(category, result, contentParts, totalBudget);
}
// Second pass: load requested categories
for (const category of this.categories) {
if (category.alwaysLoad) continue; // Already loaded
if (requestedCategories && !requestedCategories.includes(category.name)) continue;
this.loadCategory(category, result, contentParts, totalBudget);
}
// Combine content
result.content = contentParts.join('\n\n---\n\n');
// Check budget status
const usagePercent = (result.totalTokens / totalBudget) * 100;
result.nearBudgetLimit = usagePercent >= 50;
result.contextDegraded = usagePercent >= 70;
// Add warnings for budget limits
if (result.contextDegraded && options.warnOnBudgetLimit !== false) {
result.warnings.push(
`Context usage at ${Math.round(usagePercent)}% - quality may degrade. Consider spawning a fresh agent.`
);
} else if (result.nearBudgetLimit && options.warnOnBudgetLimit !== false) {
result.warnings.push(`Context usage at ${Math.round(usagePercent)}% - approaching limit.`);
}
return result;
}
/**
* Load a single category
*/
private loadCategory(
category: ContextCategory,
result: LoadedContext,
contentParts: string[],
totalBudget: number
): void {
let content: string | null = null;
// Load from file
if (category.file) {
const filePath = join(this.projectPath, category.file);
if (existsSync(filePath)) {
try {
content = readFileSync(filePath, 'utf-8');
} catch {
result.categoriesSkipped.push(category.name);
return;
}
}
}
// Use inline content if no file
if (!content && category.content) {
content = category.content;
}
if (!content) {
result.categoriesSkipped.push(category.name);
return;
}
// Estimate tokens
const tokens = estimateTokens(content);
// Check category limit
if (tokens > category.maxTokens) {
// Truncate to category limit
const truncateChars = category.maxTokens * 4;
content = content.slice(0, truncateChars) + '\n\n[... content truncated ...]';
result.warnings.push(
`Category "${category.name}" truncated to ${category.maxTokens} tokens`
);
}
// Check total budget
const truncatedTokens = estimateTokens(content);
if (result.totalTokens + truncatedTokens > totalBudget) {
// Skip if would exceed budget
result.categoriesSkipped.push(category.name);
result.warnings.push(
`Category "${category.name}" skipped - would exceed budget`
);
return;
}
// Add to result
contentParts.push(`# ${category.name.toUpperCase()}\n\n${content}`);
result.totalTokens += truncatedTokens;
result.budgetRemaining = totalBudget - result.totalTokens;
result.categoriesLoaded.push(category.name);
}
/**
* Get category by name
*/
getCategory(name: string): ContextCategory | undefined {
return this.categories.find((c) => c.name === name);
}
/**
* Add a custom category
*/
addCategory(category: ContextCategory): void {
const existing = this.categories.findIndex((c) => c.name === category.name);
if (existing >= 0) {
this.categories[existing] = category;
} else {
this.categories.push(category);
}
}
/**
* Remove a category
*/
removeCategory(name: string): void {
this.categories = this.categories.filter((c) => c.name !== name);
}
/**
* Get estimated context size for categories
*/
estimateSize(categoryNames?: string[]): { category: string; tokens: number; available: boolean }[] {
const estimates: { category: string; tokens: number; available: boolean }[] = [];
for (const category of this.categories) {
if (categoryNames && !categoryNames.includes(category.name)) continue;
let tokens = 0;
let available = false;
if (category.file) {
const filePath = join(this.projectPath, category.file);
if (existsSync(filePath)) {
try {
const stat = statSync(filePath);
tokens = Math.ceil(stat.size / 4); // Rough estimate
available = true;
} catch {
// File not accessible
}
}
} else if (category.content) {
tokens = estimateTokens(category.content);
available = true;
}
estimates.push({
category: category.name,
tokens: Math.min(tokens, category.maxTokens),
available,
});
}
return estimates;
}
/**
* Check if context would exceed budget threshold
*/
wouldExceedThreshold(additionalTokens: number, threshold: number = 0.7): boolean {
const currentTokens = this.load().totalTokens;
const newTotal = currentTokens + additionalTokens;
return newTotal / this.defaultBudget > threshold;
}
/**
* Suggest spawning fresh agent if context is degraded
*/
shouldSpawnFreshAgent(): { should: boolean; reason?: string } {
const context = this.load();
if (context.contextDegraded) {
return {
should: true,
reason: `Context at ${Math.round((context.totalTokens / this.defaultBudget) * 100)}% capacity`,
};
}
return { should: false };
}
}
/**
* Create a context loader
*/
export function createContextLoader(
projectPath: string,
options?: { categories?: ContextCategory[]; defaultBudget?: number }
): ContextLoader {
return new ContextLoader(projectPath, options);
}
+468
View File
@@ -0,0 +1,468 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import {
type ProjectContext,
type ProjectStack,
type SkillPreferences,
type AgentConfig,
type ContextExportOptions,
type ContextImportOptions,
type Detection,
ProjectContext as ProjectContextSchema,
CONTEXT_FILE,
CONTEXT_DIR,
} from './types.js';
import { ProjectDetector, getStackTags } from './detector.js';
import type { AgentType } from '../types.js';
/**
* Context Manager
*
* Handles loading, saving, and managing project contexts.
* The context is stored in .skillkit/context.yaml
*/
export class ContextManager {
private projectPath: string;
private context: ProjectContext | null = null;
constructor(projectPath: string = process.cwd()) {
this.projectPath = projectPath;
}
/**
* Get the context file path
*/
getContextPath(): string {
return join(this.projectPath, CONTEXT_FILE);
}
/**
* Check if context exists
*/
exists(): boolean {
return existsSync(this.getContextPath());
}
/**
* Load context from file
*/
load(): ProjectContext | null {
const contextPath = this.getContextPath();
if (!existsSync(contextPath)) {
return null;
}
try {
const content = readFileSync(contextPath, 'utf-8');
const data = parseYaml(content);
const parsed = ProjectContextSchema.safeParse(data);
if (parsed.success) {
this.context = parsed.data;
return this.context;
}
// Return raw data if schema validation fails but file exists
console.warn('Context file exists but failed schema validation');
return null;
} catch (error) {
console.warn('Failed to load context:', error);
return null;
}
}
/**
* Save context to file
*/
save(context: ProjectContext): void {
const contextPath = this.getContextPath();
const contextDir = join(this.projectPath, CONTEXT_DIR);
// Ensure directory exists
if (!existsSync(contextDir)) {
mkdirSync(contextDir, { recursive: true });
}
// Update timestamp
context.updatedAt = new Date().toISOString();
// Stringify with nice formatting
const content = stringifyYaml(context, {
lineWidth: 0,
defaultKeyType: 'PLAIN',
});
writeFileSync(contextPath, content, 'utf-8');
this.context = context;
}
/**
* Initialize a new context from project detection
*/
init(options: { force?: boolean; skipDetection?: boolean } = {}): ProjectContext {
// Check if context already exists
if (this.exists() && !options.force) {
const existing = this.load();
if (existing) {
return existing;
}
}
// Detect project
const detector = new ProjectDetector(this.projectPath);
const stack = options.skipDetection ? this.getEmptyStack() : detector.analyze();
const patterns = options.skipDetection ? {} : detector.detectPatterns();
const projectType = options.skipDetection ? 'unknown' : detector.detectProjectType();
const projectName = detector.getProjectName();
const projectDescription = detector.getProjectDescription();
// Create new context
const context: ProjectContext = {
version: 1,
project: {
name: projectName,
description: projectDescription,
type: projectType,
path: this.projectPath,
},
stack,
patterns,
skills: {
installed: [],
recommended: [],
excluded: [],
autoSync: true,
securityLevel: 'medium',
testingRequired: false,
},
agents: {
primary: undefined,
detected: [],
synced: [],
disabled: [],
},
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
// Save and return
this.save(context);
return context;
}
/**
* Update context with new detection
*/
refresh(): ProjectContext {
const existing = this.load();
const detector = new ProjectDetector(this.projectPath);
const stack = detector.analyze();
const patterns = detector.detectPatterns();
const projectType = detector.detectProjectType();
if (existing) {
// Merge with existing
const merged: ProjectContext = {
...existing,
stack,
patterns,
project: {
...existing.project,
type: projectType,
},
updatedAt: new Date().toISOString(),
};
this.save(merged);
return merged;
}
// No existing context, initialize new
return this.init();
}
/**
* Get current context (load if not loaded)
*/
get(): ProjectContext | null {
if (this.context) {
return this.context;
}
return this.load();
}
/**
* Update skills in context
*/
updateSkills(skills: Partial<SkillPreferences>): void {
const context = this.get();
if (!context) {
throw new Error('No context found. Run `skillkit context init` first.');
}
context.skills = {
...context.skills,
...skills,
} as SkillPreferences;
this.save(context);
}
/**
* Update agents in context
*/
updateAgents(agents: Partial<AgentConfig>): void {
const context = this.get();
if (!context) {
throw new Error('No context found. Run `skillkit context init` first.');
}
context.agents = {
...context.agents,
...agents,
} as AgentConfig;
this.save(context);
}
/**
* Set primary agent
*/
setPrimaryAgent(agent: AgentType): void {
this.updateAgents({ primary: agent });
}
/**
* Add agent to synced list
*/
addSyncedAgent(agent: AgentType): void {
const context = this.get();
if (!context) {
throw new Error('No context found');
}
const synced = new Set(context.agents?.synced || []);
synced.add(agent);
this.updateAgents({ synced: Array.from(synced) });
}
/**
* Remove agent from synced list
*/
removeSyncedAgent(agent: AgentType): void {
const context = this.get();
if (!context) {
throw new Error('No context found');
}
const synced = new Set(context.agents?.synced || []);
synced.delete(agent);
this.updateAgents({ synced: Array.from(synced) });
}
/**
* Add installed skill
*/
addInstalledSkill(skillName: string): void {
const context = this.get();
if (!context) return;
const installed = new Set(context.skills?.installed || []);
installed.add(skillName);
this.updateSkills({ installed: Array.from(installed) });
}
/**
* Remove installed skill
*/
removeInstalledSkill(skillName: string): void {
const context = this.get();
if (!context) return;
const installed = new Set(context.skills?.installed || []);
installed.delete(skillName);
this.updateSkills({ installed: Array.from(installed) });
}
/**
* Export context to file
*/
export(options: ContextExportOptions = {}): string {
const context = this.get();
if (!context) {
throw new Error('No context found');
}
// Clone and optionally filter
const exported = { ...context };
if (!options.includeSkills) {
delete (exported as Record<string, unknown>).skills;
}
if (!options.includeAgents) {
delete (exported as Record<string, unknown>).agents;
}
// Format
if (options.format === 'json') {
return JSON.stringify(exported, null, 2);
}
return stringifyYaml(exported, {
lineWidth: 0,
defaultKeyType: 'PLAIN',
});
}
/**
* Import context from content
*/
import(content: string, options: ContextImportOptions = {}): ProjectContext {
// Parse content
let data: unknown;
try {
// Try JSON first
data = JSON.parse(content);
} catch {
// Try YAML
data = parseYaml(content);
}
const parsed = ProjectContextSchema.safeParse(data);
if (!parsed.success) {
throw new Error(`Invalid context format: ${parsed.error.message}`);
}
const imported = parsed.data;
if (options.merge && this.exists()) {
const existing = this.load()!;
const merged = this.mergeContexts(existing, imported);
this.save(merged);
return merged;
}
if (!options.overwrite && this.exists()) {
throw new Error('Context already exists. Use --merge or --overwrite.');
}
this.save(imported);
return imported;
}
/**
* Merge two contexts
*/
private mergeContexts(existing: ProjectContext, imported: ProjectContext): ProjectContext {
return {
version: 1,
project: {
...existing.project,
...imported.project,
},
stack: this.mergeStacks(existing.stack, imported.stack),
patterns: {
...existing.patterns,
...imported.patterns,
},
skills: {
installed: [...new Set([...(existing.skills?.installed || []), ...(imported.skills?.installed || [])])],
recommended: [...new Set([...(existing.skills?.recommended || []), ...(imported.skills?.recommended || [])])],
excluded: [...new Set([...(existing.skills?.excluded || []), ...(imported.skills?.excluded || [])])],
autoSync: imported.skills?.autoSync ?? existing.skills?.autoSync ?? true,
securityLevel: imported.skills?.securityLevel ?? existing.skills?.securityLevel ?? 'medium',
testingRequired: imported.skills?.testingRequired ?? existing.skills?.testingRequired ?? false,
},
agents: {
primary: imported.agents?.primary ?? existing.agents?.primary,
detected: [...new Set([...(existing.agents?.detected || []), ...(imported.agents?.detected || [])])],
synced: [...new Set([...(existing.agents?.synced || []), ...(imported.agents?.synced || [])])],
disabled: [...new Set([...(existing.agents?.disabled || []), ...(imported.agents?.disabled || [])])],
},
createdAt: existing.createdAt,
updatedAt: new Date().toISOString(),
};
}
/**
* Merge two stacks
*/
private mergeStacks(existing: ProjectStack, imported: ProjectStack): ProjectStack {
const mergeArrays = (a: Detection[], b: Detection[]): Detection[] => {
const names = new Set(a.map((item) => item.name));
const result: Detection[] = [...a];
for (const item of b) {
if (!names.has(item.name)) {
result.push(item);
}
}
return result;
};
return {
languages: mergeArrays(existing.languages, imported.languages),
frameworks: mergeArrays(existing.frameworks, imported.frameworks),
libraries: mergeArrays(existing.libraries, imported.libraries),
styling: mergeArrays(existing.styling, imported.styling),
testing: mergeArrays(existing.testing, imported.testing),
databases: mergeArrays(existing.databases, imported.databases),
tools: mergeArrays(existing.tools, imported.tools),
runtime: mergeArrays(existing.runtime, imported.runtime),
};
}
/**
* Get empty stack
*/
private getEmptyStack(): ProjectStack {
return {
languages: [],
frameworks: [],
libraries: [],
styling: [],
testing: [],
databases: [],
tools: [],
runtime: [],
};
}
/**
* Get recommended skill tags based on stack
*/
getRecommendedTags(): string[] {
const context = this.get();
if (!context) return [];
return getStackTags(context.stack);
}
}
/**
* Create a context manager for the current directory
*/
export function createContextManager(projectPath?: string): ContextManager {
return new ContextManager(projectPath);
}
/**
* Load context from the current directory
*/
export function loadContext(projectPath?: string): ProjectContext | null {
const manager = new ContextManager(projectPath);
return manager.load();
}
/**
* Initialize context in the current directory
*/
export function initContext(projectPath?: string, options?: { force?: boolean }): ProjectContext {
const manager = new ContextManager(projectPath);
return manager.init(options);
}
+386
View File
@@ -0,0 +1,386 @@
import { existsSync, writeFileSync, mkdirSync, copyFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import type { AgentType } from '../types.js';
import type { ContextSyncOptions } from './types.js';
import { ContextManager } from './manager.js';
import { translateSkillFile } from '../translator/index.js';
import { findAllSkills } from '../skills.js';
/**
* Result of a sync operation
*/
export interface SyncResult {
success: boolean;
agent: AgentType;
skillsSynced: number;
skillsSkipped: number;
errors: string[];
warnings: string[];
files: string[];
}
/**
* Overall sync report
*/
export interface SyncReport {
totalAgents: number;
successfulAgents: number;
totalSkills: number;
results: SyncResult[];
}
/**
* Agent directory configuration
*/
const AGENT_DIRS: Record<AgentType, { skillsDir: string; configFile: string }> = {
'claude-code': { skillsDir: '.claude/skills', configFile: 'AGENTS.md' },
'cursor': { skillsDir: '.cursor/skills', configFile: '.cursorrules' },
'codex': { skillsDir: '.codex/skills', configFile: 'AGENTS.md' },
'gemini-cli': { skillsDir: '.gemini/skills', configFile: 'GEMINI.md' },
'opencode': { skillsDir: '.opencode/skills', configFile: 'AGENTS.md' },
'antigravity': { skillsDir: '.antigravity/skills', configFile: 'AGENTS.md' },
'amp': { skillsDir: '.agents/skills', configFile: 'AGENTS.md' },
'clawdbot': { skillsDir: 'skills', configFile: 'AGENTS.md' },
'droid': { skillsDir: '.factory/skills', configFile: 'AGENTS.md' },
'github-copilot': { skillsDir: '.github/skills', configFile: 'AGENTS.md' },
'goose': { skillsDir: '.goose/skills', configFile: 'AGENTS.md' },
'kilo': { skillsDir: '.kilocode/skills', configFile: 'AGENTS.md' },
'kiro-cli': { skillsDir: '.kiro/skills', configFile: 'AGENTS.md' },
'roo': { skillsDir: '.roo/skills', configFile: 'AGENTS.md' },
'trae': { skillsDir: '.trae/skills', configFile: 'AGENTS.md' },
'windsurf': { skillsDir: '.windsurf/skills', configFile: 'AGENTS.md' },
'universal': { skillsDir: '.agent/skills', configFile: 'AGENTS.md' },
};
/**
* Context Sync
*
* Handles syncing skills across multiple AI agents.
* Skills are translated to the appropriate format for each agent.
*/
export class ContextSync {
private projectPath: string;
private contextManager: ContextManager;
constructor(projectPath: string = process.cwd()) {
this.projectPath = projectPath;
this.contextManager = new ContextManager(projectPath);
}
/**
* Detect which agents are installed/configured on the system
*/
detectAgents(): AgentType[] {
const detected: AgentType[] = [];
for (const [agent, config] of Object.entries(AGENT_DIRS)) {
const skillsPath = join(this.projectPath, config.skillsDir);
const configPath = join(this.projectPath, config.configFile);
// Check if either skills directory or config file exists
if (existsSync(skillsPath) || existsSync(configPath)) {
detected.push(agent as AgentType);
}
}
// Also check for global indicators
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
if (homeDir) {
// Check for Claude Code
if (existsSync(join(homeDir, '.claude'))) {
if (!detected.includes('claude-code')) detected.push('claude-code');
}
// Check for Cursor
if (existsSync(join(homeDir, '.cursor'))) {
if (!detected.includes('cursor')) detected.push('cursor');
}
}
return detected;
}
/**
* Get agents to sync to based on context
*/
getTargetAgents(options: ContextSyncOptions = {}): AgentType[] {
// If specific agents provided, use those
if (options.agents?.length) {
return options.agents;
}
// Load context
const context = this.contextManager.get();
if (context?.agents?.synced?.length) {
return context.agents.synced as AgentType[];
}
// Auto-detect
return this.detectAgents();
}
/**
* Sync all skills to all target agents
*/
async syncAll(options: ContextSyncOptions = {}): Promise<SyncReport> {
const targetAgents = this.getTargetAgents(options);
const results: SyncResult[] = [];
// Get all installed skills from primary agent or first available
const skills = this.getSourceSkills();
for (const agent of targetAgents) {
const result = await this.syncToAgent(agent, skills, options);
results.push(result);
}
// Update context with synced agents
if (!options.dryRun) {
this.contextManager.updateAgents({
detected: this.detectAgents(),
synced: targetAgents,
});
}
return {
totalAgents: targetAgents.length,
successfulAgents: results.filter((r) => r.success).length,
totalSkills: skills.length,
results,
};
}
/**
* Sync skills to a specific agent
*/
async syncToAgent(
agent: AgentType,
skills?: Array<{ name: string; path: string }>,
options: ContextSyncOptions = {}
): Promise<SyncResult> {
const result: SyncResult = {
success: true,
agent,
skillsSynced: 0,
skillsSkipped: 0,
errors: [],
warnings: [],
files: [],
};
// Get skills if not provided
const sourceSkills = skills || this.getSourceSkills();
// Get target directory
const agentConfig = AGENT_DIRS[agent];
if (!agentConfig) {
result.success = false;
result.errors.push(`Unknown agent: ${agent}`);
return result;
}
const targetDir = join(this.projectPath, agentConfig.skillsDir);
// Create target directory if not dry run
if (!options.dryRun && !existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
// Sync each skill
for (const skill of sourceSkills) {
try {
const skillResult = await this.syncSkill(skill, agent, targetDir, options);
if (skillResult.synced) {
result.skillsSynced++;
result.files.push(skillResult.file!);
} else {
result.skillsSkipped++;
if (skillResult.warning) {
result.warnings.push(skillResult.warning);
}
}
} catch (error) {
result.errors.push(`Failed to sync ${skill.name}: ${error}`);
result.skillsSkipped++;
}
}
if (result.errors.length > 0) {
result.success = false;
}
return result;
}
/**
* Sync a single skill to an agent
*/
private async syncSkill(
skill: { name: string; path: string },
agent: AgentType,
targetDir: string,
options: ContextSyncOptions
): Promise<{ synced: boolean; file?: string; warning?: string }> {
const skillMdPath = join(skill.path, 'SKILL.md');
if (!existsSync(skillMdPath)) {
return { synced: false, warning: `No SKILL.md found for ${skill.name}` };
}
// Translate skill to target format
const translation = translateSkillFile(skillMdPath, agent, {
addMetadata: true,
});
if (!translation.success) {
return { synced: false, warning: `Translation failed for ${skill.name}` };
}
// Determine output path
const targetSkillDir = join(targetDir, skill.name);
const outputPath = join(targetSkillDir, translation.filename);
// Check if file exists and skip if not forcing
if (existsSync(outputPath) && !options.force) {
return { synced: false, warning: `${skill.name} already exists (use --force to overwrite)` };
}
// Write file (unless dry run)
if (!options.dryRun) {
if (!existsSync(targetSkillDir)) {
mkdirSync(targetSkillDir, { recursive: true });
}
writeFileSync(outputPath, translation.content, 'utf-8');
// Copy additional skill assets if they exist
await this.copySkillAssets(skill.path, targetSkillDir);
}
return { synced: true, file: outputPath };
}
/**
* Copy additional skill assets (references, scripts, etc.)
*/
private async copySkillAssets(sourcePath: string, targetPath: string): Promise<void> {
const assetDirs = ['references', 'scripts', 'assets', 'templates'];
for (const assetDir of assetDirs) {
const sourceAssetDir = join(sourcePath, assetDir);
if (existsSync(sourceAssetDir)) {
const targetAssetDir = join(targetPath, assetDir);
if (!existsSync(targetAssetDir)) {
mkdirSync(targetAssetDir, { recursive: true });
}
// Copy files
try {
const files = readdirSync(sourceAssetDir);
for (const file of files) {
const sourcefile = join(sourceAssetDir, file);
const targetFile = join(targetAssetDir, file);
copyFileSync(sourcefile, targetFile);
}
} catch {
// Ignore copy errors
}
}
}
}
/**
* Get source skills to sync
*/
private getSourceSkills(): Array<{ name: string; path: string }> {
const context = this.contextManager.get();
const primaryAgent = context?.agents?.primary as AgentType | undefined;
// Search directories based on primary agent or common locations
const searchDirs: string[] = [];
if (primaryAgent && AGENT_DIRS[primaryAgent]) {
searchDirs.push(join(this.projectPath, AGENT_DIRS[primaryAgent].skillsDir));
}
// Add common skill locations
const commonDirs = [
'.claude/skills',
'.cursor/skills',
'.agent/skills',
'skills',
];
for (const dir of commonDirs) {
const fullPath = join(this.projectPath, dir);
if (!searchDirs.includes(fullPath) && existsSync(fullPath)) {
searchDirs.push(fullPath);
}
}
// Find all skills
const skills = findAllSkills(searchDirs);
return skills.map((s) => ({ name: s.name, path: s.path }));
}
/**
* Check sync status - which agents have which skills
*/
checkStatus(): Record<AgentType, { hasSkills: boolean; skillCount: number; skills: string[] }> {
const status: Record<string, { hasSkills: boolean; skillCount: number; skills: string[] }> = {};
for (const [agent, config] of Object.entries(AGENT_DIRS)) {
const skillsPath = join(this.projectPath, config.skillsDir);
const skills: string[] = [];
if (existsSync(skillsPath)) {
try {
const entries = readdirSync(skillsPath, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
skills.push(entry.name);
}
}
} catch {
// Ignore errors
}
}
status[agent] = {
hasSkills: skills.length > 0,
skillCount: skills.length,
skills,
};
}
return status as Record<AgentType, { hasSkills: boolean; skillCount: number; skills: string[] }>;
}
}
/**
* Create a context sync instance
*/
export function createContextSync(projectPath?: string): ContextSync {
return new ContextSync(projectPath);
}
/**
* Sync skills to all detected agents
*/
export async function syncToAllAgents(
projectPath?: string,
options?: ContextSyncOptions
): Promise<SyncReport> {
const sync = new ContextSync(projectPath);
return sync.syncAll(options);
}
/**
* Sync skills to a specific agent
*/
export async function syncToAgent(
agent: AgentType,
projectPath?: string,
options?: ContextSyncOptions
): Promise<SyncResult> {
const sync = new ContextSync(projectPath);
return sync.syncToAgent(agent, undefined, options);
}
+172
View File
@@ -0,0 +1,172 @@
import { z } from 'zod';
import type { AgentType } from '../types.js';
/**
* Detected dependency with version
*/
export const DependencyInfo = z.object({
name: z.string(),
version: z.string().optional(),
dev: z.boolean().default(false),
});
export type DependencyInfo = z.infer<typeof DependencyInfo>;
/**
* Detection result with confidence
*/
export const Detection = z.object({
name: z.string(),
version: z.string().optional(),
confidence: z.number().min(0).max(100).default(100),
source: z.string().optional(), // Where it was detected from
});
export type Detection = z.infer<typeof Detection>;
/**
* Project stack detection results
*/
export const ProjectStack = z.object({
languages: z.array(Detection).default([]),
frameworks: z.array(Detection).default([]),
libraries: z.array(Detection).default([]),
styling: z.array(Detection).default([]),
testing: z.array(Detection).default([]),
databases: z.array(Detection).default([]),
tools: z.array(Detection).default([]),
runtime: z.array(Detection).default([]),
});
export type ProjectStack = z.infer<typeof ProjectStack>;
/**
* Project patterns and conventions
*/
export const ProjectPatterns = z.object({
components: z.string().optional(), // 'functional', 'class', 'mixed'
stateManagement: z.string().optional(), // 'redux', 'zustand', 'context', etc.
apiStyle: z.string().optional(), // 'rest', 'graphql', 'trpc', 'server-actions'
styling: z.string().optional(), // 'css-modules', 'tailwind', 'styled-components'
testing: z.string().optional(), // 'jest', 'vitest', 'playwright'
linting: z.string().optional(), // 'eslint', 'biome'
formatting: z.string().optional(), // 'prettier', 'biome'
});
export type ProjectPatterns = z.infer<typeof ProjectPatterns>;
/**
* Skill preferences for the project
*/
export const SkillPreferences = z.object({
installed: z.array(z.string()).default([]),
recommended: z.array(z.string()).default([]),
excluded: z.array(z.string()).default([]),
autoSync: z.boolean().default(true),
securityLevel: z.enum(['low', 'medium', 'high']).default('medium'),
testingRequired: z.boolean().default(false),
});
export type SkillPreferences = z.infer<typeof SkillPreferences>;
/**
* Agent configuration for the project
*/
export const AgentConfig = z.object({
primary: z.string().optional(), // Primary agent
detected: z.array(z.string()).default([]), // Auto-detected agents
synced: z.array(z.string()).default([]), // Agents to sync skills to
disabled: z.array(z.string()).default([]), // Agents to skip
});
export type AgentConfig = z.infer<typeof AgentConfig>;
/**
* Full project context
*/
export const ProjectContext = z.object({
version: z.literal(1),
project: z.object({
name: z.string(),
description: z.string().optional(),
type: z.string().optional(), // 'web-app', 'cli', 'library', 'api', etc.
path: z.string().optional(),
}),
stack: ProjectStack,
patterns: ProjectPatterns.optional(),
skills: SkillPreferences.optional(),
agents: AgentConfig.optional(),
createdAt: z.string().datetime().optional(),
updatedAt: z.string().datetime().optional(),
});
export type ProjectContext = z.infer<typeof ProjectContext>;
/**
* Context file location
*/
export const CONTEXT_FILE = '.skillkit/context.yaml';
export const CONTEXT_DIR = '.skillkit';
/**
* Detection source types
*/
export type DetectionSource =
| 'package.json'
| 'tsconfig.json'
| 'pyproject.toml'
| 'Cargo.toml'
| 'go.mod'
| 'pubspec.yaml'
| 'folder-structure'
| 'config-file'
| 'manual';
/**
* Project type hints based on detection
*/
export const PROJECT_TYPE_HINTS: Record<string, string[]> = {
'web-app': ['react', 'vue', 'angular', 'svelte', 'nextjs', 'nuxt', 'remix'],
'api': ['express', 'fastify', 'koa', 'hono', 'fastapi', 'flask', 'django'],
'cli': ['commander', 'yargs', 'clipanion', 'clap', 'cobra'],
'library': ['rollup', 'esbuild', 'tsup', 'unbuild'],
'mobile': ['react-native', 'expo', 'flutter', 'ionic'],
'desktop': ['electron', 'tauri'],
};
/**
* Framework detection patterns
*/
export interface FrameworkPattern {
name: string;
indicators: {
dependencies?: string[];
devDependencies?: string[];
files?: string[];
configFiles?: string[];
};
category: keyof ProjectStack;
relatedTags?: string[];
}
/**
* Context sync options
*/
export interface ContextSyncOptions {
agents?: AgentType[];
force?: boolean;
dryRun?: boolean;
skillsOnly?: boolean;
}
/**
* Context export options
*/
export interface ContextExportOptions {
output?: string;
format?: 'yaml' | 'json';
includeSkills?: boolean;
includeAgents?: boolean;
}
/**
* Context import options
*/
export interface ContextImportOptions {
merge?: boolean;
overwrite?: boolean;
skipDetection?: boolean;
}
+348
View File
@@ -0,0 +1,348 @@
/**
* Agent Execution Module
*
* Handles real execution of skills through various AI agent CLIs.
*/
import { spawn, type SpawnOptions } from 'node:child_process';
import type { AgentType } from '../types.js';
/**
* Agent CLI configuration
*/
export interface AgentCLIConfig {
/** Agent type */
type: AgentType;
/** CLI command name */
command: string;
/** Whether the agent supports CLI execution */
supportsCLI: boolean;
/** Arguments to pass the prompt/skill content */
promptArgs?: string[];
/** Arguments for non-interactive mode */
nonInteractiveArgs?: string[];
/** Environment variables needed */
envVars?: Record<string, string>;
/** How to check if agent is installed */
checkCommand?: string;
}
/**
* Execution result from an agent
*/
export interface AgentExecutionResult {
success: boolean;
output: string;
error?: string;
exitCode: number;
duration: number;
}
/**
* Agent CLI configurations
*/
export const AGENT_CLI_CONFIGS: AgentCLIConfig[] = [
{
type: 'claude-code',
command: 'claude',
supportsCLI: true,
promptArgs: ['--print', '-p'],
nonInteractiveArgs: ['--no-input'],
checkCommand: 'claude --version',
},
{
type: 'codex',
command: 'codex',
supportsCLI: true,
promptArgs: ['-p'],
checkCommand: 'codex --version',
},
{
type: 'gemini-cli',
command: 'gemini',
supportsCLI: true,
promptArgs: [],
checkCommand: 'gemini --version',
},
{
type: 'opencode',
command: 'opencode',
supportsCLI: true,
promptArgs: ['--prompt'],
checkCommand: 'opencode --version',
},
{
type: 'goose',
command: 'goose',
supportsCLI: true,
promptArgs: ['run'],
checkCommand: 'goose --version',
},
// IDE-based agents (no CLI execution)
{
type: 'cursor',
command: 'cursor',
supportsCLI: false,
},
{
type: 'windsurf',
command: 'windsurf',
supportsCLI: false,
},
{
type: 'github-copilot',
command: 'gh copilot',
supportsCLI: false,
},
];
/**
* Get CLI config for an agent
*/
export function getAgentCLIConfig(agentType: AgentType): AgentCLIConfig | undefined {
return AGENT_CLI_CONFIGS.find((c) => c.type === agentType);
}
/**
* Check if an agent CLI is available
*/
export async function isAgentCLIAvailable(agentType: AgentType): Promise<boolean> {
const config = getAgentCLIConfig(agentType);
if (!config || !config.supportsCLI) return false;
try {
// Check if command exists
const checkCmd = config.checkCommand || `which ${config.command}`;
const result = await executeCommand(checkCmd.split(' ')[0], checkCmd.split(' ').slice(1), {
timeout: 5000,
});
return result.exitCode === 0;
} catch {
return false;
}
}
/**
* Get all available CLI agents
*/
export async function getAvailableCLIAgents(): Promise<AgentType[]> {
const available: AgentType[] = [];
for (const config of AGENT_CLI_CONFIGS) {
if (config.supportsCLI && (await isAgentCLIAvailable(config.type))) {
available.push(config.type);
}
}
return available;
}
/**
* Execute a skill using an agent CLI
*/
export async function executeWithAgent(
agentType: AgentType,
prompt: string,
options: {
cwd?: string;
timeout?: number;
env?: Record<string, string>;
} = {}
): Promise<AgentExecutionResult> {
const config = getAgentCLIConfig(agentType);
if (!config) {
return {
success: false,
output: '',
error: `Unknown agent type: ${agentType}`,
exitCode: 1,
duration: 0,
};
}
if (!config.supportsCLI) {
return {
success: false,
output: '',
error: `Agent ${agentType} does not support CLI execution. Please use IDE integration.`,
exitCode: 1,
duration: 0,
};
}
const isAvailable = await isAgentCLIAvailable(agentType);
if (!isAvailable) {
return {
success: false,
output: '',
error: `Agent CLI '${config.command}' is not installed or not in PATH`,
exitCode: 1,
duration: 0,
};
}
// Build command arguments
const args: string[] = [...(config.promptArgs || [])];
// For Claude Code, use --print mode with the prompt
if (agentType === 'claude-code') {
args.push(prompt);
} else {
// For other agents, pass prompt as argument
args.push(prompt);
}
// Add non-interactive flags if available
if (config.nonInteractiveArgs) {
args.push(...config.nonInteractiveArgs);
}
return executeCommand(config.command, args, {
cwd: options.cwd || process.cwd(),
timeout: options.timeout || 300000, // 5 minutes default
env: {
...process.env,
...config.envVars,
...options.env,
},
});
}
/**
* Execute a command and capture output
*/
async function executeCommand(
command: string,
args: string[],
options: {
cwd?: string;
timeout?: number;
env?: NodeJS.ProcessEnv;
} = {}
): Promise<AgentExecutionResult> {
return new Promise((resolve) => {
const startTime = Date.now();
let stdout = '';
let stderr = '';
let timedOut = false;
const spawnOptions: SpawnOptions = {
cwd: options.cwd,
env: options.env as NodeJS.ProcessEnv,
// shell: false (default) - prevents shell injection when passing untrusted input
};
const child = spawn(command, args, spawnOptions);
// Set up timeout
const timeoutId = options.timeout
? setTimeout(() => {
timedOut = true;
child.kill('SIGTERM');
}, options.timeout)
: null;
child.stdout?.on('data', (data) => {
stdout += data.toString();
});
child.stderr?.on('data', (data) => {
stderr += data.toString();
});
child.on('error', (error) => {
if (timeoutId) clearTimeout(timeoutId);
resolve({
success: false,
output: stdout,
error: error.message,
exitCode: 1,
duration: Date.now() - startTime,
});
});
child.on('close', (code) => {
if (timeoutId) clearTimeout(timeoutId);
resolve({
success: code === 0 && !timedOut,
output: stdout,
error: timedOut ? 'Execution timed out' : stderr || undefined,
exitCode: code ?? 1,
duration: Date.now() - startTime,
});
});
});
}
/**
* Format skill content as a prompt for an agent
*/
export function formatSkillAsPrompt(
skillName: string,
skillContent: string,
taskDescription?: string
): string {
let prompt = `Execute the following skill: ${skillName}\n\n`;
if (taskDescription) {
prompt += `Task: ${taskDescription}\n\n`;
}
prompt += `Skill Content:\n${skillContent}`;
return prompt;
}
/**
* Agent execution strategy
*/
export type ExecutionStrategy = 'cli' | 'ide' | 'api' | 'manual';
/**
* Get recommended execution strategy for an agent
*/
export function getExecutionStrategy(agentType: AgentType): ExecutionStrategy {
const config = getAgentCLIConfig(agentType);
if (config?.supportsCLI) {
return 'cli';
}
// IDE-based agents
if (['cursor', 'windsurf', 'github-copilot', 'kilo'].includes(agentType)) {
return 'ide';
}
return 'manual';
}
/**
* Get instructions for manual/IDE execution
*/
export function getManualExecutionInstructions(
agentType: AgentType,
skillPath: string
): string {
const strategy = getExecutionStrategy(agentType);
if (strategy === 'ide') {
return `
To execute this skill with ${agentType}:
1. Open your project in ${agentType}
2. The skill has been synced to the agent's skills directory
3. Open the AI assistant/chat
4. Reference the skill or ask the assistant to follow the instructions
Skill location: ${skillPath}
`;
}
return `
To execute this skill manually:
1. Open the skill file: ${skillPath}
2. Copy the skill content
3. Paste it into your AI coding assistant
4. Follow the instructions in the skill
`;
}
+611
View File
@@ -0,0 +1,611 @@
/**
* Skill Execution Engine
*
* Executes skills with task-based orchestration, verification, and state management.
*/
import { execSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import type {
ExecutableSkill,
ExecutableTask,
ExecutionOptions,
TaskExecutionResult,
SkillExecutionResult,
CheckpointHandler,
CheckpointResponse,
ExecutionTaskStatus,
} from './types.js';
import { SessionManager } from '../session/manager.js';
import type { SessionTask } from '../session/types.js';
/**
* Progress event for execution
*/
export interface ExecutionProgressEvent {
type: 'task_start' | 'task_complete' | 'checkpoint' | 'verification' | 'complete';
taskId?: string;
taskName?: string;
taskIndex?: number;
totalTasks?: number;
status?: ExecutionTaskStatus | 'paused' | 'cancelled';
message?: string;
error?: string;
}
/**
* Progress callback type
*/
export type ExecutionProgressCallback = (event: ExecutionProgressEvent) => void;
/**
* Skill Execution Engine
*/
export class SkillExecutionEngine {
private projectPath: string;
private sessionManager: SessionManager;
private checkpointHandler?: CheckpointHandler;
private onProgress?: ExecutionProgressCallback;
constructor(
projectPath: string,
options?: {
checkpointHandler?: CheckpointHandler;
onProgress?: ExecutionProgressCallback;
}
) {
this.projectPath = projectPath;
this.sessionManager = new SessionManager(projectPath);
this.checkpointHandler = options?.checkpointHandler;
this.onProgress = options?.onProgress;
}
/**
* Execute a skill
*/
async execute(
skill: ExecutableSkill,
options: ExecutionOptions = {}
): Promise<SkillExecutionResult> {
const startTime = new Date();
const tasks = skill.tasks || [];
// Handle dry run
if (options.dryRun) {
return this.createDryRunResult(skill);
}
// Check if there's an existing paused execution for this skill
const existingState = this.sessionManager.get();
if (existingState?.currentExecution?.skillName === skill.name) {
if (existingState.currentExecution.status === 'paused') {
// Resume from paused state
return this.resumeExecution(skill, options);
}
}
// Start new execution
const sessionTasks: Omit<SessionTask, 'status'>[] = tasks.map((task, index) => ({
id: task.id || `task-${index}`,
name: task.name,
type: task.type === 'auto' ? 'auto' : task.type,
}));
this.sessionManager.startExecution(skill.name, skill.source, sessionTasks);
const taskResults: TaskExecutionResult[] = [];
let overallStatus: 'completed' | 'failed' | 'cancelled' | 'paused' = 'completed';
let overallError: string | undefined;
// Execute tasks
for (let i = 0; i < tasks.length; i++) {
const task = tasks[i];
this.onProgress?.({
type: 'task_start',
taskId: task.id,
taskName: task.name,
taskIndex: i,
totalTasks: tasks.length,
});
// Handle checkpoints
if (task.type !== 'auto') {
const checkpointResult = await this.handleCheckpoint(task, {
skillName: skill.name,
taskIndex: i,
totalTasks: tasks.length,
});
if (!checkpointResult.continue) {
overallStatus = 'paused';
this.sessionManager.pause();
break;
}
// For decision checkpoints, record the decision
if (task.type === 'checkpoint:decision' && checkpointResult.selectedOption) {
this.sessionManager.recordDecision(
`${skill.name}:${task.id}`,
checkpointResult.selectedOption,
skill.name
);
}
}
// Execute the task
const taskResult = await this.executeTask(task, skill, options);
taskResults.push(taskResult);
this.sessionManager.updateTask(task.id || `task-${i}`, {
status: taskResult.status === 'completed' ? 'completed' : 'failed',
output: taskResult.output,
error: taskResult.error,
filesModified: taskResult.filesModified,
commitSha: taskResult.commitSha,
});
this.onProgress?.({
type: 'task_complete',
taskId: task.id,
taskName: task.name,
taskIndex: i,
totalTasks: tasks.length,
status: taskResult.status,
error: taskResult.error,
});
// Handle task failure
if (taskResult.status === 'failed') {
if (!options.continueOnError) {
overallStatus = 'failed';
overallError = taskResult.error;
break;
}
}
// Run verification if enabled
if (options.verify && task.verify) {
const verificationPassed = await this.runVerification(task, taskResult);
if (!verificationPassed && !options.continueOnError) {
overallStatus = 'failed';
overallError = 'Verification failed';
break;
}
}
}
const endTime = new Date();
// Complete the execution
if (overallStatus !== 'paused') {
this.sessionManager.completeExecution(overallStatus, overallError);
}
const result: SkillExecutionResult = {
skillName: skill.name,
skillSource: skill.source,
status: overallStatus,
startedAt: startTime.toISOString(),
completedAt: endTime.toISOString(),
durationMs: endTime.getTime() - startTime.getTime(),
tasks: taskResults,
filesModified: Array.from(new Set(taskResults.flatMap((t) => t.filesModified || []))),
commits: taskResults.map((t) => t.commitSha).filter((sha): sha is string => !!sha),
error: overallError,
};
const statusMessages: Record<'completed' | 'failed' | 'cancelled' | 'paused', string> = {
completed: 'Skill execution completed',
paused: 'Skill execution paused',
failed: overallError || 'Skill execution failed',
cancelled: 'Skill execution cancelled',
};
this.onProgress?.({
type: 'complete',
status: overallStatus,
message: statusMessages[overallStatus],
});
return result;
}
/**
* Resume a paused execution
*/
private async resumeExecution(
skill: ExecutableSkill,
options: ExecutionOptions
): Promise<SkillExecutionResult> {
const state = this.sessionManager.get();
if (!state?.currentExecution) {
throw new Error('No execution to resume');
}
this.sessionManager.resume();
const execution = state.currentExecution;
const tasks = skill.tasks || [];
const taskResults: TaskExecutionResult[] = [];
let overallStatus: 'completed' | 'failed' | 'cancelled' | 'paused' = 'completed';
let overallError: string | undefined;
// Find where to resume from
const startIndex = execution.currentStep;
for (let i = startIndex; i < tasks.length; i++) {
const task = tasks[i];
this.onProgress?.({
type: 'task_start',
taskId: task.id,
taskName: task.name,
taskIndex: i,
totalTasks: tasks.length,
});
// Handle checkpoints (same as in execute)
if (task.type !== 'auto') {
const checkpointResult = await this.handleCheckpoint(task, {
skillName: skill.name,
taskIndex: i,
totalTasks: tasks.length,
});
if (!checkpointResult.continue) {
overallStatus = 'paused';
this.sessionManager.pause();
break;
}
// For decision checkpoints, record the decision
if (task.type === 'checkpoint:decision' && checkpointResult.selectedOption) {
this.sessionManager.recordDecision(
`${skill.name}:${task.id}`,
checkpointResult.selectedOption,
skill.name
);
}
}
const taskResult = await this.executeTask(task, skill, options);
taskResults.push(taskResult);
this.sessionManager.updateTask(task.id || `task-${i}`, {
status: taskResult.status === 'completed' ? 'completed' : 'failed',
output: taskResult.output,
error: taskResult.error,
filesModified: taskResult.filesModified,
commitSha: taskResult.commitSha,
});
// Emit task_complete progress event (matching execute behavior)
this.onProgress?.({
type: 'task_complete',
taskId: task.id,
taskName: task.name,
taskIndex: i,
totalTasks: tasks.length,
status: taskResult.status,
error: taskResult.error,
});
// Handle task failure
if (taskResult.status === 'failed') {
if (!options.continueOnError) {
overallStatus = 'failed';
overallError = taskResult.error;
break;
}
}
// Run verification if enabled (matching execute behavior)
if (options.verify && task.verify) {
const verificationPassed = await this.runVerification(task, taskResult);
if (!verificationPassed && !options.continueOnError) {
overallStatus = 'failed';
overallError = 'Verification failed';
break;
}
}
}
// Only complete execution if not paused
if (overallStatus !== 'paused') {
this.sessionManager.completeExecution(overallStatus, overallError);
}
return {
skillName: skill.name,
skillSource: skill.source,
status: overallStatus,
startedAt: execution.startedAt,
completedAt: new Date().toISOString(),
durationMs: Date.now() - new Date(execution.startedAt).getTime(),
tasks: taskResults,
filesModified: Array.from(new Set(taskResults.flatMap((t) => t.filesModified || []))),
commits: taskResults.map((t) => t.commitSha).filter((sha): sha is string => !!sha),
error: overallError,
};
}
/**
* Execute a single task
*/
private async executeTask(
task: ExecutableTask,
_skill: ExecutableSkill,
_options: ExecutionOptions
): Promise<TaskExecutionResult> {
const startTime = new Date();
const taskId = task.id || randomUUID();
try {
// For now, we simulate task execution
// In a real implementation, this would integrate with the AI agent
// to execute the task action based on the skill content
// Simulate some work
await new Promise((resolve) => setTimeout(resolve, 100));
const endTime = new Date();
return {
taskId,
taskName: task.name,
status: 'completed',
startedAt: startTime.toISOString(),
completedAt: endTime.toISOString(),
durationMs: endTime.getTime() - startTime.getTime(),
output: `Task "${task.name}" completed successfully`,
filesModified: task.files,
};
} catch (error) {
const endTime = new Date();
return {
taskId,
taskName: task.name,
status: 'failed',
startedAt: startTime.toISOString(),
completedAt: endTime.toISOString(),
durationMs: endTime.getTime() - startTime.getTime(),
error: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Handle a checkpoint
*/
private async handleCheckpoint(
task: ExecutableTask,
context: { skillName: string; taskIndex: number; totalTasks: number }
): Promise<CheckpointResponse> {
this.onProgress?.({
type: 'checkpoint',
taskId: task.id,
taskName: task.name,
taskIndex: context.taskIndex,
totalTasks: context.totalTasks,
message: `Checkpoint: ${task.type}`,
});
if (this.checkpointHandler) {
return this.checkpointHandler(task, context);
}
// Default: auto-continue for non-decision checkpoints
if (task.type === 'checkpoint:decision') {
// Use first option if no handler
return {
continue: true,
selectedOption: task.options?.[0],
};
}
return { continue: true };
}
/**
* Check if a regex pattern is potentially dangerous (ReDoS-vulnerable)
* Rejects patterns with nested quantifiers and other known problematic constructs
*/
private isUnsafeRegexPattern(pattern: string): boolean {
// Detect nested quantifiers like (a+)+, (a*)+, (a+)*, (a*)*
// These are the primary cause of catastrophic backtracking
const nestedQuantifierPattern = /\([^)]*[+*][^)]*\)[+*?]/;
if (nestedQuantifierPattern.test(pattern)) {
return true;
}
// Detect overlapping alternations with quantifiers like (a|a)+
const overlappingAlternation = /\([^|)]*\|[^|)]*\)[+*]/;
if (overlappingAlternation.test(pattern)) {
return true;
}
// Detect excessive quantifiers (more than 3 quantifiers in a row-ish)
const quantifierCount = (pattern.match(/[+*?]|\{\d+/g) || []).length;
if (quantifierCount > 10) {
return true;
}
// Detect very long character classes which can be slow
const longCharClass = /\[[^\]]{50,}\]/;
if (longCharClass.test(pattern)) {
return true;
}
return false;
}
/**
* Safely test a regex pattern with ReDoS prevention
*
* This method validates patterns before execution to prevent catastrophic backtracking.
* Note: This cannot guarantee protection against all ReDoS patterns, but catches common ones.
*/
private safeRegexTest(pattern: string, input: string, _timeoutMs = 1000): boolean {
// Strict length limits to prevent excessive processing
if (pattern.length > 200 || input.length > 50000) {
console.warn(`Regex test skipped: pattern or input too long`);
return false;
}
// Reject patterns known to cause ReDoS
if (this.isUnsafeRegexPattern(pattern)) {
console.warn(`Regex pattern rejected as potentially unsafe: ${pattern.slice(0, 50)}...`);
return false;
}
try {
const regex = new RegExp(pattern);
return regex.test(input);
} catch {
// Invalid regex pattern
return false;
}
}
/**
* Run verification for a task
*
* SECURITY NOTE: Verification commands are executed from skill configuration.
* Only run skills from trusted sources. Commands run with the same privileges
* as the skillkit process.
*/
private async runVerification(
task: ExecutableTask,
result: TaskExecutionResult
): Promise<boolean> {
if (!task.verify) {
return true;
}
const verificationResults = {
automated: [] as { rule: string; passed: boolean; output?: string }[],
human: [] as { description: string; passed: boolean }[],
};
// Run automated verification
if (task.verify.automated) {
for (const rule of task.verify.automated) {
if (rule.command) {
try {
// SECURITY: Commands are from skill config - only run trusted skills
const output = execSync(rule.command, {
cwd: this.projectPath,
encoding: 'utf-8',
timeout: 30000,
});
let passed = true;
if (rule.expect) {
if (rule.expect === 'success') {
passed = true;
} else if (rule.expect.startsWith('contains:')) {
const expected = rule.expect.slice(9);
passed = output.includes(expected);
} else if (rule.expect.startsWith('matches:')) {
const pattern = rule.expect.slice(8);
// Use safe regex test to prevent ReDoS
passed = this.safeRegexTest(pattern, output);
}
}
verificationResults.automated.push({
rule: rule.command,
passed,
output,
});
this.onProgress?.({
type: 'verification',
taskId: task.id,
taskName: task.name,
message: `Verification ${passed ? 'passed' : 'failed'}: ${rule.command}`,
});
if (!passed) {
return false;
}
} catch (error) {
verificationResults.automated.push({
rule: rule.command,
passed: false,
output: error instanceof Error ? error.message : String(error),
});
return false;
}
}
}
}
// Human verification would be handled by checkpoint handler
result.verificationResults = verificationResults;
return true;
}
/**
* Create a dry run result
*/
private createDryRunResult(skill: ExecutableSkill): SkillExecutionResult {
const tasks = skill.tasks || [];
return {
skillName: skill.name,
skillSource: skill.source,
status: 'completed',
startedAt: new Date().toISOString(),
completedAt: new Date().toISOString(),
durationMs: 0,
tasks: tasks.map((task) => ({
taskId: task.id || randomUUID(),
taskName: task.name,
status: 'skipped' as ExecutionTaskStatus,
startedAt: new Date().toISOString(),
completedAt: new Date().toISOString(),
durationMs: 0,
output: '[Dry run - not executed]',
})),
filesModified: [],
commits: [],
};
}
/**
* Pause current execution
*/
pause(): boolean {
return this.sessionManager.pause();
}
/**
* Check if execution is paused
*/
isPaused(): boolean {
return this.sessionManager.isPaused();
}
/**
* Get session manager
*/
getSessionManager(): SessionManager {
return this.sessionManager;
}
}
/**
* Create a new skill execution engine
*/
export function createExecutionEngine(
projectPath: string,
options?: {
checkpointHandler?: CheckpointHandler;
onProgress?: ExecutionProgressCallback;
}
): SkillExecutionEngine {
return new SkillExecutionEngine(projectPath, options);
}
+26
View File
@@ -0,0 +1,26 @@
/**
* Skill Execution Engine Module
*
* Provides skill execution with task-based orchestration,
* verification, and session state management.
*/
export * from './types.js';
export * from './engine.js';
export { SkillExecutionEngine, createExecutionEngine } from './engine.js';
// Agent Execution (Real CLI integration)
export * from './agents.js';
export {
executeWithAgent,
isAgentCLIAvailable,
getAvailableCLIAgents,
getAgentCLIConfig,
formatSkillAsPrompt,
getExecutionStrategy,
getManualExecutionInstructions,
AGENT_CLI_CONFIGS,
type AgentCLIConfig,
type AgentExecutionResult,
type ExecutionStrategy,
} from './agents.js';
+179
View File
@@ -0,0 +1,179 @@
/**
* Executor Types
*
* Types for skill execution engine.
*/
import type { AgentType } from '../types.js';
/**
* Task type within a skill
*/
export type ExecutableTaskType =
| 'auto'
| 'checkpoint:human-verify'
| 'checkpoint:decision'
| 'checkpoint:human-action';
/**
* Task status
*/
export type ExecutionTaskStatus = 'pending' | 'running' | 'completed' | 'failed' | 'skipped';
/**
* Verification rule for a task
*/
export interface VerificationRule {
/** Command to run for verification */
command?: string;
/** Expected result (success, contains:<text>, matches:<regex>) */
expect?: string;
/** Human verification prompt */
description?: string;
/** URL to show for verification */
url?: string;
}
/**
* An executable task within a skill
*/
export interface ExecutableTask {
/** Task identifier */
id: string;
/** Task name/description */
name: string;
/** Task type */
type: ExecutableTaskType;
/** Action description for AI agent */
action: string;
/** Files expected to be modified */
files?: string[];
/** Verification rules */
verify?: {
automated?: VerificationRule[];
human?: VerificationRule[];
};
/** Options for checkpoint:decision type */
options?: string[];
/** Dependencies (task IDs that must complete first) */
dependsOn?: string[];
}
/**
* Extended skill with execution metadata
*/
export interface ExecutableSkill {
/** Skill name */
name: string;
/** Skill description */
description?: string;
/** Skill version */
version?: string;
/** Skill source (repo or path) */
source: string;
/** Skill content (instructions) */
content: string;
/** Executable tasks */
tasks?: ExecutableTask[];
/** Environment requirements */
requirements?: {
frameworks?: string[];
languages?: string[];
libraries?: string[];
};
}
/**
* Task execution result
*/
export interface TaskExecutionResult {
/** Task ID */
taskId: string;
/** Task name */
taskName: string;
/** Final status */
status: ExecutionTaskStatus;
/** Start time */
startedAt: string;
/** End time (only present for completed/failed/skipped tasks) */
completedAt?: string;
/** Duration in milliseconds (only present for completed/failed/skipped tasks) */
durationMs?: number;
/** Output/result */
output?: string;
/** Error message if failed */
error?: string;
/** Files modified */
filesModified?: string[];
/** Git commit SHA if committed */
commitSha?: string;
/** Verification results */
verificationResults?: {
automated: { rule: string; passed: boolean; output?: string }[];
human: { description: string; passed: boolean }[];
};
}
/**
* Skill execution result
*/
export interface SkillExecutionResult {
/** Skill name */
skillName: string;
/** Skill source */
skillSource: string;
/** Overall status */
status: 'completed' | 'failed' | 'cancelled' | 'paused';
/** Start time */
startedAt: string;
/** End time */
completedAt?: string;
/** Total duration in milliseconds */
durationMs?: number;
/** Task results */
tasks: TaskExecutionResult[];
/** All files modified */
filesModified: string[];
/** All commits created */
commits: string[];
/** Error if failed */
error?: string;
}
/**
* Execution options
*/
export interface ExecutionOptions {
/** Target agent to use */
agent?: AgentType;
/** Whether to create commits per task */
autoCommit?: boolean;
/** Whether to run verification checks */
verify?: boolean;
/** Dry run (show what would be done) */
dryRun?: boolean;
/** Continue on task failure */
continueOnError?: boolean;
/** Environment variables to set */
env?: Record<string, string>;
}
/**
* Checkpoint response from user
*/
export interface CheckpointResponse {
/** Whether to continue */
continue: boolean;
/** Selected option (for decision checkpoints) */
selectedOption?: string;
/** User notes */
notes?: string;
}
/**
* Checkpoint handler function type
*/
export type CheckpointHandler = (
task: ExecutableTask,
context: { skillName: string; taskIndex: number; totalTasks: number }
) => Promise<CheckpointResponse>;
+41
View File
@@ -0,0 +1,41 @@
// Types
export * from './types.js';
// Skills discovery and parsing
export * from './skills.js';
// Configuration
export * from './config.js';
// Git providers
export * from './providers/index.js';
// Translator (Universal Skill Translator)
export * from './translator/index.js';
// Context (Project Context Sync)
export * from './context/index.js';
// Recommendation Engine (Smart Recommendations)
export * from './recommend/index.js';
// Session Management (Pause/Resume Support)
export * from './session/index.js';
// Workflow Orchestration (Skill Composition)
export * from './workflow/index.js';
// Skill Execution Engine
export * from './executor/index.js';
// Skill Testing Framework
export * from './testing/index.js';
// Skill Marketplace (Aggregated Index)
export * from './marketplace/index.js';
// CI/CD Integration (Templates & Utilities)
export * from './cicd/index.js';
// Memory System (Cross-Agent Session Memory)
export * from './memory/index.js';
+526
View File
@@ -0,0 +1,526 @@
/**
* Marketplace Aggregator
*
* Fetches and indexes skills from multiple GitHub repositories.
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import type {
SkillSource,
MarketplaceSkill,
MarketplaceIndex,
MarketplaceSearchOptions,
MarketplaceSearchResult,
MarketplaceConfig,
} from './types.js';
import {
DEFAULT_SKILL_SOURCES,
MARKETPLACE_CACHE_FILE,
DEFAULT_CACHE_TTL,
} from './types.js';
/**
* Marketplace Aggregator
*/
export class MarketplaceAggregator {
private config: MarketplaceConfig;
private cacheDir: string;
private cachePath: string;
private index: MarketplaceIndex | null = null;
constructor(config: MarketplaceConfig = {}) {
this.config = config;
this.cacheDir = config.cacheDir || join(homedir(), '.skillkit', 'marketplace');
this.cachePath = join(this.cacheDir, MARKETPLACE_CACHE_FILE);
// Ensure cache directory exists
if (!existsSync(this.cacheDir)) {
mkdirSync(this.cacheDir, { recursive: true });
}
}
/**
* Get all sources (default + custom)
*/
getSources(): SkillSource[] {
return [...DEFAULT_SKILL_SOURCES, ...(this.config.sources || [])];
}
/**
* Load cached index
*/
loadCache(): MarketplaceIndex | null {
if (!existsSync(this.cachePath)) {
return null;
}
try {
const content = readFileSync(this.cachePath, 'utf-8');
const index = JSON.parse(content) as MarketplaceIndex;
// Check if cache is expired
const cacheAge = Date.now() - new Date(index.updatedAt).getTime();
const ttl = this.config.cacheTTL || DEFAULT_CACHE_TTL;
if (cacheAge > ttl) {
return null; // Cache expired
}
this.index = index;
return index;
} catch {
return null;
}
}
/**
* Save index to cache
*/
saveCache(index: MarketplaceIndex): void {
writeFileSync(this.cachePath, JSON.stringify(index, null, 2));
this.index = index;
}
/**
* Fetch skills from a single source
*/
async fetchSource(source: SkillSource): Promise<MarketplaceSkill[]> {
const skills: MarketplaceSkill[] = [];
const branch = source.branch || 'main';
try {
// Try to fetch skills index file
const indexPaths = [
source.indexPath,
'skills.json',
'index.json',
'.skillkit/skills.json',
].filter(Boolean) as string[];
for (const indexPath of indexPaths) {
try {
const url = `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${branch}/${indexPath}`;
const response = await fetch(url);
if (response.ok) {
const data = (await response.json()) as unknown;
if (Array.isArray(data)) {
for (const item of data) {
skills.push(this.parseSkillEntry(item as Record<string, unknown>, source));
}
return skills;
}
const dataObj = data as Record<string, unknown>;
if (dataObj.skills && Array.isArray(dataObj.skills)) {
for (const item of dataObj.skills) {
skills.push(this.parseSkillEntry(item as Record<string, unknown>, source));
}
return skills;
}
}
} catch {
// Try next path
}
}
// Fallback: Try to parse README for skill links
const readmeUrl = `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${branch}/README.md`;
const readmeResponse = await fetch(readmeUrl);
if (readmeResponse.ok) {
const readme = await readmeResponse.text();
const parsedSkills = this.parseReadmeForSkills(readme, source);
skills.push(...parsedSkills);
}
// If still no skills, add the repo itself as a skill source
if (skills.length === 0) {
skills.push({
id: `${source.owner}/${source.repo}`,
name: source.repo,
description: source.description || `Skills from ${source.name}`,
source,
path: '/',
tags: ['repository'],
rawUrl: `https://github.com/${source.owner}/${source.repo}`,
});
}
} catch (error) {
console.error(`Failed to fetch skills from ${source.owner}/${source.repo}:`, error);
}
return skills;
}
/**
* Check if a path is an absolute URL
*/
private isAbsoluteUrl(path: string): boolean {
return /^https?:\/\//i.test(path);
}
/**
* Convert a GitHub URL to raw content URL
*/
private toRawUrl(url: string): string {
return url
.replace('://github.com/', '://raw.githubusercontent.com/')
.replace('/blob/', '/');
}
/**
* Parse a skill entry from JSON
*/
private parseSkillEntry(
item: Record<string, unknown>,
source: SkillSource
): MarketplaceSkill {
const name = String(item.name || item.title || 'Unknown');
const path = String(item.path || item.file || item.url || '/');
// Handle absolute URLs - use them directly instead of building from source
const rawUrl = this.isAbsoluteUrl(path)
? this.toRawUrl(path)
: this.buildRawUrl(source, path);
return {
id: `${source.owner}/${source.repo}/${path}`,
name,
description: String(item.description || item.desc || ''),
source,
path,
version: item.version as string | undefined,
author: item.author as string | undefined,
tags: Array.isArray(item.tags) ? item.tags : [],
agents: Array.isArray(item.agents) ? item.agents : undefined,
stars: typeof item.stars === 'number' ? item.stars : undefined,
updatedAt: item.updatedAt as string | undefined,
downloads: typeof item.downloads === 'number' ? item.downloads : undefined,
rawUrl,
};
}
/**
* Parse README for skill links
*/
private parseReadmeForSkills(
readme: string,
source: SkillSource
): MarketplaceSkill[] {
const skills: MarketplaceSkill[] = [];
const branch = source.branch || 'main';
// Look for markdown links to skill files
const linkPattern = /\[([^\]]+)\]\(([^)]+\.md)\)/g;
let match;
while ((match = linkPattern.exec(readme)) !== null) {
const name = match[1];
const path = match[2];
// Skip external links and non-skill files
if (path.startsWith('http') && !path.includes(source.repo)) {
continue;
}
// Extract description from surrounding text
const contextStart = Math.max(0, match.index - 200);
const contextEnd = Math.min(readme.length, match.index + 200);
const context = readme.slice(contextStart, contextEnd);
// Try to find description in list item or paragraph
const descMatch = context.match(/[-*]\s*\[.*?\]\(.*?\)\s*[-:]\s*(.+?)(?:\n|$)/);
const description = descMatch ? descMatch[1].trim() : '';
// Handle absolute URLs in README links
const isAbsolute = this.isAbsoluteUrl(path);
const normalizedPath = isAbsolute ? path : (path.startsWith('/') ? path : `/${path}`);
const rawUrl = isAbsolute
? this.toRawUrl(path)
: `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${branch}/${path}`;
skills.push({
id: `${source.owner}/${source.repo}/${path}`,
name,
description,
source,
path: normalizedPath,
tags: this.inferTags(name, description),
rawUrl,
});
}
return skills;
}
/**
* Build raw URL for a skill
*/
private buildRawUrl(source: SkillSource, path: string): string {
const branch = source.branch || 'main';
const cleanPath = path.startsWith('/') ? path.slice(1) : path;
return `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${branch}/${cleanPath}`;
}
/**
* Infer tags from name and description
*/
private inferTags(name: string, description: string): string[] {
const tags: string[] = [];
const text = `${name} ${description}`.toLowerCase();
const tagKeywords: Record<string, string[]> = {
typescript: ['typescript', 'ts', 'tsc'],
javascript: ['javascript', 'js', 'node'],
react: ['react', 'jsx', 'tsx'],
nextjs: ['next', 'nextjs', 'next.js'],
testing: ['test', 'jest', 'vitest', 'mocha'],
linting: ['lint', 'eslint', 'prettier'],
auth: ['auth', 'authentication', 'login', 'oauth'],
database: ['database', 'db', 'postgres', 'mysql', 'mongo'],
api: ['api', 'rest', 'graphql'],
devops: ['ci', 'cd', 'docker', 'kubernetes'],
git: ['git', 'github', 'commit'],
};
for (const [tag, keywords] of Object.entries(tagKeywords)) {
if (keywords.some((k) => text.includes(k))) {
tags.push(tag);
}
}
return tags;
}
/**
* Refresh the marketplace index
*/
async refresh(): Promise<MarketplaceIndex> {
const sources = this.getSources();
const allSkills: MarketplaceSkill[] = [];
// Fetch from all sources in parallel
const results = await Promise.all(
sources.map((source) => this.fetchSource(source))
);
for (const skills of results) {
allSkills.push(...skills);
}
// Create index
const index: MarketplaceIndex = {
version: 1,
updatedAt: new Date().toISOString(),
sources,
skills: allSkills,
totalCount: allSkills.length,
};
// Save to cache
this.saveCache(index);
return index;
}
/**
* Get the marketplace index (from cache or refresh)
*/
async getIndex(forceRefresh = false): Promise<MarketplaceIndex> {
// Check in-memory cache first
if (!forceRefresh && this.index) {
return this.index;
}
// Check file cache
if (!forceRefresh) {
const cached = this.loadCache();
if (cached) {
return cached;
}
}
return this.refresh();
}
/**
* Search the marketplace
*/
async search(options: MarketplaceSearchOptions = {}): Promise<MarketplaceSearchResult> {
const index = await this.getIndex();
let skills = [...index.skills];
// Filter by query
if (options.query) {
const query = options.query.toLowerCase();
skills = skills.filter(
(s) =>
s.name.toLowerCase().includes(query) ||
s.description.toLowerCase().includes(query) ||
s.tags.some((t) => t.toLowerCase().includes(query))
);
}
// Filter by tags
if (options.tags && options.tags.length > 0) {
skills = skills.filter((s) =>
options.tags!.some((t) => s.tags.includes(t))
);
}
// Filter by source
if (options.source) {
skills = skills.filter(
(s) =>
s.source.name === options.source ||
`${s.source.owner}/${s.source.repo}` === options.source
);
}
// Filter by agent
if (options.agent) {
skills = skills.filter(
(s) => !s.agents || s.agents.includes(options.agent!)
);
}
// Sort
const sortBy = options.sortBy || 'name';
const sortOrder = options.sortOrder || 'asc';
skills.sort((a, b) => {
let comparison = 0;
switch (sortBy) {
case 'name':
comparison = a.name.localeCompare(b.name);
break;
case 'stars':
comparison = (a.stars || 0) - (b.stars || 0);
break;
case 'downloads':
comparison = (a.downloads || 0) - (b.downloads || 0);
break;
case 'updatedAt':
comparison =
new Date(a.updatedAt || 0).getTime() -
new Date(b.updatedAt || 0).getTime();
break;
}
return sortOrder === 'desc' ? -comparison : comparison;
});
const total = skills.length;
// Apply pagination
if (options.offset) {
skills = skills.slice(options.offset);
}
if (options.limit) {
skills = skills.slice(0, options.limit);
}
return {
skills,
total,
query: options.query,
};
}
/**
* Get a skill by ID
*/
async getSkill(id: string): Promise<MarketplaceSkill | null> {
const index = await this.getIndex();
return index.skills.find((s) => s.id === id) || null;
}
/**
* Get skill content
*/
async getSkillContent(skill: MarketplaceSkill): Promise<string | null> {
if (!skill.rawUrl) {
return null;
}
try {
const response = await fetch(skill.rawUrl);
if (response.ok) {
return response.text();
}
} catch {
// Fetch failed
}
return null;
}
/**
* Get popular tags
*/
async getPopularTags(limit = 20): Promise<{ tag: string; count: number }[]> {
const index = await this.getIndex();
const tagCounts = new Map<string, number>();
for (const skill of index.skills) {
for (const tag of skill.tags) {
tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);
}
}
const tags = Array.from(tagCounts.entries())
.map(([tag, count]) => ({ tag, count }))
.sort((a, b) => b.count - a.count)
.slice(0, limit);
return tags;
}
/**
* Add a custom source
*/
addSource(source: SkillSource): void {
if (!this.config.sources) {
this.config.sources = [];
}
this.config.sources.push(source);
this.clearCache();
}
/**
* Remove a custom source
*/
removeSource(owner: string, repo: string): void {
if (this.config.sources) {
this.config.sources = this.config.sources.filter(
(s) => s.owner !== owner || s.repo !== repo
);
}
this.clearCache();
}
/**
* Clear cache
*/
clearCache(): void {
if (existsSync(this.cachePath)) {
unlinkSync(this.cachePath);
}
this.index = null;
}
}
/**
* Create a marketplace aggregator
*/
export function createMarketplaceAggregator(
config?: MarketplaceConfig
): MarketplaceAggregator {
return new MarketplaceAggregator(config);
}
+41
View File
@@ -0,0 +1,41 @@
/**
* Skill Marketplace Module
*
* Provides aggregated skill discovery from multiple GitHub repositories.
*
* @example
* ```typescript
* import { createMarketplaceAggregator } from '@skillkit/core';
*
* const marketplace = createMarketplaceAggregator();
*
* // Search for skills
* const results = await marketplace.search({ query: 'typescript' });
*
* // Get popular tags
* const tags = await marketplace.getPopularTags();
*
* // Refresh index from all sources
* await marketplace.refresh();
* ```
*/
export * from './types.js';
export * from './aggregator.js';
export {
MarketplaceAggregator,
createMarketplaceAggregator,
} from './aggregator.js';
export {
DEFAULT_SKILL_SOURCES,
MARKETPLACE_CACHE_FILE,
DEFAULT_CACHE_TTL,
type SkillSource,
type MarketplaceSkill,
type MarketplaceIndex,
type MarketplaceSearchOptions,
type MarketplaceSearchResult,
type MarketplaceConfig,
} from './types.js';
+153
View File
@@ -0,0 +1,153 @@
/**
* Skill Marketplace Types
*
* Types for the aggregated skill marketplace.
*/
/**
* Skill source repository
*/
export interface SkillSource {
/** Repository owner */
owner: string;
/** Repository name */
repo: string;
/** Human-readable name */
name: string;
/** Description */
description?: string;
/** Whether this is an official source */
official?: boolean;
/** Branch to fetch from */
branch?: string;
/** Path to skills index file */
indexPath?: string;
}
/**
* Skill entry in the marketplace
*/
export interface MarketplaceSkill {
/** Unique identifier (owner/repo/path) */
id: string;
/** Skill name */
name: string;
/** Description */
description: string;
/** Source repository */
source: SkillSource;
/** Path within the repository */
path: string;
/** Version if available */
version?: string;
/** Author */
author?: string;
/** Tags for categorization */
tags: string[];
/** Supported agents */
agents?: string[];
/** GitHub stars (if available) */
stars?: number;
/** Last updated date */
updatedAt?: string;
/** Download/install count */
downloads?: number;
/** Raw content URL */
rawUrl?: string;
}
/**
* Marketplace index (cached locally)
*/
export interface MarketplaceIndex {
/** Index version */
version: number;
/** When the index was last updated */
updatedAt: string;
/** Sources included in this index */
sources: SkillSource[];
/** All skills in the index */
skills: MarketplaceSkill[];
/** Total skill count */
totalCount: number;
}
/**
* Search options for the marketplace
*/
export interface MarketplaceSearchOptions {
/** Search query */
query?: string;
/** Filter by tags */
tags?: string[];
/** Filter by source */
source?: string;
/** Filter by agent compatibility */
agent?: string;
/** Sort by field */
sortBy?: 'name' | 'stars' | 'downloads' | 'updatedAt';
/** Sort direction */
sortOrder?: 'asc' | 'desc';
/** Limit results */
limit?: number;
/** Offset for pagination */
offset?: number;
}
/**
* Search result
*/
export interface MarketplaceSearchResult {
/** Matching skills */
skills: MarketplaceSkill[];
/** Total matches (before limit) */
total: number;
/** Query that was searched */
query?: string;
}
/**
* Marketplace configuration
*/
export interface MarketplaceConfig {
/** Custom sources to include */
sources?: SkillSource[];
/** Cache directory */
cacheDir?: string;
/** Cache TTL in milliseconds */
cacheTTL?: number;
/** GitHub token for API access */
githubToken?: string;
}
/**
* Default skill sources
*/
export const DEFAULT_SKILL_SOURCES: SkillSource[] = [
{
owner: 'composioHQ',
repo: 'awesome-claude-code-skills',
name: 'Composio Curated',
description: 'Curated collection of Claude Code skills',
official: false,
branch: 'main',
},
{
owner: 'anthropics',
repo: 'courses',
name: 'Anthropic Official',
description: 'Official Anthropic courses and skills',
official: true,
branch: 'master',
},
];
/**
* Cache file name
*/
export const MARKETPLACE_CACHE_FILE = 'marketplace-index.json';
/**
* Default cache TTL (1 hour)
*/
export const DEFAULT_CACHE_TTL = 60 * 60 * 1000;
@@ -0,0 +1,500 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import {
RuleBasedCompressor,
APIBasedCompressor,
MemoryCompressor,
LearningConsolidator,
createRuleBasedCompressor,
createAPIBasedCompressor,
createMemoryCompressor,
} from '../compressor.js';
import type { Observation, Learning } from '../types.js';
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
}));
// Helper to create mock observations
const createObservation = (overrides: Partial<Observation> = {}): Observation => ({
id: `obs-${Math.random().toString(36).slice(2, 9)}`,
timestamp: new Date().toISOString(),
sessionId: 'test-session',
agent: 'claude-code',
type: 'tool_use',
content: {
action: 'Test action',
context: 'Test context',
},
relevance: 60,
...overrides,
});
// Helper to create mock learnings
const createLearning = (overrides: Partial<Learning> = {}): Learning => ({
id: `learn-${Math.random().toString(36).slice(2, 9)}`,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
source: 'session',
title: 'Test Learning',
content: 'Test content for learning',
scope: 'project',
tags: ['test'],
useCount: 0,
...overrides,
});
describe('RuleBasedCompressor', () => {
let compressor: RuleBasedCompressor;
beforeEach(() => {
compressor = new RuleBasedCompressor();
vi.clearAllMocks();
});
describe('getType', () => {
it('should return rule-based', () => {
expect(compressor.getType()).toBe('rule-based');
});
});
describe('compress', () => {
it('should return empty result when observations below threshold', async () => {
const observations = [createObservation(), createObservation()];
const result = await compressor.compress(observations, { minObservations: 5 });
expect(result.learnings).toHaveLength(0);
expect(result.skippedObservationIds).toHaveLength(2);
});
it('should extract error-solution pairs', async () => {
const observations = [
createObservation({
type: 'error',
content: {
action: 'Build failed',
context: 'Running npm build',
error: 'TypeError: Cannot read property of undefined',
},
relevance: 85,
}),
createObservation({
type: 'solution',
content: {
action: 'Added null check',
context: 'Fixed the TypeError',
solution: 'Added optional chaining operator',
},
relevance: 90,
}),
createObservation({
type: 'tool_use',
content: {
action: 'Some other action',
context: 'Context',
},
relevance: 50,
}),
];
const result = await compressor.compress(observations, { minObservations: 2 });
expect(result.learnings.length).toBeGreaterThanOrEqual(1);
const errorSolutionLearning = result.learnings.find((l) =>
l.title.includes('Error Resolution')
);
expect(errorSolutionLearning).toBeDefined();
});
it('should extract decision patterns', async () => {
const observations = [
createObservation({
type: 'decision',
content: {
action: 'Use TypeScript',
context: 'Choosing programming language',
},
relevance: 75,
}),
createObservation({
type: 'decision',
content: {
action: 'Use React hooks',
context: 'State management approach',
},
relevance: 75,
}),
createObservation({
type: 'tool_use',
content: {
action: 'Filler',
context: 'Context',
},
relevance: 50,
}),
];
const result = await compressor.compress(observations, { minObservations: 2 });
expect(result.learnings.length).toBeGreaterThanOrEqual(1);
const decisionLearning = result.learnings.find((l) => l.title.includes('Decision'));
expect(decisionLearning).toBeDefined();
});
it('should filter by minimum importance', async () => {
const observations = [
createObservation({
type: 'tool_use',
content: { action: 'Low importance action', context: 'Context' },
relevance: 50,
}),
createObservation({
type: 'tool_use',
content: { action: 'Another action', context: 'Context' },
relevance: 50,
}),
createObservation({
type: 'tool_use',
content: { action: 'Third action', context: 'Context' },
relevance: 50,
}),
];
const result = await compressor.compress(observations, {
minObservations: 2,
minImportance: 9, // Very high threshold
});
// Tool use patterns have low importance, so should be filtered
expect(result.learnings.length).toBe(0);
});
it('should limit output to maxLearnings', async () => {
const observations = [
createObservation({
type: 'error',
content: { action: 'Error 1', context: 'Context', error: 'Error 1' },
relevance: 85,
}),
createObservation({
type: 'error',
content: { action: 'Error 2', context: 'Context', error: 'Error 2' },
relevance: 85,
}),
createObservation({
type: 'error',
content: { action: 'Error 3', context: 'Context', error: 'Error 3' },
relevance: 85,
}),
createObservation({
type: 'solution',
content: { action: 'Solution 1', context: 'Context', solution: 'Solution' },
relevance: 90,
}),
];
const result = await compressor.compress(observations, {
minObservations: 2,
maxLearnings: 2,
});
expect(result.learnings.length).toBeLessThanOrEqual(2);
});
it('should add additional tags to learnings', async () => {
const observations = [
createObservation({
type: 'error',
content: { action: 'Error', context: 'Context', error: 'Some error' },
relevance: 85,
}),
createObservation({
type: 'solution',
content: { action: 'Fix', context: 'Context', solution: 'Fixed it' },
relevance: 90,
}),
createObservation({
type: 'tool_use',
content: { action: 'Action', context: 'Context' },
relevance: 50,
}),
];
const result = await compressor.compress(observations, {
minObservations: 2,
additionalTags: ['project-x', 'sprint-1'],
});
if (result.learnings.length > 0) {
expect(result.learnings[0].tags).toContain('project-x');
expect(result.learnings[0].tags).toContain('sprint-1');
}
});
it('should calculate compression stats', async () => {
const observations = [
createObservation({ type: 'error', relevance: 85 }),
createObservation({ type: 'solution', relevance: 90 }),
createObservation({ type: 'tool_use', relevance: 50 }),
];
const result = await compressor.compress(observations, { minObservations: 2 });
expect(result.stats.inputCount).toBe(3);
expect(result.stats.outputCount).toBe(result.learnings.length);
expect(result.stats.compressionRatio).toBeDefined();
});
});
});
describe('APIBasedCompressor', () => {
let compressor: APIBasedCompressor;
beforeEach(() => {
compressor = new APIBasedCompressor({
provider: 'anthropic',
apiKey: 'test-key',
model: 'claude-3-haiku-20240307',
});
vi.clearAllMocks();
});
describe('getType', () => {
it('should return api', () => {
expect(compressor.getType()).toBe('api');
});
});
describe('compress', () => {
it('should return empty result when observations below threshold', async () => {
const observations = [createObservation()];
const result = await compressor.compress(observations, { minObservations: 5 });
expect(result.learnings).toHaveLength(0);
});
it('should fall back to rule-based on API failure', async () => {
// Mock fetch to fail
global.fetch = vi.fn().mockRejectedValue(new Error('API error'));
const observations = [
createObservation({ type: 'error', relevance: 85 }),
createObservation({ type: 'solution', relevance: 90 }),
createObservation({ type: 'tool_use', relevance: 50 }),
];
const result = await compressor.compress(observations, { minObservations: 2 });
// Should not throw, should return result from fallback
expect(result.stats.inputCount).toBe(3);
});
});
});
describe('MemoryCompressor', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(existsSync).mockReturnValue(false);
});
describe('constructor', () => {
it('should create with default engine', () => {
const compressor = new MemoryCompressor('/test/project');
expect(compressor.getEngineType()).toBe('rule-based');
});
it('should accept custom engine', () => {
const apiEngine = new APIBasedCompressor({
provider: 'openai',
apiKey: 'test',
});
const compressor = new MemoryCompressor('/test/project', { engine: apiEngine });
expect(compressor.getEngineType()).toBe('api');
});
});
describe('setEngine', () => {
it('should allow changing the engine', () => {
const compressor = new MemoryCompressor('/test/project');
expect(compressor.getEngineType()).toBe('rule-based');
compressor.setEngine(
new APIBasedCompressor({
provider: 'anthropic',
apiKey: 'test',
})
);
expect(compressor.getEngineType()).toBe('api');
});
});
describe('compressAndStore', () => {
it('should compress and store learnings', async () => {
const compressor = createMemoryCompressor('/test/project', {
projectName: 'test-project',
});
const observations = [
createObservation({
type: 'error',
content: { action: 'Error', context: 'Context', error: 'Test error' },
relevance: 85,
}),
createObservation({
type: 'solution',
content: { action: 'Fix', context: 'Fixed error', solution: 'Applied fix' },
relevance: 90,
}),
createObservation({ type: 'tool_use', relevance: 50 }),
];
const { learnings, result } = await compressor.compressAndStore(observations, {
minObservations: 2,
});
expect(result.stats.inputCount).toBe(3);
// Learnings should have been created
expect(learnings.length).toBe(result.learnings.length);
});
});
});
describe('LearningConsolidator', () => {
let consolidator: LearningConsolidator;
beforeEach(() => {
consolidator = new LearningConsolidator();
vi.clearAllMocks();
vi.mocked(existsSync).mockReturnValue(false);
});
describe('findSimilar', () => {
it('should find similar learnings', () => {
const learnings = [
createLearning({
id: 'l1',
title: 'React hooks best practices',
tags: ['react', 'hooks'],
patterns: ['best-practices'],
content: 'When using React hooks, always follow the rules of hooks.',
}),
createLearning({
id: 'l2',
title: 'React hooks patterns',
tags: ['react', 'hooks', 'patterns'],
patterns: ['best-practices'],
content: 'React hooks provide a way to use state in functional components.',
}),
createLearning({
id: 'l3',
title: 'TypeScript generics guide',
tags: ['typescript', 'generics'],
patterns: ['type-safety'],
content: 'TypeScript generics allow you to write reusable type-safe code.',
}),
];
const pairs = consolidator.findSimilar(learnings, 0.5);
// The two React hooks learnings should be similar
expect(pairs.length).toBeGreaterThanOrEqual(1);
const reactPair = pairs.find(
([a, b]) =>
(a.id === 'l1' && b.id === 'l2') || (a.id === 'l2' && b.id === 'l1')
);
expect(reactPair).toBeDefined();
});
it('should not find similar for distinct learnings', () => {
const learnings = [
createLearning({
title: 'React tutorial',
tags: ['react', 'frontend'],
content: 'React is a library for building user interfaces.',
}),
createLearning({
title: 'Python basics',
tags: ['python', 'backend'],
content: 'Python is a versatile programming language.',
}),
];
const pairs = consolidator.findSimilar(learnings, 0.8);
expect(pairs).toHaveLength(0);
});
});
describe('merge', () => {
it('should merge two learnings', () => {
const l1 = createLearning({
title: 'React hooks patterns',
content: 'Content 1 about hooks',
tags: ['react', 'hooks'],
frameworks: ['react'],
patterns: ['hooks'],
useCount: 5,
effectiveness: 80,
});
const l2 = createLearning({
title: 'React hooks best practices',
content: 'Content 2 about best practices for hooks in React applications',
tags: ['react', 'best-practices'],
frameworks: ['react', 'nextjs'],
patterns: ['hooks', 'state-management'],
useCount: 3,
effectiveness: 70,
});
const merged = consolidator.merge(l1, l2);
// Should combine tags
expect(merged.tags).toContain('react');
expect(merged.tags).toContain('hooks');
expect(merged.tags).toContain('best-practices');
// Should combine frameworks
expect(merged.frameworks).toContain('react');
expect(merged.frameworks).toContain('nextjs');
// Should combine patterns
expect(merged.patterns).toContain('hooks');
expect(merged.patterns).toContain('state-management');
// Should combine use count
expect(merged.useCount).toBe(8);
// Should keep higher effectiveness
expect(merged.effectiveness).toBe(80);
});
});
});
describe('Factory functions', () => {
it('createRuleBasedCompressor should create instance', () => {
const compressor = createRuleBasedCompressor();
expect(compressor).toBeInstanceOf(RuleBasedCompressor);
expect(compressor.getType()).toBe('rule-based');
});
it('createAPIBasedCompressor should create instance', () => {
const compressor = createAPIBasedCompressor({
provider: 'anthropic',
apiKey: 'test-key',
});
expect(compressor).toBeInstanceOf(APIBasedCompressor);
expect(compressor.getType()).toBe('api');
});
it('createMemoryCompressor should create instance', () => {
vi.mocked(existsSync).mockReturnValue(false);
const compressor = createMemoryCompressor('/test/project');
expect(compressor).toBeInstanceOf(MemoryCompressor);
});
});
@@ -0,0 +1,533 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { MemoryInjector, createMemoryInjector } from '../injector.js';
import type { Learning } from '../types.js';
import type { ProjectContext } from '../../context/types.js';
vi.mock('node:fs', () => ({
existsSync: vi.fn(),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
}));
// Helper to create mock learnings
const createLearning = (overrides: Partial<Learning> = {}): Learning => ({
id: `learn-${Math.random().toString(36).slice(2, 9)}`,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
source: 'session',
title: 'Test Learning',
content: 'Test content for learning that provides useful information about best practices.',
scope: 'project',
tags: ['test'],
useCount: 0,
...overrides,
});
// Helper to create mock project context
const createProjectContext = (overrides: Partial<ProjectContext> = {}): ProjectContext => ({
version: 1,
project: {
name: 'test-project',
description: 'A test project',
type: 'web-app',
},
stack: {
languages: [{ name: 'TypeScript', confidence: 100 }],
frameworks: [{ name: 'React', confidence: 100 }, { name: 'Next.js', confidence: 90 }],
libraries: [],
styling: [{ name: 'Tailwind', confidence: 100 }],
testing: [{ name: 'Vitest', confidence: 100 }],
databases: [],
tools: [],
runtime: [{ name: 'Node.js', confidence: 100 }],
},
...overrides,
});
// Mock YAML content for project learnings
const createMockLearningsYaml = (learnings: Learning[]) => ({
version: 1,
learnings,
});
describe('MemoryInjector', () => {
let injector: MemoryInjector;
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(existsSync).mockReturnValue(false);
});
describe('constructor', () => {
it('should create instance without project context', () => {
injector = new MemoryInjector('/test/project');
expect(injector).toBeInstanceOf(MemoryInjector);
});
it('should create instance with project context', () => {
const context = createProjectContext();
injector = new MemoryInjector('/test/project', 'test-project', context);
expect(injector).toBeInstanceOf(MemoryInjector);
});
});
describe('setProjectContext', () => {
it('should set project context', () => {
injector = new MemoryInjector('/test/project');
const context = createProjectContext();
injector.setProjectContext(context);
// No direct way to verify, but it should not throw
});
});
describe('getRelevantMemories', () => {
it('should return empty array when no learnings exist', async () => {
injector = new MemoryInjector('/test/project');
const memories = await injector.getRelevantMemories();
expect(memories).toHaveLength(0);
});
it('should return learnings with relevance scores', async () => {
const learnings = [
createLearning({
id: 'l1',
title: 'React hooks best practices',
tags: ['react', 'hooks'],
frameworks: ['react'],
useCount: 5,
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
const context = createProjectContext();
injector = new MemoryInjector('/test/project', 'test-project', context);
const memories = await injector.getRelevantMemories();
expect(memories.length).toBeGreaterThanOrEqual(0);
});
it('should filter by minimum relevance', async () => {
const learnings = [
createLearning({
id: 'l1',
title: 'Unrelated learning',
tags: ['unrelated'],
useCount: 0,
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const memories = await injector.getRelevantMemories({ minRelevance: 90 });
expect(memories).toHaveLength(0);
});
it('should limit results to maxLearnings', async () => {
const learnings = Array.from({ length: 20 }, (_, i) =>
createLearning({
id: `l${i}`,
title: `Learning ${i}`,
tags: ['common-tag'],
useCount: i,
})
);
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const memories = await injector.getRelevantMemories({
maxLearnings: 5,
minRelevance: 0,
});
expect(memories.length).toBeLessThanOrEqual(5);
});
it('should match by current task keywords', async () => {
const learnings = [
createLearning({
id: 'l1',
title: 'Authentication patterns',
content: 'How to implement JWT authentication in Node.js applications.',
tags: ['auth', 'jwt', 'security'],
}),
createLearning({
id: 'l2',
title: 'CSS Grid layout',
content: 'Guide to using CSS Grid for responsive layouts.',
tags: ['css', 'layout'],
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const memories = await injector.getRelevantMemories({
currentTask: 'implement JWT authentication',
minRelevance: 0,
});
// Auth learning should rank higher
if (memories.length > 0) {
const authMemory = memories.find((m) => m.learning.id === 'l1');
const cssMemory = memories.find((m) => m.learning.id === 'l2');
if (authMemory && cssMemory) {
expect(authMemory.relevanceScore).toBeGreaterThan(cssMemory.relevanceScore);
}
}
});
});
describe('inject', () => {
it('should return empty result when no learnings exist', async () => {
injector = new MemoryInjector('/test/project');
const result = await injector.inject();
expect(result.memories).toHaveLength(0);
expect(result.formattedContent).toBe('');
expect(result.totalTokens).toBe(0);
expect(result.stats.injected).toBe(0);
});
it('should respect token budget', async () => {
const learnings = Array.from({ length: 10 }, (_, i) =>
createLearning({
id: `l${i}`,
title: `Learning ${i}`,
content: 'A'.repeat(500), // Long content
tags: ['test'],
useCount: 10 - i,
})
);
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const result = await injector.inject({
maxTokens: 100,
minRelevance: 0,
});
expect(result.totalTokens).toBeLessThanOrEqual(100);
});
it('should format content as markdown by default', async () => {
const learnings = [
createLearning({
id: 'l1',
title: 'Test Learning',
content: 'Test content',
tags: ['test'],
useCount: 5,
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const result = await injector.inject({ minRelevance: 0 });
if (result.memories.length > 0) {
expect(result.formattedContent).toContain('# Relevant Memories');
expect(result.formattedContent).toContain('## Test Learning');
}
});
});
describe('injectForAgent', () => {
const learnings = [
createLearning({
id: 'l1',
title: 'Test Learning',
content: 'Test content for agent',
tags: ['test'],
frameworks: ['react'],
useCount: 5,
}),
];
beforeEach(() => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
});
it('should format for claude-code with XML tags', async () => {
injector = new MemoryInjector('/test/project');
const result = await injector.injectForAgent('claude-code', { minRelevance: 0 });
if (result.memories.length > 0) {
expect(result.formattedContent).toContain('<memories>');
expect(result.formattedContent).toContain('<memory');
expect(result.formattedContent).toContain('</memories>');
}
});
it('should format for cursor with MDC format', async () => {
injector = new MemoryInjector('/test/project');
const result = await injector.injectForAgent('cursor', { minRelevance: 0 });
if (result.memories.length > 0) {
expect(result.formattedContent).toContain('---');
expect(result.formattedContent).toContain('description:');
expect(result.formattedContent).toContain('# Session Memories');
}
});
it('should format for github-copilot with HTML comments', async () => {
injector = new MemoryInjector('/test/project');
const result = await injector.injectForAgent('github-copilot', { minRelevance: 0 });
if (result.memories.length > 0) {
expect(result.formattedContent).toContain('<!-- Session Memories -->');
}
});
it('should use default markdown for unknown agents', async () => {
injector = new MemoryInjector('/test/project');
const result = await injector.injectForAgent('universal', { minRelevance: 0 });
if (result.memories.length > 0) {
expect(result.formattedContent).toContain('# Relevant Memories');
}
});
});
describe('getSummaries', () => {
it('should return memory summaries', () => {
const learnings = [
createLearning({
id: 'l1',
title: 'Test Learning',
tags: ['test', 'example'],
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const summaries = injector.getSummaries();
expect(summaries.length).toBeGreaterThanOrEqual(0);
if (summaries.length > 0) {
expect(summaries[0]).toHaveProperty('id');
expect(summaries[0]).toHaveProperty('title');
expect(summaries[0]).toHaveProperty('tags');
expect(summaries[0]).toHaveProperty('relevance');
}
});
});
describe('getPreviews', () => {
it('should return memory previews for given IDs', () => {
const learnings = [
createLearning({
id: 'l1',
title: 'Test Learning',
content: 'Full content that is longer than the excerpt limit would allow.',
tags: ['test'],
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const previews = injector.getPreviews(['l1']);
if (previews.length > 0) {
expect(previews[0]).toHaveProperty('excerpt');
expect(previews[0].excerpt.length).toBeLessThanOrEqual(200);
}
});
it('should return empty for non-existent IDs', () => {
vi.mocked(existsSync).mockReturnValue(false);
injector = new MemoryInjector('/test/project');
const previews = injector.getPreviews(['non-existent']);
expect(previews).toHaveLength(0);
});
});
describe('getFullMemories', () => {
it('should return full memory content', () => {
const fullContent = 'This is the full content of the learning that should be returned.';
const learnings = [
createLearning({
id: 'l1',
title: 'Test Learning',
content: fullContent,
tags: ['test'],
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const fullMemories = injector.getFullMemories(['l1']);
if (fullMemories.length > 0) {
expect(fullMemories[0].content).toBe(fullContent);
}
});
});
describe('search', () => {
it('should search memories by query', () => {
const learnings = [
createLearning({
id: 'l1',
title: 'React hooks patterns',
content: 'How to use useEffect and useState effectively.',
tags: ['react', 'hooks'],
}),
createLearning({
id: 'l2',
title: 'Python data analysis',
content: 'Using pandas for data manipulation.',
tags: ['python', 'data'],
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const results = injector.search('react hooks');
// React learning should be found
const reactResult = results.find((r) => r.learning.id === 'l1');
if (results.length > 0 && reactResult) {
expect(reactResult.matchedBy.keywords.length).toBeGreaterThanOrEqual(0);
}
});
it('should respect minRelevance in search', () => {
const learnings = [
createLearning({
id: 'l1',
title: 'Unrelated topic',
content: 'Nothing to do with the search.',
tags: ['other'],
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const results = injector.search('completely different query', { minRelevance: 80 });
expect(results).toHaveLength(0);
});
});
describe('formatForAgent', () => {
it('should escape XML special characters for Claude', () => {
const learnings = [
createLearning({
id: 'l1',
title: 'Test <script> & "quotes"',
content: 'Content with <tags> & special chars',
tags: ['test'],
useCount: 5,
}),
];
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(readFileSync).mockReturnValue(
JSON.stringify(createMockLearningsYaml(learnings))
);
injector = new MemoryInjector('/test/project');
const memories = injector.search('test', { minRelevance: 0 });
const formatted = injector.formatForAgent(memories, 'claude-code');
if (memories.length > 0) {
expect(formatted).toContain('&lt;script&gt;');
expect(formatted).toContain('&amp;');
expect(formatted).toContain('&quot;');
}
});
});
});
describe('createMemoryInjector', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(existsSync).mockReturnValue(false);
});
it('should create MemoryInjector instance', () => {
const injector = createMemoryInjector('/test/project');
expect(injector).toBeInstanceOf(MemoryInjector);
});
it('should create with project name', () => {
const injector = createMemoryInjector('/test/project', 'my-project');
expect(injector).toBeInstanceOf(MemoryInjector);
});
it('should create with project context', () => {
const context = createProjectContext();
const injector = createMemoryInjector('/test/project', 'my-project', context);
expect(injector).toBeInstanceOf(MemoryInjector);
});
});

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