mirror of
https://github.com/rohitg00/skillkit.git
synced 2026-11-19 02:13:58 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8a6b4a700 | ||
|
|
0518ed40a3 | ||
|
|
91e7ab3450 | ||
|
|
d62fe0b761 | ||
|
|
1344d65b3d | ||
|
|
9688959361 | ||
|
|
7805a5fd4b | ||
|
|
b34177ca85 | ||
|
|
2fa62e6863 | ||
|
|
64b802a1e6 | ||
|
|
d3ffb79512 | ||
|
|
b008a46b8d | ||
|
|
ed90080786 | ||
|
|
b701bb5f47 | ||
|
|
1c4c9a794f | ||
|
|
cb37ebeca7 | ||
|
|
7053d1a2b2 | ||
|
|
1ea5ddd4c7 | ||
|
|
720532c020 | ||
|
|
bc12775e0e | ||
|
|
cd64f7f7d0 | ||
|
|
ca9af70f10 | ||
|
|
160d2b1534 | ||
|
|
4a632e9262 | ||
|
|
a763348922 | ||
|
|
4782b6773b | ||
|
|
75001a1310 | ||
|
|
73f9c26cbe | ||
|
|
e56873c491 | ||
|
|
eaeb7ef221 | ||
|
|
acec136e81 | ||
|
|
70cb4f74ff | ||
|
|
2f4232182f |
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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!
|
||||
@@ -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.
|
||||
|
||||
@@ -3,286 +3,406 @@
|
||||
[](https://www.npmjs.com/package/skillkit)
|
||||
[](https://www.npmjs.com/package/skillkit)
|
||||
[](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
Universal skills loader for AI coding agents. Install, manage, and sync skills across your favorite AI tools.
|
||||
## One CLI. 17 AI Agents. Zero Lock-in.
|
||||
|
||||
Skills follow the [Agent Skills](https://agentskills.io) open format—a simple, portable standard for giving agents new capabilities and expertise.
|
||||
|
||||
### Compatible With
|
||||
|
||||
| Agent | Status |
|
||||
|-------|--------|
|
||||
| Claude Code | ✅ Native |
|
||||
| OpenAI Codex | ✅ Native |
|
||||
| Cursor | ✅ Native |
|
||||
| Gemini CLI | ✅ Native |
|
||||
| OpenCode | ✅ Native |
|
||||
| Amp | ✅ Supported |
|
||||
| Goose | ✅ Supported |
|
||||
| VS Code (Copilot) | ✅ Supported |
|
||||
| Letta | ✅ Supported |
|
||||
| Factory | ✅ Supported |
|
||||
| Antigravity | ✅ Native |
|
||||
| *Any markdown-config agent* | ✅ Universal |
|
||||
|
||||
## Features
|
||||
|
||||
- **Multi-Agent Support**: Works with 10+ AI coding agents out of the box
|
||||
- **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
|
||||
- **Zero Config**: Auto-detects your agent and configures appropriately
|
||||
|
||||
## Installation
|
||||
**Write skills once, use everywhere.** SkillKit is the universal platform that lets your AI coding skills work across Claude Code, Cursor, Codex, Windsurf, GitHub Copilot, and 12 more agents.
|
||||
|
||||
```bash
|
||||
npm install -g skillkit
|
||||
# or
|
||||
npx skillkit <command>
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
## What's New in v1.5.0
|
||||
|
||||
- **Team Collaboration**: Share skill bundles with your team via Git
|
||||
- **Plugin System**: Extend SkillKit with custom translators, providers, and commands
|
||||
- **Methodologies**: 5 ready-to-use development frameworks (Agile, TDD, DevOps, etc.)
|
||||
- **Agent Orchestration**: Coordinate multiple AI agents working together
|
||||
- **Hooks & Automation**: Auto-trigger skills on git commits, file changes
|
||||
|
||||
## The Problem
|
||||
|
||||
You've built amazing skills for Claude Code. Now you want to try Cursor. Or your team uses different agents. Your options:
|
||||
|
||||
1. **Rewrite everything** - each agent has different formats, directories, and conventions
|
||||
2. **Pick one agent** - lock yourself in, miss out on innovations
|
||||
3. **Give up on skills** - lose the productivity gains
|
||||
|
||||
## The Solution
|
||||
|
||||
```bash
|
||||
# Initialize in your project (auto-detects agent)
|
||||
skillkit init
|
||||
# Install a skill for ALL your agents at once
|
||||
skillkit install anthropics/skills --agent claude-code,cursor,windsurf
|
||||
|
||||
# Install skills from GitHub
|
||||
skillkit install owner/repo
|
||||
# Or translate existing skills between any agents
|
||||
skillkit translate my-skill --from claude --to cursor,codex,copilot
|
||||
|
||||
# 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
|
||||
skillkit sync
|
||||
|
||||
# Read a skill (for AI consumption)
|
||||
skillkit read pdf
|
||||
# Get smart recommendations based on your project
|
||||
skillkit recommend
|
||||
# > 92% match: vercel-react-best-practices
|
||||
# > 87% match: tailwind-v4-patterns
|
||||
# > 85% match: nextjs-app-router
|
||||
```
|
||||
|
||||
## Popular Skill Repositories
|
||||

|
||||
|
||||
Install skills from these community repositories:
|
||||
## What Makes SkillKit Different
|
||||
|
||||
| Feature | Without SkillKit | With SkillKit |
|
||||
|---------|-----------------|---------------|
|
||||
| **Multi-Agent Support** | Manual rewrite for each agent | One command, all agents |
|
||||
| **Team Collaboration** | Email skills back and forth | Git-based bundles, remote sync |
|
||||
| **Skill Discovery** | Search GitHub manually | Smart recommendations for your stack |
|
||||
| **Format Translation** | Learn each agent's format | Automatic conversion (17 formats) |
|
||||
| **Context Sync** | Configure each agent separately | One config, synced everywhere |
|
||||
| **Session Memory** | Knowledge dies with each session | Persistent learning across agents |
|
||||
| **Skill Testing** | Hope it works | Test framework with assertions |
|
||||
|
||||
## 5-Minute Quick Start
|
||||
|
||||
```bash
|
||||
# Anthropic's official skill marketplace
|
||||
# 1. Install SkillKit globally
|
||||
npm install -g skillkit
|
||||
|
||||
# 2. Launch the interactive TUI (easiest way to start)
|
||||
skillkit
|
||||
|
||||
# Or use CLI commands directly:
|
||||
|
||||
# 3. Get personalized skill recommendations
|
||||
skillkit recommend
|
||||
|
||||
# 4. Install skills from the marketplace
|
||||
skillkit install anthropics/skills
|
||||
|
||||
# Vercel's React & Next.js best practices
|
||||
skillkit install vercel-labs/agent-skills/skills
|
||||
```
|
||||
|
||||
| Repository | Skills | Description |
|
||||
|------------|--------|-------------|
|
||||
| [anthropics/skills](https://github.com/anthropics/skills) | `pdf`, `xlsx`, `docx`, etc. | Official Claude Code skill marketplace |
|
||||
| [vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills) | `vercel-react-best-practices`, `web-design-guidelines` | React/Next.js optimization & UI review |
|
||||
|
||||
|
||||
## Commands
|
||||
|
||||
### `skillkit install <source>`
|
||||
|
||||
Install skills from various sources.
|
||||
|
||||
```bash
|
||||
# GitHub (default)
|
||||
skillkit install owner/repo
|
||||
skillkit install https://github.com/owner/repo
|
||||
|
||||
# Install from a subdirectory
|
||||
skillkit install owner/repo/skills
|
||||
|
||||
# GitLab
|
||||
skillkit install gitlab:owner/repo
|
||||
skillkit install https://gitlab.com/owner/repo
|
||||
|
||||
# Bitbucket
|
||||
skillkit install bitbucket:owner/repo
|
||||
|
||||
# Local path
|
||||
skillkit install ./my-skills
|
||||
skillkit install ~/dev/skills
|
||||
|
||||
# Options
|
||||
--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
|
||||
```
|
||||
|
||||
### `skillkit sync`
|
||||
|
||||
Sync installed skills to your agent's config file.
|
||||
|
||||
```bash
|
||||
# 5. Sync to your AI agent
|
||||
skillkit sync
|
||||
skillkit sync --agent cursor
|
||||
skillkit sync --output AGENTS.md
|
||||
skillkit sync --enabled-only
|
||||
```
|
||||
|
||||
### `skillkit read <skills>`
|
||||
## Core Features
|
||||
|
||||
Read skill content for AI agent consumption.
|
||||
### Cross-Agent Translation
|
||||
|
||||
Use any skill with any agent. SkillKit automatically converts between formats:
|
||||
|
||||
```bash
|
||||
skillkit read pdf
|
||||
skillkit read pdf,xlsx,docx # Multiple skills
|
||||
# Translate a Claude skill to Cursor format
|
||||
skillkit translate react-patterns --to cursor
|
||||
|
||||
# Translate all your skills to a new agent
|
||||
skillkit translate --all --to windsurf
|
||||
|
||||
# Preview translation without writing
|
||||
skillkit translate my-skill --to codex --dry-run
|
||||
```
|
||||
|
||||
### `skillkit list`
|
||||
**Supported Agents:** Claude Code, Cursor, Codex, Gemini CLI, OpenCode, Antigravity, Amp, Clawdbot, Droid, GitHub Copilot, Goose, Kilo, Kiro, Roo, Trae, Windsurf, Universal
|
||||
|
||||
List all installed skills.
|
||||
### Smart Recommendations
|
||||
|
||||
SkillKit analyzes your project and suggests the perfect skills:
|
||||
|
||||
```bash
|
||||
skillkit list
|
||||
skillkit list --enabled
|
||||
skillkit list --json
|
||||
skillkit recommend
|
||||
|
||||
# Project: my-app (Next.js + TypeScript + Tailwind)
|
||||
#
|
||||
# Recommended Skills:
|
||||
# 92% vercel-react-best-practices
|
||||
# 87% tailwind-v4-patterns
|
||||
# 85% nextjs-app-router
|
||||
# 78% typescript-strict-mode
|
||||
```
|
||||
|
||||
### `skillkit enable/disable <skills>`
|
||||
|
||||
Toggle skills on/off without removing them.
|
||||
Filter by task, category, or minimum score:
|
||||
|
||||
```bash
|
||||
skillkit enable pdf xlsx
|
||||
skillkit disable docx
|
||||
skillkit recommend --search "auth" # Task-based search
|
||||
skillkit recommend --category security # Category filter
|
||||
skillkit recommend --min-score 80 # Quality threshold
|
||||
```
|
||||
|
||||
### `skillkit update [skills]`
|
||||
### Session Memory System
|
||||
|
||||
Update skills from their original sources.
|
||||
Your AI agents learn, but that knowledge dies with the session. SkillKit captures learnings and makes them persistent:
|
||||
|
||||
```bash
|
||||
skillkit update # Update all
|
||||
skillkit update pdf xlsx # Update specific
|
||||
# Compress session observations into reusable learnings
|
||||
skillkit memory compress
|
||||
|
||||
# Search past learnings
|
||||
skillkit memory search "authentication patterns"
|
||||
|
||||
# Export a learning as a shareable skill
|
||||
skillkit memory export auth-insight --output auth-patterns.md
|
||||
|
||||
# Share memory across projects
|
||||
skillkit memory --global
|
||||
```
|
||||
|
||||
### `skillkit remove <skills>`
|
||||
### Skill Marketplace
|
||||
|
||||
Remove installed skills.
|
||||
Browse and install from curated skill repositories:
|
||||
|
||||
```bash
|
||||
skillkit remove pdf xlsx
|
||||
# Browse all available skills
|
||||
skillkit marketplace
|
||||
|
||||
# Search for specific skills
|
||||
skillkit marketplace search "react hooks"
|
||||
|
||||
# Filter by tags
|
||||
skillkit marketplace --tags typescript,testing
|
||||
|
||||
# Refresh the skill index
|
||||
skillkit marketplace refresh
|
||||
```
|
||||
|
||||
### `skillkit init`
|
||||
### Interactive TUI
|
||||
|
||||
Initialize skillkit in a project.
|
||||
Beautiful terminal interface for visual skill management:
|
||||
|
||||
```bash
|
||||
skillkit init
|
||||
skillkit init --agent cursor
|
||||
skillkit init --list # List supported agents
|
||||
skillkit ui
|
||||
# or just
|
||||
skillkit
|
||||
```
|
||||
|
||||
### `skillkit validate <path>`
|
||||
**Navigation:** `h` Home | `b` Browse | `r` Recommend | `t` Translate | `c` Context | `l` List | `s` Sync | `q` Quit
|
||||
|
||||
Validate skills against the [Agent Skills specification](https://agentskills.io/specification).
|
||||
### Skill Testing Framework
|
||||
|
||||
Test your skills with built-in assertions:
|
||||
|
||||
```bash
|
||||
skillkit validate ./my-skill # Validate single skill
|
||||
skillkit validate ./skills --all # Validate all skills in directory
|
||||
# Run all skill tests
|
||||
skillkit test
|
||||
|
||||
# Test specific skills
|
||||
skillkit test ./my-skill
|
||||
|
||||
# Run tests with specific tags
|
||||
skillkit test --tags unit,integration
|
||||
|
||||
# JSON output for CI
|
||||
skillkit test --json
|
||||
```
|
||||
|
||||
## Supported Agents
|
||||
### Workflow Orchestration
|
||||
|
||||
| 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/` |
|
||||
Compose skills into multi-step workflows:
|
||||
|
||||
```bash
|
||||
# List available workflows
|
||||
skillkit workflow list
|
||||
|
||||
# Run a workflow
|
||||
skillkit workflow run feature-development
|
||||
|
||||
# Create new workflow
|
||||
skillkit workflow create my-workflow
|
||||
```
|
||||
|
||||
### CI/CD Integration
|
||||
|
||||
Generate CI/CD templates for automated skill management:
|
||||
|
||||
```bash
|
||||
# GitHub Actions
|
||||
skillkit cicd github-action
|
||||
|
||||
# GitLab CI
|
||||
skillkit cicd gitlab-ci
|
||||
|
||||
# Pre-commit hooks
|
||||
skillkit cicd pre-commit
|
||||
```
|
||||
|
||||
## Supported Agents (17)
|
||||
|
||||
| Agent | Format | Skills Directory |
|
||||
|-------|--------|------------------|
|
||||
| Claude Code | SKILL.md | `.claude/skills/` |
|
||||
| Cursor | MDC (.mdc) | `.cursor/skills/` |
|
||||
| Codex | SKILL.md | `.codex/skills/` |
|
||||
| Gemini CLI | SKILL.md | `.gemini/skills/` |
|
||||
| OpenCode | SKILL.md | `.opencode/skills/` |
|
||||
| Antigravity | SKILL.md | `.antigravity/skills/` |
|
||||
| Amp | SKILL.md | `.amp/skills/` |
|
||||
| Clawdbot | SKILL.md | `skills/` |
|
||||
| Droid (Factory) | SKILL.md | `.factory/skills/` |
|
||||
| GitHub Copilot | Markdown | `.github/skills/` |
|
||||
| Goose | SKILL.md | `.goose/skills/` |
|
||||
| Kilo Code | SKILL.md | `.kilocode/skills/` |
|
||||
| Kiro CLI | SKILL.md | `.kiro/skills/` |
|
||||
| Roo Code | SKILL.md | `.roo/skills/` |
|
||||
| Trae | SKILL.md | `.trae/skills/` |
|
||||
| Windsurf | Markdown | `.windsurf/skills/` |
|
||||
| Universal | SKILL.md | `skills/` |
|
||||
|
||||
## All Commands
|
||||
|
||||
### Skill Management
|
||||
|
||||
```bash
|
||||
skillkit install <source> # Install skills from GitHub/GitLab/Bitbucket/local
|
||||
skillkit remove <skills> # Remove installed skills
|
||||
skillkit update [skills] # Update skills from source
|
||||
skillkit list # List installed skills
|
||||
skillkit enable <skills> # Enable specific skills
|
||||
skillkit disable <skills> # Disable specific skills
|
||||
skillkit sync # Sync skills to agent config
|
||||
skillkit read <skills> # Read skill content for AI
|
||||
```
|
||||
|
||||
### Discovery & Recommendations
|
||||
|
||||
```bash
|
||||
skillkit recommend # Get smart recommendations
|
||||
skillkit marketplace # Browse skill marketplace
|
||||
skillkit marketplace search # Search marketplace
|
||||
```
|
||||
|
||||
### Translation & Context
|
||||
|
||||
```bash
|
||||
skillkit translate # Translate between formats
|
||||
skillkit context init # Initialize project context
|
||||
skillkit context sync # Sync context to agents
|
||||
```
|
||||
|
||||
### Memory System
|
||||
|
||||
```bash
|
||||
skillkit memory status # View memory status
|
||||
skillkit memory search # Search learnings
|
||||
skillkit memory compress # Compress observations
|
||||
skillkit memory export # Export as skill
|
||||
```
|
||||
|
||||
### Testing & Workflows
|
||||
|
||||
```bash
|
||||
skillkit test # Run skill tests
|
||||
skillkit workflow run # Execute workflow
|
||||
skillkit cicd # Generate CI/CD templates
|
||||
```
|
||||
|
||||
### Utilities
|
||||
|
||||
```bash
|
||||
skillkit init # Initialize in project
|
||||
skillkit validate # Validate skill format
|
||||
skillkit create # Create new skill
|
||||
```
|
||||
|
||||
## Creating Skills
|
||||
|
||||
A skill is a directory with a `SKILL.md` file:
|
||||
### Quick Start
|
||||
|
||||
```
|
||||
my-skill/
|
||||
├── SKILL.md # Required: Instructions for the AI
|
||||
├── references/ # Optional: Documentation
|
||||
├── scripts/ # Optional: Helper scripts
|
||||
└── assets/ # Optional: Templates, configs
|
||||
```bash
|
||||
skillkit create my-skill
|
||||
```
|
||||
|
||||
### SKILL.md Format
|
||||
### Manual Creation
|
||||
|
||||
Follows the [Agent Skills specification](https://agentskills.io/specification):
|
||||
Create a `SKILL.md` file following the [Agent Skills specification](https://agentskills.io/specification):
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: my-skill
|
||||
description: What this skill does and when to use it. Include trigger keywords.
|
||||
description: What this skill does and when to use it
|
||||
license: MIT
|
||||
compatibility: Requires Node.js 18+
|
||||
metadata:
|
||||
author: your-org
|
||||
author: your-name
|
||||
version: "1.0"
|
||||
---
|
||||
|
||||
# My Skill
|
||||
|
||||
Instructions for the AI agent on how to use this skill.
|
||||
Instructions for the AI agent.
|
||||
|
||||
## When to Use
|
||||
|
||||
- Scenario 1
|
||||
- Scenario 2
|
||||
|
||||
## Steps
|
||||
|
||||
1. First step
|
||||
2. Second step
|
||||
```
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `name` | Yes | Lowercase alphanumeric with hyphens (max 64 chars) |
|
||||
| `description` | Yes | What it does and when to use it (max 1024 chars) |
|
||||
| `license` | No | License name or reference |
|
||||
| `compatibility` | No | Environment requirements |
|
||||
| `metadata` | No | Arbitrary key-value pairs |
|
||||
|
||||
## CI/CD Usage
|
||||
|
||||
```yaml
|
||||
# GitHub Actions example
|
||||
- name: Setup skills
|
||||
run: |
|
||||
npx skillkit install owner/skills --skills=lint,test,deploy --yes
|
||||
npx skillkit sync --yes
|
||||
```
|
||||
|
||||
## Programmatic API
|
||||
|
||||
```typescript
|
||||
import {
|
||||
// Skill discovery
|
||||
findAllSkills,
|
||||
discoverSkills,
|
||||
detectAgent,
|
||||
getAdapter,
|
||||
|
||||
// Translation
|
||||
translateSkill,
|
||||
translateSkillFile,
|
||||
|
||||
// Recommendations
|
||||
RecommendationEngine,
|
||||
analyzeProject,
|
||||
|
||||
// Context
|
||||
ContextManager,
|
||||
syncToAllAgents,
|
||||
|
||||
// Memory
|
||||
createMemoryCompressor,
|
||||
createMemoryInjector,
|
||||
LearningStore,
|
||||
|
||||
// Marketplace
|
||||
createMarketplaceAggregator,
|
||||
|
||||
// Testing
|
||||
SkillTestRunner,
|
||||
|
||||
// Workflows
|
||||
WorkflowOrchestrator,
|
||||
} from 'skillkit';
|
||||
|
||||
// Find all installed skills
|
||||
const skills = findAllSkills(searchDirs);
|
||||
// Example: Translate and install
|
||||
const skill = await translateSkill(skillContent, 'cursor');
|
||||
console.log(skill.content);
|
||||
|
||||
// Detect current agent
|
||||
const agent = await detectAgent();
|
||||
// Example: Get recommendations
|
||||
const engine = new RecommendationEngine();
|
||||
const profile = await analyzeProject('./my-project');
|
||||
const recs = engine.recommend(profile);
|
||||
```
|
||||
|
||||
// Generate config
|
||||
const adapter = getAdapter(agent);
|
||||
const config = adapter.generateConfig(skills);
|
||||
## Popular Skill Repositories
|
||||
|
||||
| Repository | Description |
|
||||
|------------|-------------|
|
||||
| [anthropics/skills](https://github.com/anthropics/skills) | Official Claude Code marketplace - PDF, XLSX, DOCX processing |
|
||||
| [vercel-labs/agent-skills](https://github.com/vercel-labs/agent-skills) | React/Next.js best practices, web design guidelines |
|
||||
|
||||
## Installation Options
|
||||
|
||||
```bash
|
||||
# npm (recommended)
|
||||
npm install -g skillkit
|
||||
|
||||
# pnpm
|
||||
pnpm add -g skillkit
|
||||
|
||||
# yarn
|
||||
yarn global add skillkit
|
||||
|
||||
# bun
|
||||
bun add -g skillkit
|
||||
|
||||
# npx (no install)
|
||||
npx skillkit <command>
|
||||
```
|
||||
|
||||
## Configuration
|
||||
@@ -300,14 +420,26 @@ disabledSkills:
|
||||
- deprecated-skill
|
||||
```
|
||||
|
||||
## Why SkillKit Exists
|
||||
|
||||
AI coding agents are amazing, but the ecosystem is fragmented:
|
||||
- **Skills don't transfer** between agents
|
||||
- **Knowledge dies** when sessions end
|
||||
- **No standard** for skill quality or testing
|
||||
- **Manual discovery** of useful skills
|
||||
|
||||
SkillKit solves these problems with a universal platform that works across all major AI coding agents.
|
||||
|
||||
## 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).
|
||||
|
||||
## Acknowledgments
|
||||
## Links
|
||||
|
||||
Implements the [Agent Skills](https://agentskills.io) open format, originally developed by Anthropic and adopted by leading AI development tools.
|
||||
- [Agent Skills Specification](https://agentskills.io/specification)
|
||||
- [GitHub Repository](https://github.com/rohitg00/skillkit)
|
||||
- [NPM Package](https://www.npmjs.com/package/skillkit)
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,201 @@
|
||||
# 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 skills from GitHub
|
||||
skillkit install anthropics/skills
|
||||
|
||||
# Get recommendations for your stack
|
||||
skillkit recommend
|
||||
|
||||
# Launch interactive TUI
|
||||
skillkit ui
|
||||
```
|
||||
|
||||
## Core Features
|
||||
|
||||
### Cross-Agent Translation
|
||||
|
||||
```bash
|
||||
# Translate a Claude skill to Cursor format
|
||||
skillkit translate react-patterns --to cursor
|
||||
|
||||
# Translate all skills to multiple agents
|
||||
skillkit translate --all --to windsurf,codex
|
||||
|
||||
# Preview translation
|
||||
skillkit translate my-skill --to copilot --dry-run
|
||||
```
|
||||
|
||||
### Smart Recommendations
|
||||
|
||||
```bash
|
||||
# Get project-aware suggestions
|
||||
skillkit recommend
|
||||
|
||||
# Filter by task
|
||||
skillkit recommend --search "authentication"
|
||||
|
||||
# Quality threshold
|
||||
skillkit recommend --min-score 85
|
||||
```
|
||||
|
||||
### Team Collaboration
|
||||
|
||||
```bash
|
||||
# Initialize team
|
||||
skillkit team init --name "Engineering Team"
|
||||
|
||||
# Create skill bundle
|
||||
skillkit team bundle-create
|
||||
|
||||
# Share with team
|
||||
skillkit team share onboarding-bundle
|
||||
|
||||
# Sync with remote registry
|
||||
skillkit team sync
|
||||
```
|
||||
|
||||
### Plugin System
|
||||
|
||||
```bash
|
||||
# List installed plugins
|
||||
skillkit plugin list
|
||||
|
||||
# Install custom plugin
|
||||
skillkit plugin install @company/custom-translator
|
||||
|
||||
# View plugin info
|
||||
skillkit plugin info my-plugin
|
||||
```
|
||||
|
||||
### Development Methodologies
|
||||
|
||||
```bash
|
||||
# List available methodologies
|
||||
skillkit methodology list
|
||||
|
||||
# Load TDD methodology
|
||||
skillkit methodology load tdd
|
||||
|
||||
# Apply to project
|
||||
skillkit methodology apply agile
|
||||
```
|
||||
|
||||
### Plan System
|
||||
|
||||
```bash
|
||||
# Parse and validate plan
|
||||
skillkit plan parse ./implementation-plan.md
|
||||
skillkit plan validate ./plan.md
|
||||
|
||||
# Execute plan
|
||||
skillkit plan execute ./feature-plan.md
|
||||
|
||||
# Check status
|
||||
skillkit plan status
|
||||
```
|
||||
|
||||
### Hooks & Automation
|
||||
|
||||
```bash
|
||||
# List hooks
|
||||
skillkit hook list
|
||||
|
||||
# Register pre-commit hook
|
||||
skillkit hook register pre-commit
|
||||
|
||||
# Trigger manually
|
||||
skillkit hook trigger pre-commit
|
||||
```
|
||||
|
||||
### Workflow Orchestration
|
||||
|
||||
```bash
|
||||
# List workflows
|
||||
skillkit workflow list
|
||||
|
||||
# Run workflow
|
||||
skillkit workflow run feature-development
|
||||
|
||||
# Create new workflow
|
||||
skillkit workflow create deployment-flow
|
||||
```
|
||||
|
||||
### Session Memory
|
||||
|
||||
```bash
|
||||
# View learnings
|
||||
skillkit memory list
|
||||
|
||||
# Search past sessions
|
||||
skillkit memory search "error handling"
|
||||
|
||||
# Compress observations
|
||||
skillkit memory compress
|
||||
|
||||
# Export learning as skill
|
||||
skillkit memory export auth-insight --output auth-skill.md
|
||||
```
|
||||
|
||||
## Supported Agents (17)
|
||||
|
||||
Claude Code, Cursor, Codex, Gemini CLI, Windsurf, GitHub Copilot, OpenCode, Antigravity, Amp, Clawdbot, Droid, Goose, Kilo, Kiro, Roo, Trae, Universal
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Install and Sync
|
||||
|
||||
```bash
|
||||
# Install to multiple agents
|
||||
skillkit install anthropics/skills --agent claude-code,cursor
|
||||
|
||||
# Sync all skills to detected agents
|
||||
skillkit sync --all
|
||||
```
|
||||
|
||||
### Context Management
|
||||
|
||||
```bash
|
||||
# Initialize project context
|
||||
skillkit context init
|
||||
|
||||
# View detected stack
|
||||
skillkit context show
|
||||
|
||||
# Sync to all agents
|
||||
skillkit context sync --all
|
||||
```
|
||||
|
||||
### Testing
|
||||
|
||||
```bash
|
||||
# Run all skill tests
|
||||
skillkit test
|
||||
|
||||
# Test specific skills
|
||||
skillkit test ./my-skill --tags unit
|
||||
|
||||
# CI/CD integration
|
||||
skillkit cicd init
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"name": "skillkit",
|
||||
"version": "1.6.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": "^1.6.0",
|
||||
"@skillkit/agents": "^1.6.0",
|
||||
"@skillkit/cli": "^1.6.0",
|
||||
"@skillkit/tui": "^1.6.0",
|
||||
"clipanion": "^4.0.0-rc.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.5",
|
||||
"tsup": "^8.3.5",
|
||||
"typescript": "^5.7.2",
|
||||
"vitest": "^2.1.8"
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/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,
|
||||
SettingsCommand,
|
||||
CICDCommand,
|
||||
TeamCommand,
|
||||
PluginCommand,
|
||||
MethodologyCommand,
|
||||
HookCommand,
|
||||
PlanCommand,
|
||||
CommandCmd,
|
||||
AICommand,
|
||||
AuditCommand,
|
||||
} 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.register(SettingsCommand);
|
||||
cli.register(CICDCommand);
|
||||
cli.register(TeamCommand);
|
||||
cli.register(PluginCommand);
|
||||
cli.register(MethodologyCommand);
|
||||
cli.register(HookCommand);
|
||||
cli.register(PlanCommand);
|
||||
cli.register(CommandCmd);
|
||||
cli.register(AICommand);
|
||||
cli.register(AuditCommand);
|
||||
|
||||
cli.runExit(process.argv.slice(2));
|
||||
@@ -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';
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"composite": false
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -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 |
Generated
+572
-2
@@ -1,19 +1,24 @@
|
||||
{
|
||||
"name": "skillkit",
|
||||
"version": "1.0.0",
|
||||
"version": "1.5.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "skillkit",
|
||||
"version": "1.0.0",
|
||||
"version": "1.5.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
@@ -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.6.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"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
# @skillkit/agents
|
||||
|
||||
[](https://www.npmjs.com/package/@skillkit/agents)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
**Agent adapters for SkillKit** - configuration and detection for 17 AI coding agents.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @skillkit/agents
|
||||
```
|
||||
|
||||
## Supported Agents (17)
|
||||
|
||||
| Agent | Config Format | Project Skills | Global Skills |
|
||||
|-------|--------------|----------------|---------------|
|
||||
| Claude Code | SKILL.md | `.claude/skills/` | `~/.claude/skills/` |
|
||||
| Cursor | MDC (.mdc) | `.cursor/skills/` | `~/.cursor/skills/` |
|
||||
| Codex | SKILL.md | `.codex/skills/` | `~/.codex/skills/` |
|
||||
| Gemini CLI | SKILL.md | `.gemini/skills/` | `~/.gemini/skills/` |
|
||||
| OpenCode | SKILL.md | `.opencode/skills/` | `~/.config/opencode/skills/` |
|
||||
| Antigravity | SKILL.md | `.antigravity/skills/` | `~/.gemini/antigravity/skills/` |
|
||||
| Amp | SKILL.md | `.agents/skills/` | `~/.config/agents/skills/` |
|
||||
| Clawdbot | SKILL.md | `skills/` | `~/.clawdbot/skills/` |
|
||||
| Droid (Factory) | SKILL.md | `.factory/skills/` | `~/.factory/skills/` |
|
||||
| GitHub Copilot | Markdown | `.github/skills/` | `~/.copilot/skills/` |
|
||||
| Goose | SKILL.md | `.goose/skills/` | `~/.config/goose/skills/` |
|
||||
| Kilo Code | SKILL.md | `.kilocode/skills/` | `~/.kilocode/skills/` |
|
||||
| Kiro CLI | SKILL.md | `.kiro/skills/` | `~/.kiro/skills/` |
|
||||
| Roo Code | SKILL.md | `.roo/skills/` | `~/.roo/skills/` |
|
||||
| Trae | SKILL.md | `.trae/skills/` | `~/.trae/skills/` |
|
||||
| Windsurf | Markdown | `.windsurf/skills/` | `~/.codeium/windsurf/skills/` |
|
||||
| Universal | SKILL.md | `skills/` | `~/.agent/skills/` |
|
||||
|
||||
## Usage
|
||||
|
||||
### Get Agent Adapter
|
||||
|
||||
```typescript
|
||||
import { getAdapter, AgentType } from '@skillkit/agents';
|
||||
|
||||
// Get adapter for specific agent
|
||||
const adapter = getAdapter('claude-code');
|
||||
|
||||
console.log(adapter.name); // 'claude-code'
|
||||
console.log(adapter.skillsDir); // '.claude/skills/'
|
||||
console.log(adapter.globalSkillsDir); // '~/.claude/skills/'
|
||||
console.log(adapter.configFile); // 'AGENTS.md'
|
||||
console.log(adapter.format); // 'skill-md'
|
||||
```
|
||||
|
||||
### Detect Installed Agents
|
||||
|
||||
```typescript
|
||||
import { detectAgent, detectAllAgents } from '@skillkit/agents';
|
||||
|
||||
// Detect primary agent in current directory
|
||||
const primary = await detectAgent();
|
||||
console.log(primary); // 'claude-code'
|
||||
|
||||
// Detect all installed agents
|
||||
const all = await detectAllAgents();
|
||||
console.log(all); // ['claude-code', 'cursor', 'windsurf']
|
||||
|
||||
// Detect in specific directory
|
||||
const agents = await detectAllAgents('./my-project');
|
||||
```
|
||||
|
||||
### List All Adapters
|
||||
|
||||
```typescript
|
||||
import { listAdapters, getAdapterNames } from '@skillkit/agents';
|
||||
|
||||
// Get all adapter configurations
|
||||
const adapters = listAdapters();
|
||||
adapters.forEach(adapter => {
|
||||
console.log(`${adapter.name}: ${adapter.skillsDir}`);
|
||||
});
|
||||
|
||||
// Get just the names
|
||||
const names = getAdapterNames();
|
||||
console.log(names); // ['claude-code', 'cursor', 'codex', ...]
|
||||
```
|
||||
|
||||
### Generate Agent Config
|
||||
|
||||
```typescript
|
||||
import { getAdapter } from '@skillkit/agents';
|
||||
import { findAllSkills } from '@skillkit/core';
|
||||
|
||||
const adapter = getAdapter('cursor');
|
||||
const skills = findAllSkills([adapter.skillsDir]);
|
||||
|
||||
// Generate config file content
|
||||
const config = adapter.generateConfig(skills);
|
||||
console.log(config);
|
||||
```
|
||||
|
||||
### Get Skills Directory
|
||||
|
||||
```typescript
|
||||
import { getAdapter } from '@skillkit/agents';
|
||||
import { homedir } from 'os';
|
||||
|
||||
const adapter = getAdapter('claude-code');
|
||||
|
||||
// Project-local skills directory
|
||||
const projectDir = adapter.skillsDir; // '.claude/skills/'
|
||||
|
||||
// Global skills directory
|
||||
const globalDir = adapter.globalSkillsDir.replace('~', homedir());
|
||||
// '/Users/you/.claude/skills/'
|
||||
```
|
||||
|
||||
## Adapter Interface
|
||||
|
||||
```typescript
|
||||
interface AgentAdapter {
|
||||
// Agent identifier
|
||||
name: AgentType;
|
||||
|
||||
// Display name
|
||||
displayName: string;
|
||||
|
||||
// Skill file format
|
||||
format: 'skill-md' | 'mdc' | 'markdown';
|
||||
|
||||
// Project skills directory (relative)
|
||||
skillsDir: string;
|
||||
|
||||
// Global skills directory (with ~)
|
||||
globalSkillsDir: string;
|
||||
|
||||
// Config file name
|
||||
configFile: string;
|
||||
|
||||
// Generate config from skills
|
||||
generateConfig(skills: Skill[]): string;
|
||||
|
||||
// Parse existing config
|
||||
parseConfig(content: string): Skill[];
|
||||
}
|
||||
```
|
||||
|
||||
## Agent Types
|
||||
|
||||
```typescript
|
||||
type AgentType =
|
||||
| 'claude-code'
|
||||
| 'cursor'
|
||||
| 'codex'
|
||||
| 'gemini-cli'
|
||||
| 'opencode'
|
||||
| 'antigravity'
|
||||
| 'amp'
|
||||
| 'clawdbot'
|
||||
| 'droid'
|
||||
| 'github-copilot'
|
||||
| 'goose'
|
||||
| 'kilo'
|
||||
| 'kiro-cli'
|
||||
| 'roo'
|
||||
| 'trae'
|
||||
| 'windsurf'
|
||||
| 'universal';
|
||||
```
|
||||
|
||||
## Format Details
|
||||
|
||||
### SKILL.md Format
|
||||
Used by most agents. YAML frontmatter + Markdown content:
|
||||
```markdown
|
||||
---
|
||||
name: my-skill
|
||||
description: What this skill does
|
||||
---
|
||||
# My Skill
|
||||
Instructions...
|
||||
```
|
||||
|
||||
### MDC Format (Cursor)
|
||||
Cursor-specific format with globs and alwaysApply:
|
||||
```
|
||||
---
|
||||
description: What this skill does
|
||||
globs: ["**/*.tsx"]
|
||||
alwaysApply: false
|
||||
---
|
||||
Instructions...
|
||||
```
|
||||
|
||||
### Markdown Format
|
||||
Plain markdown used by Windsurf and Copilot:
|
||||
```markdown
|
||||
# Skill Name
|
||||
Instructions for the agent...
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@skillkit/agents",
|
||||
"version": "1.6.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": "^1.6.0",
|
||||
"minimatch": "^9.0.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,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');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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')));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
/**
|
||||
* Agent Features Tests
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import {
|
||||
PermissionManager,
|
||||
createPermissionManager,
|
||||
isAllowed,
|
||||
isDenied,
|
||||
needsConfirmation,
|
||||
} from '../permissions.js';
|
||||
import {
|
||||
GlobMatcher,
|
||||
createGlobMatcher,
|
||||
matchPattern,
|
||||
parseGlobsFromMDC,
|
||||
fromCommonPatterns,
|
||||
COMMON_PATTERNS,
|
||||
} from '../globs.js';
|
||||
import {
|
||||
BootstrapManager,
|
||||
createBootstrapManager,
|
||||
createBootstrapSet,
|
||||
} from '../bootstrap.js';
|
||||
import {
|
||||
ModeManager,
|
||||
createModeManager,
|
||||
createDefaultModeManager,
|
||||
ALL_MODES,
|
||||
} from '../modes.js';
|
||||
import type { PermissionConfig, GlobConfig, ModeConfig } from '../types.js';
|
||||
|
||||
describe('PermissionManager', () => {
|
||||
let manager: PermissionManager;
|
||||
|
||||
beforeEach(() => {
|
||||
manager = createPermissionManager();
|
||||
});
|
||||
|
||||
describe('checkFileAccess', () => {
|
||||
it('should return default permission for unmatched files', () => {
|
||||
manager.setConfig({ default: 'ask' });
|
||||
expect(manager.checkFileAccess('some/file.ts')).toBe('ask');
|
||||
});
|
||||
|
||||
it('should match file patterns', () => {
|
||||
manager.setConfig({
|
||||
files: [
|
||||
{ pattern: '*.ts', level: 'allow' },
|
||||
{ pattern: 'secret/*', level: 'deny' },
|
||||
],
|
||||
default: 'ask',
|
||||
});
|
||||
|
||||
expect(manager.checkFileAccess('app.ts')).toBe('allow');
|
||||
expect(manager.checkFileAccess('secret/keys.json')).toBe('deny');
|
||||
expect(manager.checkFileAccess('random.json')).toBe('ask');
|
||||
});
|
||||
|
||||
it('should use first matching pattern', () => {
|
||||
manager.setConfig({
|
||||
files: [
|
||||
{ pattern: '*.ts', level: 'deny' },
|
||||
{ pattern: 'src/*.ts', level: 'allow' },
|
||||
],
|
||||
});
|
||||
|
||||
expect(manager.checkFileAccess('app.ts')).toBe('deny');
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkCommandAccess', () => {
|
||||
it('should check command patterns', () => {
|
||||
manager.setConfig({
|
||||
commands: [
|
||||
{ pattern: 'npm *', level: 'allow' },
|
||||
{ pattern: 'rm *', level: 'deny' },
|
||||
],
|
||||
default: 'ask',
|
||||
});
|
||||
|
||||
expect(manager.checkCommandAccess('npm install')).toBe('allow');
|
||||
expect(manager.checkCommandAccess('rm -rf /')).toBe('deny');
|
||||
expect(manager.checkCommandAccess('git status')).toBe('ask');
|
||||
});
|
||||
});
|
||||
|
||||
describe('addFilePattern', () => {
|
||||
it('should add file pattern', () => {
|
||||
manager.addFilePattern({ pattern: '*.js', level: 'allow' });
|
||||
|
||||
expect(manager.checkFileAccess('app.js')).toBe('allow');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateOpenCodeConfig', () => {
|
||||
it('should generate OpenCode-compatible config', () => {
|
||||
manager.setConfig({
|
||||
files: [{ pattern: 'src/*', level: 'allow' }],
|
||||
commands: [{ pattern: 'npm *', level: 'allow' }],
|
||||
default: 'ask',
|
||||
});
|
||||
|
||||
const config = manager.generateOpenCodeConfig();
|
||||
|
||||
expect(config).toContain('File Access');
|
||||
expect(config).toContain('allow: `src/*`');
|
||||
expect(config).toContain('Command Execution');
|
||||
expect(config).toContain('Default: ask');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateSkillMetadata', () => {
|
||||
it('should generate skill metadata', () => {
|
||||
manager.setConfig({
|
||||
files: [{ pattern: '*.ts', level: 'allow' }],
|
||||
default: 'deny',
|
||||
});
|
||||
|
||||
const metadata = manager.generateSkillMetadata();
|
||||
|
||||
expect(metadata.filePermissions).toHaveLength(1);
|
||||
expect(metadata.defaultPermission).toBe('deny');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fromMetadata', () => {
|
||||
it('should parse permissions from metadata', () => {
|
||||
const metadata = {
|
||||
filePermissions: [{ pattern: '*.ts', level: 'allow' }],
|
||||
defaultPermission: 'ask',
|
||||
};
|
||||
|
||||
const config = PermissionManager.fromMetadata(metadata);
|
||||
|
||||
expect(config.files).toHaveLength(1);
|
||||
expect(config.default).toBe('ask');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Permission helpers', () => {
|
||||
it('isAllowed should work correctly', () => {
|
||||
expect(isAllowed('allow')).toBe(true);
|
||||
expect(isAllowed('deny')).toBe(false);
|
||||
expect(isAllowed('ask')).toBe(false);
|
||||
});
|
||||
|
||||
it('isDenied should work correctly', () => {
|
||||
expect(isDenied('deny')).toBe(true);
|
||||
expect(isDenied('allow')).toBe(false);
|
||||
});
|
||||
|
||||
it('needsConfirmation should work correctly', () => {
|
||||
expect(needsConfirmation('ask')).toBe(true);
|
||||
expect(needsConfirmation('allow')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GlobMatcher', () => {
|
||||
let matcher: GlobMatcher;
|
||||
|
||||
describe('matches', () => {
|
||||
it('should match simple patterns', () => {
|
||||
matcher = createGlobMatcher({ include: ['*.ts'] });
|
||||
|
||||
expect(matcher.matches('app.ts')).toBe(true);
|
||||
expect(matcher.matches('app.js')).toBe(false);
|
||||
});
|
||||
|
||||
it('should match wildcard patterns', () => {
|
||||
matcher = createGlobMatcher({ include: ['src/**/*.ts'] });
|
||||
|
||||
expect(matcher.matches('src/app.ts')).toBe(true);
|
||||
expect(matcher.matches('src/components/Button.ts')).toBe(true);
|
||||
expect(matcher.matches('lib/app.ts')).toBe(false);
|
||||
});
|
||||
|
||||
it('should respect exclude patterns', () => {
|
||||
matcher = createGlobMatcher({
|
||||
include: ['**/*.ts'],
|
||||
exclude: ['**/*.test.ts'],
|
||||
});
|
||||
|
||||
expect(matcher.matches('app.ts')).toBe(true);
|
||||
expect(matcher.matches('app.test.ts')).toBe(false);
|
||||
});
|
||||
|
||||
it('should skip hidden files by default', () => {
|
||||
matcher = createGlobMatcher({ include: ['**/*'] });
|
||||
|
||||
expect(matcher.matches('.hidden/file.ts')).toBe(false);
|
||||
});
|
||||
|
||||
it('should match hidden files when enabled', () => {
|
||||
matcher = createGlobMatcher({
|
||||
include: ['**/*'],
|
||||
matchHidden: true,
|
||||
});
|
||||
|
||||
expect(matcher.matches('.hidden/file.ts')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('filter', () => {
|
||||
it('should filter file list', () => {
|
||||
matcher = createGlobMatcher({ include: ['*.ts'] });
|
||||
|
||||
const files = ['app.ts', 'app.js', 'index.ts'];
|
||||
const result = matcher.filter(files);
|
||||
|
||||
expect(result).toEqual(['app.ts', 'index.ts']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addInclude', () => {
|
||||
it('should add include pattern', () => {
|
||||
matcher = createGlobMatcher({ include: ['*.ts'] });
|
||||
matcher.addInclude('*.js');
|
||||
|
||||
expect(matcher.matches('app.js')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateCursorGlobs', () => {
|
||||
it('should generate Cursor-compatible globs', () => {
|
||||
matcher = createGlobMatcher({
|
||||
include: ['src/**/*.ts'],
|
||||
exclude: ['**/*.test.ts'],
|
||||
});
|
||||
|
||||
const globs = matcher.generateCursorGlobs();
|
||||
|
||||
expect(globs).toContain('src/**/*.ts');
|
||||
expect(globs).toContain('!**/*.test.ts');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('matchPattern', () => {
|
||||
it('should create matcher from single pattern', () => {
|
||||
const matcher = matchPattern('*.ts');
|
||||
|
||||
expect(matcher.matches('app.ts')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseGlobsFromMDC', () => {
|
||||
it('should parse globs from MDC content', () => {
|
||||
const content = `---
|
||||
globs: ["**/*.ts", "!**/*.test.ts"]
|
||||
---
|
||||
Content here`;
|
||||
|
||||
const config = parseGlobsFromMDC(content);
|
||||
|
||||
expect(config?.include).toContain('**/*.ts');
|
||||
expect(config?.exclude).toContain('**/*.test.ts');
|
||||
});
|
||||
|
||||
it('should return null for invalid content', () => {
|
||||
const result = parseGlobsFromMDC('no globs here');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('fromCommonPatterns', () => {
|
||||
it('should create config from common patterns', () => {
|
||||
const config = fromCommonPatterns(['typescript', 'source'], ['nodeModules']);
|
||||
|
||||
expect(config.include).toContain('**/*.ts');
|
||||
expect(config.include).toContain('src/**/*');
|
||||
expect(config.exclude).toContain('**/node_modules/**');
|
||||
});
|
||||
});
|
||||
|
||||
describe('COMMON_PATTERNS', () => {
|
||||
it('should have expected patterns', () => {
|
||||
expect(COMMON_PATTERNS.typescript).toContain('**/*.ts');
|
||||
expect(COMMON_PATTERNS.tests).toContain('**/*.test.*');
|
||||
expect(COMMON_PATTERNS.nodeModules).toContain('**/node_modules/**');
|
||||
});
|
||||
});
|
||||
|
||||
describe('BootstrapManager', () => {
|
||||
let manager: BootstrapManager;
|
||||
|
||||
beforeEach(() => {
|
||||
manager = createBootstrapManager();
|
||||
});
|
||||
|
||||
describe('addFile/getFile', () => {
|
||||
it('should add and get files', () => {
|
||||
manager.addFile({
|
||||
type: 'agents',
|
||||
name: 'AGENTS.md',
|
||||
content: '# Agents',
|
||||
priority: 100,
|
||||
});
|
||||
|
||||
const file = manager.getFile('agents');
|
||||
|
||||
expect(file).toBeDefined();
|
||||
expect(file?.name).toBe('AGENTS.md');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFilesByPriority', () => {
|
||||
it('should return files sorted by priority', () => {
|
||||
manager.addFile({ type: 'tools', name: 'TOOLS.md', content: '', priority: 10 });
|
||||
manager.addFile({ type: 'agents', name: 'AGENTS.md', content: '', priority: 100 });
|
||||
manager.addFile({ type: 'soul', name: 'SOUL.md', content: '', priority: 50 });
|
||||
|
||||
const files = manager.getFilesByPriority();
|
||||
|
||||
expect(files[0].type).toBe('agents');
|
||||
expect(files[1].type).toBe('soul');
|
||||
expect(files[2].type).toBe('tools');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createAgentsFile', () => {
|
||||
it('should create AGENTS.md', () => {
|
||||
manager.createAgentsFile([
|
||||
{
|
||||
name: 'Coder',
|
||||
description: 'A coding agent',
|
||||
capabilities: ['Write code', 'Debug'],
|
||||
},
|
||||
]);
|
||||
|
||||
const file = manager.getFile('agents');
|
||||
|
||||
expect(file).toBeDefined();
|
||||
expect(file?.content).toContain('# Agents');
|
||||
expect(file?.content).toContain('## Coder');
|
||||
expect(file?.content).toContain('Write code');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createSoulFile', () => {
|
||||
it('should create SOUL.md', () => {
|
||||
manager.createSoulFile({
|
||||
personality: 'Helpful and precise',
|
||||
values: ['Accuracy', 'Efficiency'],
|
||||
});
|
||||
|
||||
const file = manager.getFile('soul');
|
||||
|
||||
expect(file).toBeDefined();
|
||||
expect(file?.content).toContain('Helpful and precise');
|
||||
expect(file?.content).toContain('Accuracy');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createToolsFile', () => {
|
||||
it('should create TOOLS.md', () => {
|
||||
manager.createToolsFile([
|
||||
{
|
||||
name: 'read_file',
|
||||
description: 'Read a file',
|
||||
usage: 'read_file(path)',
|
||||
},
|
||||
]);
|
||||
|
||||
const file = manager.getFile('tools');
|
||||
|
||||
expect(file).toBeDefined();
|
||||
expect(file?.content).toContain('## read_file');
|
||||
expect(file?.content).toContain('read_file(path)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateCombinedContent', () => {
|
||||
it('should generate combined content', () => {
|
||||
manager.addFile({ type: 'agents', name: 'AGENTS.md', content: '# Agents', priority: 100 });
|
||||
manager.addFile({ type: 'soul', name: 'SOUL.md', content: '# Soul', priority: 50 });
|
||||
|
||||
const combined = manager.generateCombinedContent();
|
||||
|
||||
expect(combined).toContain('<!-- AGENTS.md -->');
|
||||
expect(combined).toContain('# Agents');
|
||||
expect(combined).toContain('<!-- SOUL.md -->');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBootstrapSet', () => {
|
||||
it('should create complete bootstrap set', () => {
|
||||
const manager = createBootstrapSet({
|
||||
agents: [{ name: 'Test Agent' }],
|
||||
soul: { personality: 'Friendly' },
|
||||
tools: [{ name: 'tool1' }],
|
||||
});
|
||||
|
||||
expect(manager.hasFile('agents')).toBe(true);
|
||||
expect(manager.hasFile('soul')).toBe(true);
|
||||
expect(manager.hasFile('tools')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ModeManager', () => {
|
||||
let manager: ModeManager;
|
||||
|
||||
beforeEach(() => {
|
||||
manager = createModeManager([
|
||||
{ mode: 'code', description: 'Coding mode', skills: ['tdd', 'debugging'] },
|
||||
{ mode: 'architect', description: 'Architecture mode', skills: ['planning'] },
|
||||
]);
|
||||
});
|
||||
|
||||
describe('addMode/getMode', () => {
|
||||
it('should add and get modes', () => {
|
||||
const mode = manager.getMode('code');
|
||||
|
||||
expect(mode).toBeDefined();
|
||||
expect(mode?.description).toBe('Coding mode');
|
||||
expect(mode?.skills).toContain('tdd');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAvailableModes', () => {
|
||||
it('should return available modes', () => {
|
||||
const modes = manager.getAvailableModes();
|
||||
|
||||
expect(modes).toContain('code');
|
||||
expect(modes).toContain('architect');
|
||||
});
|
||||
});
|
||||
|
||||
describe('setMode/getCurrentMode', () => {
|
||||
it('should set and get current mode', () => {
|
||||
manager.setMode('architect');
|
||||
|
||||
expect(manager.getCurrentMode()).toBe('architect');
|
||||
});
|
||||
|
||||
it('should throw for unconfigured mode', () => {
|
||||
expect(() => manager.setMode('debug')).toThrow('Mode not configured');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCurrentSkills', () => {
|
||||
it('should return skills for current mode', () => {
|
||||
manager.setMode('code');
|
||||
|
||||
const skills = manager.getCurrentSkills();
|
||||
|
||||
expect(skills).toContain('tdd');
|
||||
expect(skills).toContain('debugging');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSkillAvailable', () => {
|
||||
it('should check if skill is available', () => {
|
||||
manager.setMode('code');
|
||||
|
||||
expect(manager.isSkillAvailable('tdd')).toBe(true);
|
||||
expect(manager.isSkillAvailable('planning')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isFileAllowed', () => {
|
||||
it('should return true when no patterns defined', () => {
|
||||
expect(manager.isFileAllowed('any/file.ts')).toBe(true);
|
||||
});
|
||||
|
||||
it('should check file patterns when defined', () => {
|
||||
manager.addMode({
|
||||
mode: 'restricted',
|
||||
description: 'Restricted mode',
|
||||
skills: [],
|
||||
allowedFiles: ['src/**/*'],
|
||||
});
|
||||
manager.setMode('restricted');
|
||||
|
||||
expect(manager.isFileAllowed('src/app.ts')).toBe(true);
|
||||
expect(manager.isFileAllowed('lib/util.ts')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addModeListener', () => {
|
||||
it('should notify listeners on mode change', () => {
|
||||
let notified = false;
|
||||
let newModeValue = '';
|
||||
|
||||
manager.addModeListener((newMode) => {
|
||||
notified = true;
|
||||
newModeValue = newMode;
|
||||
});
|
||||
|
||||
manager.setMode('architect');
|
||||
|
||||
expect(notified).toBe(true);
|
||||
expect(newModeValue).toBe('architect');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateRooConfig', () => {
|
||||
it('should generate Roo-compatible config', () => {
|
||||
const config = manager.generateRooConfig();
|
||||
|
||||
expect(config.defaultMode).toBe('code');
|
||||
expect(config.modes).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateModeDocumentation', () => {
|
||||
it('should generate mode documentation', () => {
|
||||
const docs = manager.generateModeDocumentation();
|
||||
|
||||
expect(docs).toContain('# Available Modes');
|
||||
expect(docs).toContain('## code');
|
||||
expect(docs).toContain('## architect');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('createDefaultModeManager', () => {
|
||||
it('should create manager with default modes', () => {
|
||||
const manager = createDefaultModeManager({
|
||||
code: ['tdd'],
|
||||
debug: ['debugging'],
|
||||
});
|
||||
|
||||
const modes = manager.getAvailableModes();
|
||||
|
||||
expect(modes.length).toBe(7); // All default modes
|
||||
expect(manager.getMode('code')?.skills).toContain('tdd');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ALL_MODES', () => {
|
||||
it('should contain all mode types', () => {
|
||||
expect(ALL_MODES).toContain('code');
|
||||
expect(ALL_MODES).toContain('architect');
|
||||
expect(ALL_MODES).toContain('debug');
|
||||
expect(ALL_MODES).toContain('test');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,434 @@
|
||||
/**
|
||||
* Bootstrap Files System
|
||||
*
|
||||
* Implements bootstrap file generation for agents that support them.
|
||||
*/
|
||||
|
||||
import type {
|
||||
BootstrapFile,
|
||||
BootstrapFileType,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* Default bootstrap file names for each type
|
||||
*/
|
||||
const DEFAULT_FILE_NAMES: Record<BootstrapFileType, string> = {
|
||||
agents: 'AGENTS.md',
|
||||
soul: 'SOUL.md',
|
||||
tools: 'TOOLS.md',
|
||||
identity: 'IDENTITY.md',
|
||||
context: 'CONTEXT.md',
|
||||
brief: 'BRIEF.md',
|
||||
history: 'HISTORY.md',
|
||||
};
|
||||
|
||||
/**
|
||||
* BootstrapManager - Manage bootstrap files for agents
|
||||
*/
|
||||
export class BootstrapManager {
|
||||
private files: Map<BootstrapFileType, BootstrapFile> = new Map();
|
||||
|
||||
/**
|
||||
* Add a bootstrap file
|
||||
*/
|
||||
addFile(file: BootstrapFile): void {
|
||||
this.files.set(file.type, file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a bootstrap file by type
|
||||
*/
|
||||
getFile(type: BootstrapFileType): BootstrapFile | undefined {
|
||||
return this.files.get(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all bootstrap files
|
||||
*/
|
||||
getAllFiles(): BootstrapFile[] {
|
||||
return Array.from(this.files.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get files sorted by priority
|
||||
*/
|
||||
getFilesByPriority(): BootstrapFile[] {
|
||||
return this.getAllFiles().sort((a, b) => (b.priority || 0) - (a.priority || 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a bootstrap file
|
||||
*/
|
||||
removeFile(type: BootstrapFileType): boolean {
|
||||
return this.files.delete(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file type exists
|
||||
*/
|
||||
hasFile(type: BootstrapFileType): boolean {
|
||||
return this.files.has(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create AGENTS.md file
|
||||
*/
|
||||
createAgentsFile(agents: AgentDefinition[]): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Agents');
|
||||
lines.push('');
|
||||
lines.push('This file defines the available agents and their capabilities.');
|
||||
lines.push('');
|
||||
|
||||
for (const agent of agents) {
|
||||
lines.push(`## ${agent.name}`);
|
||||
lines.push('');
|
||||
if (agent.description) {
|
||||
lines.push(agent.description);
|
||||
lines.push('');
|
||||
}
|
||||
if (agent.capabilities && agent.capabilities.length > 0) {
|
||||
lines.push('### Capabilities');
|
||||
lines.push('');
|
||||
for (const cap of agent.capabilities) {
|
||||
lines.push(`- ${cap}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
if (agent.constraints && agent.constraints.length > 0) {
|
||||
lines.push('### Constraints');
|
||||
lines.push('');
|
||||
for (const constraint of agent.constraints) {
|
||||
lines.push(`- ${constraint}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'agents',
|
||||
name: 'AGENTS.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 100,
|
||||
required: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create SOUL.md file
|
||||
*/
|
||||
createSoulFile(soul: SoulDefinition): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Soul');
|
||||
lines.push('');
|
||||
lines.push('This file defines the personality and behavior of the agent.');
|
||||
lines.push('');
|
||||
|
||||
if (soul.personality) {
|
||||
lines.push('## Personality');
|
||||
lines.push('');
|
||||
lines.push(soul.personality);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (soul.values && soul.values.length > 0) {
|
||||
lines.push('## Values');
|
||||
lines.push('');
|
||||
for (const value of soul.values) {
|
||||
lines.push(`- ${value}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (soul.communication) {
|
||||
lines.push('## Communication Style');
|
||||
lines.push('');
|
||||
lines.push(soul.communication);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (soul.rules && soul.rules.length > 0) {
|
||||
lines.push('## Rules');
|
||||
lines.push('');
|
||||
for (const rule of soul.rules) {
|
||||
lines.push(`- ${rule}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'soul',
|
||||
name: 'SOUL.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 90,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create TOOLS.md file
|
||||
*/
|
||||
createToolsFile(tools: ToolDefinition[]): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Tools');
|
||||
lines.push('');
|
||||
lines.push('This file defines the available tools and their usage.');
|
||||
lines.push('');
|
||||
|
||||
for (const tool of tools) {
|
||||
lines.push(`## ${tool.name}`);
|
||||
lines.push('');
|
||||
if (tool.description) {
|
||||
lines.push(tool.description);
|
||||
lines.push('');
|
||||
}
|
||||
if (tool.usage) {
|
||||
lines.push('### Usage');
|
||||
lines.push('');
|
||||
lines.push('```');
|
||||
lines.push(tool.usage);
|
||||
lines.push('```');
|
||||
lines.push('');
|
||||
}
|
||||
if (tool.examples && tool.examples.length > 0) {
|
||||
lines.push('### Examples');
|
||||
lines.push('');
|
||||
for (const example of tool.examples) {
|
||||
lines.push(`- ${example}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'tools',
|
||||
name: 'TOOLS.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 80,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create IDENTITY.md file
|
||||
*/
|
||||
createIdentityFile(identity: IdentityDefinition): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Identity');
|
||||
lines.push('');
|
||||
|
||||
if (identity.name) {
|
||||
lines.push(`**Name:** ${identity.name}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (identity.role) {
|
||||
lines.push(`**Role:** ${identity.role}`);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (identity.description) {
|
||||
lines.push('## Description');
|
||||
lines.push('');
|
||||
lines.push(identity.description);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (identity.expertise && identity.expertise.length > 0) {
|
||||
lines.push('## Expertise');
|
||||
lines.push('');
|
||||
for (const exp of identity.expertise) {
|
||||
lines.push(`- ${exp}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'identity',
|
||||
name: 'IDENTITY.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 95,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create CONTEXT.md file
|
||||
*/
|
||||
createContextFile(context: ContextDefinition): void {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Context');
|
||||
lines.push('');
|
||||
|
||||
if (context.project) {
|
||||
lines.push('## Project');
|
||||
lines.push('');
|
||||
lines.push(context.project);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (context.techStack && context.techStack.length > 0) {
|
||||
lines.push('## Tech Stack');
|
||||
lines.push('');
|
||||
for (const tech of context.techStack) {
|
||||
lines.push(`- ${tech}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (context.conventions && context.conventions.length > 0) {
|
||||
lines.push('## Conventions');
|
||||
lines.push('');
|
||||
for (const conv of context.conventions) {
|
||||
lines.push(`- ${conv}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (context.currentTask) {
|
||||
lines.push('## Current Task');
|
||||
lines.push('');
|
||||
lines.push(context.currentTask);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
this.addFile({
|
||||
type: 'context',
|
||||
name: 'CONTEXT.md',
|
||||
content: lines.join('\n'),
|
||||
priority: 70,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate all files as a map
|
||||
*/
|
||||
generateFiles(): Map<string, string> {
|
||||
const files = new Map<string, string>();
|
||||
|
||||
for (const file of this.getFilesByPriority()) {
|
||||
files.set(file.name, file.content);
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate combined content for agents without file support
|
||||
*/
|
||||
generateCombinedContent(): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const file of this.getFilesByPriority()) {
|
||||
lines.push(`<!-- ${file.name} -->`);
|
||||
lines.push('');
|
||||
lines.push(file.content);
|
||||
lines.push('');
|
||||
lines.push('---');
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default file name for a type
|
||||
*/
|
||||
static getDefaultFileName(type: BootstrapFileType): string {
|
||||
return DEFAULT_FILE_NAMES[type];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent definition for AGENTS.md
|
||||
*/
|
||||
export interface AgentDefinition {
|
||||
name: string;
|
||||
description?: string;
|
||||
capabilities?: string[];
|
||||
constraints?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Soul definition for SOUL.md
|
||||
*/
|
||||
export interface SoulDefinition {
|
||||
personality?: string;
|
||||
values?: string[];
|
||||
communication?: string;
|
||||
rules?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool definition for TOOLS.md
|
||||
*/
|
||||
export interface ToolDefinition {
|
||||
name: string;
|
||||
description?: string;
|
||||
usage?: string;
|
||||
examples?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Identity definition for IDENTITY.md
|
||||
*/
|
||||
export interface IdentityDefinition {
|
||||
name?: string;
|
||||
role?: string;
|
||||
description?: string;
|
||||
expertise?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Context definition for CONTEXT.md
|
||||
*/
|
||||
export interface ContextDefinition {
|
||||
project?: string;
|
||||
techStack?: string[];
|
||||
conventions?: string[];
|
||||
currentTask?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a BootstrapManager instance
|
||||
*/
|
||||
export function createBootstrapManager(): BootstrapManager {
|
||||
return new BootstrapManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a complete bootstrap set from definitions
|
||||
*/
|
||||
export function createBootstrapSet(options: {
|
||||
agents?: AgentDefinition[];
|
||||
soul?: SoulDefinition;
|
||||
tools?: ToolDefinition[];
|
||||
identity?: IdentityDefinition;
|
||||
context?: ContextDefinition;
|
||||
}): BootstrapManager {
|
||||
const manager = new BootstrapManager();
|
||||
|
||||
if (options.agents) {
|
||||
manager.createAgentsFile(options.agents);
|
||||
}
|
||||
|
||||
if (options.soul) {
|
||||
manager.createSoulFile(options.soul);
|
||||
}
|
||||
|
||||
if (options.tools) {
|
||||
manager.createToolsFile(options.tools);
|
||||
}
|
||||
|
||||
if (options.identity) {
|
||||
manager.createIdentityFile(options.identity);
|
||||
}
|
||||
|
||||
if (options.context) {
|
||||
manager.createContextFile(options.context);
|
||||
}
|
||||
|
||||
return manager;
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* Glob Pattern System
|
||||
*
|
||||
* Implements file pattern matching for file-scoped skills.
|
||||
*/
|
||||
|
||||
import { minimatch } from 'minimatch';
|
||||
import type { GlobConfig } from './types.js';
|
||||
|
||||
/**
|
||||
* GlobMatcher - Match files against glob patterns
|
||||
*/
|
||||
export class GlobMatcher {
|
||||
private config: GlobConfig;
|
||||
private includePatterns: RegExp[];
|
||||
private excludePatterns: RegExp[];
|
||||
|
||||
constructor(config: GlobConfig) {
|
||||
this.config = config;
|
||||
this.includePatterns = config.include.map((p) => this.patternToRegex(p));
|
||||
this.excludePatterns = (config.exclude || []).map((p) => this.patternToRegex(p));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file matches the glob patterns
|
||||
*/
|
||||
matches(filePath: string): boolean {
|
||||
// Normalize path separators
|
||||
const normalizedPath = filePath.replace(/\\/g, '/');
|
||||
|
||||
// Check if hidden file and skip if not matching hidden
|
||||
if (!this.config.matchHidden && this.isHiddenFile(normalizedPath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check exclude patterns first
|
||||
for (const pattern of this.excludePatterns) {
|
||||
if (pattern.test(normalizedPath)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check include patterns
|
||||
for (const pattern of this.includePatterns) {
|
||||
if (pattern.test(normalizedPath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter a list of files
|
||||
*/
|
||||
filter(filePaths: string[]): string[] {
|
||||
return filePaths.filter((p) => this.matches(p));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all include patterns
|
||||
*/
|
||||
getIncludePatterns(): string[] {
|
||||
return [...this.config.include];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all exclude patterns
|
||||
*/
|
||||
getExcludePatterns(): string[] {
|
||||
return [...(this.config.exclude || [])];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an include pattern
|
||||
*/
|
||||
addInclude(pattern: string): void {
|
||||
this.config.include.push(pattern);
|
||||
this.includePatterns.push(this.patternToRegex(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an exclude pattern
|
||||
*/
|
||||
addExclude(pattern: string): void {
|
||||
if (!this.config.exclude) {
|
||||
this.config.exclude = [];
|
||||
}
|
||||
this.config.exclude.push(pattern);
|
||||
this.excludePatterns.push(this.patternToRegex(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert glob pattern to regex using minimatch
|
||||
*
|
||||
* Uses the battle-tested minimatch library to avoid ReDoS vulnerabilities
|
||||
* and ensure consistent glob matching behavior.
|
||||
*/
|
||||
private patternToRegex(pattern: string): RegExp {
|
||||
// Handle negation
|
||||
const isNegated = pattern.startsWith('!');
|
||||
const cleanPattern = isNegated ? pattern.slice(1) : pattern;
|
||||
|
||||
// Adjust pattern for directory matching
|
||||
let adjustedPattern = cleanPattern;
|
||||
if (this.config.matchDirectories && !cleanPattern.endsWith('/**')) {
|
||||
// Append /** to match directories and their contents
|
||||
adjustedPattern = cleanPattern.endsWith('/')
|
||||
? `${cleanPattern}**`
|
||||
: `${cleanPattern}/**`;
|
||||
}
|
||||
|
||||
// Use minimatch to create a safe regex
|
||||
// minimatch returns null if pattern is invalid, fallback to match-nothing regex
|
||||
const regex = minimatch.makeRe(adjustedPattern, { dot: this.config.matchHidden });
|
||||
|
||||
return regex || /(?!)/; // /(?!)/ is a regex that never matches anything
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file is hidden (starts with .)
|
||||
*/
|
||||
private isHiddenFile(path: string): boolean {
|
||||
const parts = path.split('/');
|
||||
return parts.some((part) => part.startsWith('.') && part !== '.' && part !== '..');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Cursor-compatible globs field
|
||||
*/
|
||||
generateCursorGlobs(): string[] {
|
||||
const globs: string[] = [...this.config.include];
|
||||
|
||||
// Add negated exclude patterns
|
||||
if (this.config.exclude) {
|
||||
for (const pattern of this.config.exclude) {
|
||||
globs.push(`!${pattern}`);
|
||||
}
|
||||
}
|
||||
|
||||
return globs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate MDC frontmatter
|
||||
*/
|
||||
generateMDCFrontmatter(): string {
|
||||
const globs = this.generateCursorGlobs();
|
||||
return `globs: ${JSON.stringify(globs)}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a GlobMatcher instance
|
||||
*/
|
||||
export function createGlobMatcher(config: GlobConfig): GlobMatcher {
|
||||
return new GlobMatcher(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a GlobMatcher from a single pattern
|
||||
*/
|
||||
export function matchPattern(pattern: string): GlobMatcher {
|
||||
return new GlobMatcher({ include: [pattern] });
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse glob patterns from Cursor MDC format
|
||||
*/
|
||||
export function parseGlobsFromMDC(content: string): GlobConfig | null {
|
||||
const match = content.match(/globs:\s*(\[.*?\])/s);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const patterns = JSON.parse(match[1]) as string[];
|
||||
const include: string[] = [];
|
||||
const exclude: string[] = [];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
if (pattern.startsWith('!')) {
|
||||
exclude.push(pattern.slice(1));
|
||||
} else {
|
||||
include.push(pattern);
|
||||
}
|
||||
}
|
||||
|
||||
return { include, exclude };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Common glob patterns for different file types
|
||||
*/
|
||||
export const COMMON_PATTERNS = {
|
||||
/** All TypeScript files */
|
||||
typescript: ['**/*.ts', '**/*.tsx'],
|
||||
/** All JavaScript files */
|
||||
javascript: ['**/*.js', '**/*.jsx', '**/*.mjs', '**/*.cjs'],
|
||||
/** All test files */
|
||||
tests: ['**/*.test.*', '**/*.spec.*', '**/__tests__/**'],
|
||||
/** All config files */
|
||||
configs: ['*.config.*', '*rc', '*rc.*', '*.json', '*.yaml', '*.yml'],
|
||||
/** All source files */
|
||||
source: ['src/**/*'],
|
||||
/** All documentation */
|
||||
docs: ['**/*.md', 'docs/**/*', 'README*'],
|
||||
/** Node modules (usually excluded) */
|
||||
nodeModules: ['**/node_modules/**'],
|
||||
/** Build outputs (usually excluded) */
|
||||
buildOutputs: ['**/dist/**', '**/build/**', '**/.next/**'],
|
||||
/** All files */
|
||||
all: ['**/*'],
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Create glob config from common pattern names
|
||||
*/
|
||||
export function fromCommonPatterns(
|
||||
includeNames: (keyof typeof COMMON_PATTERNS)[],
|
||||
excludeNames?: (keyof typeof COMMON_PATTERNS)[]
|
||||
): GlobConfig {
|
||||
const include: string[] = [];
|
||||
const exclude: string[] = [];
|
||||
|
||||
for (const name of includeNames) {
|
||||
include.push(...COMMON_PATTERNS[name]);
|
||||
}
|
||||
|
||||
if (excludeNames) {
|
||||
for (const name of excludeNames) {
|
||||
exclude.push(...COMMON_PATTERNS[name]);
|
||||
}
|
||||
}
|
||||
|
||||
return { include, exclude };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Agent Features Module
|
||||
*
|
||||
* Enhanced agent-specific features including:
|
||||
* - Permissions system (OpenCode-style)
|
||||
* - Glob pattern matching (Cursor-style)
|
||||
* - Bootstrap files (Amp-style)
|
||||
* - Multi-mode support (Roo/Kilo-style)
|
||||
*/
|
||||
|
||||
export * from './types.js';
|
||||
export * from './permissions.js';
|
||||
export * from './globs.js';
|
||||
export * from './bootstrap.js';
|
||||
export * from './modes.js';
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* Multi-Mode System
|
||||
*
|
||||
* Implements multi-mode support for agents that support different operating modes.
|
||||
*/
|
||||
|
||||
import type { AgentMode, ModeConfig } from './types.js';
|
||||
import { GlobMatcher } from './globs.js';
|
||||
|
||||
/**
|
||||
* Default mode configurations
|
||||
*/
|
||||
const DEFAULT_MODES: Record<AgentMode, Omit<ModeConfig, 'skills'>> = {
|
||||
code: {
|
||||
mode: 'code',
|
||||
description: 'Code editing and implementation mode',
|
||||
promptPrefix: 'You are in code mode. Focus on writing and editing code.',
|
||||
},
|
||||
architect: {
|
||||
mode: 'architect',
|
||||
description: 'Architecture and planning mode',
|
||||
promptPrefix: 'You are in architect mode. Focus on system design and planning.',
|
||||
},
|
||||
ask: {
|
||||
mode: 'ask',
|
||||
description: 'Question and answer mode',
|
||||
promptPrefix: 'You are in ask mode. Focus on answering questions clearly.',
|
||||
},
|
||||
debug: {
|
||||
mode: 'debug',
|
||||
description: 'Debugging and troubleshooting mode',
|
||||
promptPrefix: 'You are in debug mode. Focus on finding and fixing issues.',
|
||||
},
|
||||
review: {
|
||||
mode: 'review',
|
||||
description: 'Code review mode',
|
||||
promptPrefix: 'You are in review mode. Focus on reviewing code quality.',
|
||||
},
|
||||
test: {
|
||||
mode: 'test',
|
||||
description: 'Testing mode',
|
||||
promptPrefix: 'You are in test mode. Focus on writing and running tests.',
|
||||
},
|
||||
docs: {
|
||||
mode: 'docs',
|
||||
description: 'Documentation mode',
|
||||
promptPrefix: 'You are in docs mode. Focus on writing documentation.',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* ModeManager - Manage agent operating modes
|
||||
*/
|
||||
export class ModeManager {
|
||||
private modes: Map<AgentMode, ModeConfig> = new Map();
|
||||
private currentMode: AgentMode = 'code';
|
||||
private modeListeners: Set<ModeChangeListener> = new Set();
|
||||
|
||||
constructor(modes?: ModeConfig[]) {
|
||||
if (modes) {
|
||||
for (const mode of modes) {
|
||||
this.addMode(mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a mode configuration
|
||||
*/
|
||||
addMode(config: ModeConfig): void {
|
||||
this.modes.set(config.mode, config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a mode configuration
|
||||
*/
|
||||
getMode(mode: AgentMode): ModeConfig | undefined {
|
||||
return this.modes.get(mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all mode configurations
|
||||
*/
|
||||
getAllModes(): ModeConfig[] {
|
||||
return Array.from(this.modes.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available mode names
|
||||
*/
|
||||
getAvailableModes(): AgentMode[] {
|
||||
return Array.from(this.modes.keys());
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current mode
|
||||
*/
|
||||
setMode(mode: AgentMode): void {
|
||||
const config = this.modes.get(mode);
|
||||
if (!config) {
|
||||
throw new Error(`Mode not configured: ${mode}`);
|
||||
}
|
||||
|
||||
const previousMode = this.currentMode;
|
||||
this.currentMode = mode;
|
||||
|
||||
// Notify listeners
|
||||
for (const listener of this.modeListeners) {
|
||||
listener(mode, previousMode, config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current mode
|
||||
*/
|
||||
getCurrentMode(): AgentMode {
|
||||
return this.currentMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current mode configuration
|
||||
*/
|
||||
getCurrentModeConfig(): ModeConfig | undefined {
|
||||
return this.modes.get(this.currentMode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get skills for current mode
|
||||
*/
|
||||
getCurrentSkills(): string[] {
|
||||
const config = this.getCurrentModeConfig();
|
||||
return config?.skills || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tools for current mode
|
||||
*/
|
||||
getCurrentTools(): string[] {
|
||||
const config = this.getCurrentModeConfig();
|
||||
return config?.tools || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a skill is available in current mode
|
||||
*/
|
||||
isSkillAvailable(skillName: string): boolean {
|
||||
const skills = this.getCurrentSkills();
|
||||
return skills.length === 0 || skills.includes(skillName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file is allowed in current mode
|
||||
*/
|
||||
isFileAllowed(filePath: string): boolean {
|
||||
const config = this.getCurrentModeConfig();
|
||||
if (!config?.allowedFiles || config.allowedFiles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const matcher = new GlobMatcher({ include: config.allowedFiles });
|
||||
return matcher.matches(filePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add mode change listener
|
||||
*/
|
||||
addModeListener(listener: ModeChangeListener): void {
|
||||
this.modeListeners.add(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove mode change listener
|
||||
*/
|
||||
removeModeListener(listener: ModeChangeListener): void {
|
||||
this.modeListeners.delete(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a mode from default configuration
|
||||
*/
|
||||
addDefaultMode(mode: AgentMode, skills: string[]): void {
|
||||
const defaultConfig = DEFAULT_MODES[mode];
|
||||
this.addMode({
|
||||
...defaultConfig,
|
||||
skills,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate mode-specific prompt prefix
|
||||
*/
|
||||
getPromptPrefix(): string {
|
||||
const config = this.getCurrentModeConfig();
|
||||
return config?.promptPrefix || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Roo-compatible mode configuration
|
||||
*/
|
||||
generateRooConfig(): Record<string, unknown> {
|
||||
const modes: Record<string, unknown> = {};
|
||||
|
||||
for (const config of this.modes.values()) {
|
||||
modes[config.mode] = {
|
||||
description: config.description,
|
||||
skills: config.skills,
|
||||
tools: config.tools,
|
||||
promptPrefix: config.promptPrefix,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
defaultMode: this.currentMode,
|
||||
modes,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate mode documentation
|
||||
*/
|
||||
generateModeDocumentation(): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Available Modes');
|
||||
lines.push('');
|
||||
|
||||
for (const config of this.modes.values()) {
|
||||
lines.push(`## ${config.mode}`);
|
||||
lines.push('');
|
||||
lines.push(config.description);
|
||||
lines.push('');
|
||||
|
||||
if (config.skills.length > 0) {
|
||||
lines.push('### Skills');
|
||||
lines.push('');
|
||||
for (const skill of config.skills) {
|
||||
lines.push(`- ${skill}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (config.tools && config.tools.length > 0) {
|
||||
lines.push('### Tools');
|
||||
lines.push('');
|
||||
for (const tool of config.tools) {
|
||||
lines.push(`- ${tool}`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode change listener type
|
||||
*/
|
||||
export type ModeChangeListener = (
|
||||
newMode: AgentMode,
|
||||
previousMode: AgentMode,
|
||||
config: ModeConfig
|
||||
) => void;
|
||||
|
||||
/**
|
||||
* Create a ModeManager instance
|
||||
*/
|
||||
export function createModeManager(modes?: ModeConfig[]): ModeManager {
|
||||
return new ModeManager(modes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a ModeManager with all default modes
|
||||
*/
|
||||
export function createDefaultModeManager(
|
||||
skillsPerMode: Partial<Record<AgentMode, string[]>>
|
||||
): ModeManager {
|
||||
const manager = new ModeManager();
|
||||
|
||||
for (const [mode, config] of Object.entries(DEFAULT_MODES)) {
|
||||
const skills = skillsPerMode[mode as AgentMode] || [];
|
||||
manager.addMode({
|
||||
...config,
|
||||
skills,
|
||||
});
|
||||
}
|
||||
|
||||
return manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default configuration for a mode
|
||||
*/
|
||||
export function getDefaultModeConfig(mode: AgentMode): Omit<ModeConfig, 'skills'> {
|
||||
return DEFAULT_MODES[mode];
|
||||
}
|
||||
|
||||
/**
|
||||
* All available agent modes
|
||||
*/
|
||||
export const ALL_MODES: AgentMode[] = ['code', 'architect', 'ask', 'debug', 'review', 'test', 'docs'];
|
||||
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* Permissions System
|
||||
*
|
||||
* Implements permission patterns for agent skill access control.
|
||||
*/
|
||||
|
||||
import { minimatch } from 'minimatch';
|
||||
import type {
|
||||
PermissionConfig,
|
||||
PermissionPattern,
|
||||
PermissionLevel,
|
||||
} from './types.js';
|
||||
|
||||
/**
|
||||
* PermissionManager - Manage skill permissions
|
||||
*/
|
||||
export class PermissionManager {
|
||||
private config: PermissionConfig;
|
||||
|
||||
constructor(config?: PermissionConfig) {
|
||||
this.config = config || { default: 'ask' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Set permission configuration
|
||||
*/
|
||||
setConfig(config: PermissionConfig): void {
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get permission configuration
|
||||
*/
|
||||
getConfig(): PermissionConfig {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check file access permission
|
||||
*/
|
||||
checkFileAccess(path: string): PermissionLevel {
|
||||
return this.checkPattern(path, this.config.files);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check command execution permission
|
||||
*/
|
||||
checkCommandAccess(command: string): PermissionLevel {
|
||||
return this.checkPattern(command, this.config.commands);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check network access permission
|
||||
*/
|
||||
checkNetworkAccess(url: string): PermissionLevel {
|
||||
return this.checkPattern(url, this.config.network);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check environment variable access
|
||||
*/
|
||||
checkEnvAccess(varName: string): PermissionLevel {
|
||||
return this.checkPattern(varName, this.config.env);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add file permission pattern
|
||||
*/
|
||||
addFilePattern(pattern: PermissionPattern): void {
|
||||
if (!this.config.files) {
|
||||
this.config.files = [];
|
||||
}
|
||||
this.config.files.push(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add command permission pattern
|
||||
*/
|
||||
addCommandPattern(pattern: PermissionPattern): void {
|
||||
if (!this.config.commands) {
|
||||
this.config.commands = [];
|
||||
}
|
||||
this.config.commands.push(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check pattern against permission list
|
||||
*/
|
||||
private checkPattern(
|
||||
value: string,
|
||||
patterns?: PermissionPattern[]
|
||||
): PermissionLevel {
|
||||
if (!patterns || patterns.length === 0) {
|
||||
return this.config.default || 'ask';
|
||||
}
|
||||
|
||||
// Check patterns in order (first match wins)
|
||||
for (const pattern of patterns) {
|
||||
if (this.matchPattern(value, pattern.pattern)) {
|
||||
return pattern.level;
|
||||
}
|
||||
}
|
||||
|
||||
return this.config.default || 'ask';
|
||||
}
|
||||
|
||||
/**
|
||||
* Match value against pattern (glob-style)
|
||||
*
|
||||
* Uses minimatch for safe glob matching, avoiding ReDoS vulnerabilities.
|
||||
*/
|
||||
private matchPattern(value: string, pattern: string): boolean {
|
||||
// Use minimatch for safe, battle-tested glob matching
|
||||
// nocase option ensures case-insensitive matching
|
||||
return minimatch(value, pattern, { nocase: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate OpenCode-compatible permission config
|
||||
*/
|
||||
generateOpenCodeConfig(): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push('# Permission Configuration');
|
||||
lines.push('');
|
||||
|
||||
if (this.config.files && this.config.files.length > 0) {
|
||||
lines.push('## File Access');
|
||||
lines.push('');
|
||||
for (const pattern of this.config.files) {
|
||||
lines.push(`- ${pattern.level}: \`${pattern.pattern}\``);
|
||||
if (pattern.reason) {
|
||||
lines.push(` - Reason: ${pattern.reason}`);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (this.config.commands && this.config.commands.length > 0) {
|
||||
lines.push('## Command Execution');
|
||||
lines.push('');
|
||||
for (const pattern of this.config.commands) {
|
||||
lines.push(`- ${pattern.level}: \`${pattern.pattern}\``);
|
||||
if (pattern.reason) {
|
||||
lines.push(` - Reason: ${pattern.reason}`);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
if (this.config.network && this.config.network.length > 0) {
|
||||
lines.push('## Network Access');
|
||||
lines.push('');
|
||||
for (const pattern of this.config.network) {
|
||||
lines.push(`- ${pattern.level}: \`${pattern.pattern}\``);
|
||||
if (pattern.reason) {
|
||||
lines.push(` - Reason: ${pattern.reason}`);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
lines.push(`Default: ${this.config.default || 'ask'}`);
|
||||
lines.push('');
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate SKILL.md metadata for permissions
|
||||
*/
|
||||
generateSkillMetadata(): Record<string, unknown> {
|
||||
const metadata: Record<string, unknown> = {};
|
||||
|
||||
if (this.config.files) {
|
||||
metadata.filePermissions = this.config.files.map((p) => ({
|
||||
pattern: p.pattern,
|
||||
level: p.level,
|
||||
}));
|
||||
}
|
||||
|
||||
if (this.config.commands) {
|
||||
metadata.commandPermissions = this.config.commands.map((p) => ({
|
||||
pattern: p.pattern,
|
||||
level: p.level,
|
||||
}));
|
||||
}
|
||||
|
||||
if (this.config.network) {
|
||||
metadata.networkPermissions = this.config.network.map((p) => ({
|
||||
pattern: p.pattern,
|
||||
level: p.level,
|
||||
}));
|
||||
}
|
||||
|
||||
if (this.config.default) {
|
||||
metadata.defaultPermission = this.config.default;
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse permissions from SKILL.md metadata
|
||||
*/
|
||||
static fromMetadata(metadata: Record<string, unknown>): PermissionConfig {
|
||||
const config: PermissionConfig = {};
|
||||
|
||||
if (metadata.filePermissions && Array.isArray(metadata.filePermissions)) {
|
||||
config.files = metadata.filePermissions as PermissionPattern[];
|
||||
}
|
||||
|
||||
if (metadata.commandPermissions && Array.isArray(metadata.commandPermissions)) {
|
||||
config.commands = metadata.commandPermissions as PermissionPattern[];
|
||||
}
|
||||
|
||||
if (metadata.networkPermissions && Array.isArray(metadata.networkPermissions)) {
|
||||
config.network = metadata.networkPermissions as PermissionPattern[];
|
||||
}
|
||||
|
||||
if (metadata.defaultPermission) {
|
||||
config.default = metadata.defaultPermission as PermissionLevel;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge two permission configs
|
||||
*/
|
||||
static merge(base: PermissionConfig, override: PermissionConfig): PermissionConfig {
|
||||
return {
|
||||
files: [...(base.files || []), ...(override.files || [])],
|
||||
commands: [...(base.commands || []), ...(override.commands || [])],
|
||||
network: [...(base.network || []), ...(override.network || [])],
|
||||
env: [...(base.env || []), ...(override.env || [])],
|
||||
default: override.default || base.default,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a PermissionManager instance
|
||||
*/
|
||||
export function createPermissionManager(config?: PermissionConfig): PermissionManager {
|
||||
return new PermissionManager(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick permission check helpers
|
||||
*/
|
||||
export function isAllowed(level: PermissionLevel): boolean {
|
||||
return level === 'allow';
|
||||
}
|
||||
|
||||
export function isDenied(level: PermissionLevel): boolean {
|
||||
return level === 'deny';
|
||||
}
|
||||
|
||||
export function needsConfirmation(level: PermissionLevel): boolean {
|
||||
return level === 'ask';
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* Agent Features Types
|
||||
*
|
||||
* Type definitions for enhanced agent-specific features.
|
||||
*/
|
||||
|
||||
import type { AgentType } from '@skillkit/core';
|
||||
|
||||
/**
|
||||
* Permission level for agent actions
|
||||
*/
|
||||
export type PermissionLevel = 'allow' | 'deny' | 'ask';
|
||||
|
||||
/**
|
||||
* Permission pattern for file/resource access
|
||||
*/
|
||||
export interface PermissionPattern {
|
||||
/** Pattern to match (glob or regex) */
|
||||
pattern: string;
|
||||
/** Permission level */
|
||||
level: PermissionLevel;
|
||||
/** Description of why this permission is needed */
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission configuration for skills
|
||||
*/
|
||||
export interface PermissionConfig {
|
||||
/** File access permissions */
|
||||
files?: PermissionPattern[];
|
||||
/** Command execution permissions */
|
||||
commands?: PermissionPattern[];
|
||||
/** Network access permissions */
|
||||
network?: PermissionPattern[];
|
||||
/** Environment variable access */
|
||||
env?: PermissionPattern[];
|
||||
/** Default permission level */
|
||||
default?: PermissionLevel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Glob pattern configuration for file-scoped skills
|
||||
*/
|
||||
export interface GlobConfig {
|
||||
/** Patterns to include */
|
||||
include: string[];
|
||||
/** Patterns to exclude */
|
||||
exclude?: string[];
|
||||
/** Whether to match directories */
|
||||
matchDirectories?: boolean;
|
||||
/** Whether to match hidden files */
|
||||
matchHidden?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap file types
|
||||
*/
|
||||
export type BootstrapFileType =
|
||||
| 'agents' // AGENTS.md - Agent definitions
|
||||
| 'soul' // SOUL.md - Personality and behavior
|
||||
| 'tools' // TOOLS.md - Available tools
|
||||
| 'identity' // IDENTITY.md - Agent identity
|
||||
| 'context' // CONTEXT.md - Context information
|
||||
| 'brief' // BRIEF.md - Project brief
|
||||
| 'history'; // HISTORY.md - Conversation history
|
||||
|
||||
/**
|
||||
* Bootstrap file configuration
|
||||
*/
|
||||
export interface BootstrapFile {
|
||||
/** File type */
|
||||
type: BootstrapFileType;
|
||||
/** File name */
|
||||
name: string;
|
||||
/** File content */
|
||||
content: string;
|
||||
/** Priority (higher = loaded first) */
|
||||
priority?: number;
|
||||
/** Whether file is required */
|
||||
required?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent mode types
|
||||
*/
|
||||
export type AgentMode =
|
||||
| 'code' // Code editing mode
|
||||
| 'architect' // Architecture/planning mode
|
||||
| 'ask' // Question/answer mode
|
||||
| 'debug' // Debugging mode
|
||||
| 'review' // Code review mode
|
||||
| 'test' // Testing mode
|
||||
| 'docs'; // Documentation mode
|
||||
|
||||
/**
|
||||
* Mode configuration
|
||||
*/
|
||||
export interface ModeConfig {
|
||||
/** Mode name */
|
||||
mode: AgentMode;
|
||||
/** Mode description */
|
||||
description: string;
|
||||
/** Skills available in this mode */
|
||||
skills: string[];
|
||||
/** Tools available in this mode */
|
||||
tools?: string[];
|
||||
/** Default prompt prefix for this mode */
|
||||
promptPrefix?: string;
|
||||
/** Allowed file patterns in this mode */
|
||||
allowedFiles?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tool whitelist configuration
|
||||
*/
|
||||
export interface ToolWhitelistConfig {
|
||||
/** Allowed tools */
|
||||
allowed: string[];
|
||||
/** Denied tools */
|
||||
denied?: string[];
|
||||
/** Mode for handling unlisted tools */
|
||||
unlisted?: 'allow' | 'deny' | 'ask';
|
||||
}
|
||||
|
||||
/**
|
||||
* Skill package configuration (for .skill bundles)
|
||||
*/
|
||||
export interface SkillPackageConfig {
|
||||
/** Package name */
|
||||
name: string;
|
||||
/** Package version */
|
||||
version: string;
|
||||
/** Package description */
|
||||
description?: string;
|
||||
/** Entry point skill */
|
||||
entryPoint: string;
|
||||
/** Included skill files */
|
||||
files: string[];
|
||||
/** Dependencies */
|
||||
dependencies?: string[];
|
||||
/** Metadata */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent feature capabilities
|
||||
*/
|
||||
export interface AgentCapabilities {
|
||||
/** Supports permission system */
|
||||
permissions: boolean;
|
||||
/** Supports glob patterns */
|
||||
globs: boolean;
|
||||
/** Supports bootstrap files */
|
||||
bootstrapFiles: boolean;
|
||||
/** Supports multi-mode */
|
||||
multiMode: boolean;
|
||||
/** Supports tool whitelisting */
|
||||
toolWhitelist: boolean;
|
||||
/** Supports .skill packages */
|
||||
skillPackages: boolean;
|
||||
/** Supports hooks */
|
||||
hooks: boolean;
|
||||
/** Supports subagents */
|
||||
subagents: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent feature set
|
||||
*/
|
||||
export interface AgentFeatures {
|
||||
/** Agent type */
|
||||
agent: AgentType;
|
||||
/** Agent capabilities */
|
||||
capabilities: AgentCapabilities;
|
||||
/** Permission configuration */
|
||||
permissions?: PermissionConfig;
|
||||
/** Glob configuration */
|
||||
globs?: GlobConfig;
|
||||
/** Bootstrap files */
|
||||
bootstrapFiles?: BootstrapFile[];
|
||||
/** Mode configurations */
|
||||
modes?: ModeConfig[];
|
||||
/** Tool whitelist */
|
||||
toolWhitelist?: ToolWhitelistConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Feature generation options
|
||||
*/
|
||||
export interface FeatureGenerationOptions {
|
||||
/** Target agent */
|
||||
agent: AgentType;
|
||||
/** Output directory */
|
||||
outputDir?: string;
|
||||
/** Include optional files */
|
||||
includeOptional?: boolean;
|
||||
/** Dry run (don't write files) */
|
||||
dryRun?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Feature validation result
|
||||
*/
|
||||
export interface FeatureValidationResult {
|
||||
/** Whether features are valid */
|
||||
valid: boolean;
|
||||
/** Validation errors */
|
||||
errors: string[];
|
||||
/** Validation warnings */
|
||||
warnings: string[];
|
||||
/** Agent capabilities used */
|
||||
usedCapabilities: (keyof AgentCapabilities)[];
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
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';
|
||||
|
||||
// Agent features
|
||||
export * from './features/index.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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"composite": false
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist", "**/*.test.ts"]
|
||||
}
|
||||
@@ -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',
|
||||
});
|
||||
@@ -0,0 +1,254 @@
|
||||
# @skillkit/cli
|
||||
|
||||
[](https://www.npmjs.com/package/@skillkit/cli)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
**Command-line interface for SkillKit** - install, manage, translate, and sync skills across 17 AI coding agents.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install -g @skillkit/cli
|
||||
# or
|
||||
npm install -g skillkit # includes CLI
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Get skill recommendations for your project
|
||||
skillkit recommend
|
||||
|
||||
# Install skills from GitHub
|
||||
skillkit install anthropics/skills
|
||||
|
||||
# Translate skills between agents
|
||||
skillkit translate my-skill --to cursor
|
||||
|
||||
# Launch interactive TUI
|
||||
skillkit ui
|
||||
```
|
||||
|
||||
## All Commands
|
||||
|
||||
### Skill Management
|
||||
|
||||
```bash
|
||||
skillkit install <source> # Install from GitHub/GitLab/Bitbucket/local
|
||||
skillkit remove <skills> # Remove installed skills
|
||||
skillkit update [skills] # Update skills from source
|
||||
skillkit list # List installed skills
|
||||
skillkit enable <skills> # Enable specific skills
|
||||
skillkit disable <skills> # Disable specific skills
|
||||
skillkit sync # Sync to agent config
|
||||
skillkit read <skills> # Read skill content
|
||||
```
|
||||
|
||||
### Discovery & Recommendations
|
||||
|
||||
```bash
|
||||
skillkit recommend # Project-based recommendations
|
||||
skillkit recommend --search "auth" # Task-based search
|
||||
skillkit recommend --category security # Filter by category
|
||||
skillkit recommend --min-score 80 # Quality threshold
|
||||
|
||||
skillkit marketplace # Browse skills
|
||||
skillkit marketplace search "react" # Search marketplace
|
||||
skillkit marketplace --tags typescript # Filter by tags
|
||||
skillkit marketplace refresh # Refresh index
|
||||
```
|
||||
|
||||
### Translation
|
||||
|
||||
```bash
|
||||
skillkit translate <skill> --to <agent> # Translate single skill
|
||||
skillkit translate --all --to cursor # Translate all skills
|
||||
skillkit translate skill --dry-run # Preview without writing
|
||||
```
|
||||
|
||||
### Context Management
|
||||
|
||||
```bash
|
||||
skillkit context init # Analyze project, create context
|
||||
skillkit context show # Display current context
|
||||
skillkit context sync --all # Sync to all detected agents
|
||||
skillkit context export # Export context file
|
||||
```
|
||||
|
||||
### Session Memory
|
||||
|
||||
```bash
|
||||
skillkit memory status # View memory status
|
||||
skillkit memory search "auth" # Search learnings
|
||||
skillkit memory list # List all learnings
|
||||
skillkit memory compress # Compress observations
|
||||
skillkit memory export <id> # Export as skill
|
||||
skillkit memory add # Add manual learning
|
||||
skillkit memory --global # Use global scope
|
||||
```
|
||||
|
||||
### Testing & Workflows
|
||||
|
||||
```bash
|
||||
skillkit test # Run all skill tests
|
||||
skillkit test ./my-skill # Test specific skill
|
||||
skillkit test --tags unit # Run tagged tests
|
||||
|
||||
skillkit workflow list # List workflows
|
||||
skillkit workflow run <name> # Execute workflow
|
||||
skillkit workflow create # Create new workflow
|
||||
|
||||
skillkit cicd github-action # Generate GitHub Actions
|
||||
skillkit cicd gitlab-ci # Generate GitLab CI
|
||||
skillkit cicd pre-commit # Generate pre-commit hook
|
||||
skillkit cicd init # Initialize CI/CD templates
|
||||
```
|
||||
|
||||
### Team Collaboration
|
||||
|
||||
```bash
|
||||
skillkit team init --name "Team" # Initialize team
|
||||
skillkit team share <bundle> # Share skill bundle
|
||||
skillkit team import <path> # Import bundle
|
||||
skillkit team list # List team bundles
|
||||
skillkit team sync # Sync with remote
|
||||
skillkit team remove <bundle> # Remove bundle
|
||||
skillkit team bundle-create # Create new bundle
|
||||
skillkit team bundle-export <id> # Export bundle
|
||||
skillkit team bundle-list # List all bundles
|
||||
```
|
||||
|
||||
### Plugin System
|
||||
|
||||
```bash
|
||||
skillkit plugin list # List installed plugins
|
||||
skillkit plugin install <name> # Install plugin
|
||||
skillkit plugin uninstall <name> # Uninstall plugin
|
||||
skillkit plugin enable <name> # Enable plugin
|
||||
skillkit plugin disable <name> # Disable plugin
|
||||
skillkit plugin info <name> # Plugin details
|
||||
```
|
||||
|
||||
### Methodologies & Plans
|
||||
|
||||
```bash
|
||||
skillkit methodology list # List methodologies
|
||||
skillkit methodology load <name> # Load methodology
|
||||
skillkit methodology apply <name> # Apply to project
|
||||
|
||||
skillkit plan parse <file> # Parse plan file
|
||||
skillkit plan validate <file> # Validate plan
|
||||
skillkit plan execute <file> # Execute plan
|
||||
skillkit plan status # Plan execution status
|
||||
```
|
||||
|
||||
### Hooks & Automation
|
||||
|
||||
```bash
|
||||
skillkit hook list # List registered hooks
|
||||
skillkit hook register <event> # Register new hook
|
||||
skillkit hook trigger <event> # Trigger hook manually
|
||||
skillkit hook enable <id> # Enable hook
|
||||
skillkit hook disable <id> # Disable hook
|
||||
```
|
||||
|
||||
### Agent Commands
|
||||
|
||||
```bash
|
||||
skillkit command generate <agent> # Generate agent-native commands
|
||||
skillkit command list <agent> # List available commands
|
||||
```
|
||||
|
||||
### Utilities
|
||||
|
||||
```bash
|
||||
skillkit init # Initialize in project
|
||||
skillkit init --agent cursor # Initialize for specific agent
|
||||
skillkit validate ./skill # Validate skill format
|
||||
skillkit create my-skill # Create new skill
|
||||
skillkit settings # View all settings
|
||||
skillkit settings --set key=value # Update setting
|
||||
```
|
||||
|
||||
## Install Options
|
||||
|
||||
```bash
|
||||
skillkit install owner/repo # GitHub repository
|
||||
skillkit install gitlab:owner/repo # GitLab repository
|
||||
skillkit install ./local/path # Local directory
|
||||
|
||||
# Options
|
||||
--list # List available skills without installing
|
||||
--skills=pdf,xlsx # Install specific skills
|
||||
--all # Install all discovered skills
|
||||
--yes # Skip confirmation prompts
|
||||
--global # Install globally
|
||||
--force # Overwrite existing
|
||||
--agent=cursor,windsurf # Install to specific agents
|
||||
```
|
||||
|
||||
## Programmatic Usage
|
||||
|
||||
```typescript
|
||||
import {
|
||||
installCommand,
|
||||
listCommand,
|
||||
syncCommand,
|
||||
translateCommand,
|
||||
recommendCommand,
|
||||
} from '@skillkit/cli';
|
||||
|
||||
// Install skills programmatically
|
||||
await installCommand('anthropics/skills', {
|
||||
agent: ['claude-code', 'cursor'],
|
||||
yes: true,
|
||||
});
|
||||
|
||||
// List installed skills
|
||||
const skills = await listCommand({ json: true });
|
||||
|
||||
// Sync to agent
|
||||
await syncCommand({ all: true });
|
||||
|
||||
// Translate skill
|
||||
await translateCommand('my-skill', {
|
||||
to: 'cursor',
|
||||
dryRun: false,
|
||||
});
|
||||
|
||||
// Get recommendations
|
||||
const recs = await recommendCommand({
|
||||
path: './my-project',
|
||||
minScore: 70,
|
||||
});
|
||||
```
|
||||
|
||||
## CI/CD Usage
|
||||
|
||||
```yaml
|
||||
# GitHub Actions example
|
||||
- name: Setup skills
|
||||
run: |
|
||||
npx skillkit install owner/skills --skills=lint,test --yes
|
||||
npx skillkit sync --yes
|
||||
```
|
||||
|
||||
## Supported Agents
|
||||
|
||||
| Agent | Format |
|
||||
|-------|--------|
|
||||
| Claude Code | SKILL.md |
|
||||
| Cursor | MDC (.mdc) |
|
||||
| Codex | SKILL.md |
|
||||
| Gemini CLI | SKILL.md |
|
||||
| Windsurf | Markdown |
|
||||
| GitHub Copilot | Markdown |
|
||||
| + 11 more | SKILL.md |
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"name": "@skillkit/cli",
|
||||
"version": "1.6.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": "^1.6.0",
|
||||
"@skillkit/agents": "^1.6.0",
|
||||
"@skillkit/tui": "^1.6.0",
|
||||
"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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,390 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import { promises as fs } from 'fs';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
type SearchableSkill,
|
||||
type SkillExample,
|
||||
AIManager,
|
||||
loadIndex as loadIndexFromCache,
|
||||
} from '@skillkit/core';
|
||||
|
||||
export class AICommand extends Command {
|
||||
static override paths = [['ai']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'AI-powered skill search and generation',
|
||||
details: `
|
||||
The ai command provides AI-powered features for skills:
|
||||
|
||||
- Natural language search: Find skills using conversational queries
|
||||
- Skill generation: Automatically generate skills from examples
|
||||
- Similar skills: Find skills similar to a given skill
|
||||
|
||||
Note: Without an API key, the command uses a basic mock AI provider.
|
||||
Set ANTHROPIC_API_KEY or OPENAI_API_KEY to use real AI features.
|
||||
`,
|
||||
examples: [
|
||||
['Search skills naturally', '$0 ai search "help me write better tests"'],
|
||||
['Generate skill from description', '$0 ai generate --description "skill for code review"'],
|
||||
['Generate from code example', '$0 ai generate --from-code example.ts --description "..."'],
|
||||
['Find similar skills', '$0 ai similar my-skill-name'],
|
||||
],
|
||||
});
|
||||
|
||||
// Subcommand
|
||||
subcommand = Option.String({ required: true });
|
||||
|
||||
// Search options
|
||||
query = Option.String('--query,-q', {
|
||||
description: 'Search query for natural language search',
|
||||
});
|
||||
|
||||
// Generation options
|
||||
description = Option.String('--description,-d', {
|
||||
description: 'Description of the skill to generate',
|
||||
});
|
||||
|
||||
fromCode = Option.String('--from-code', {
|
||||
description: 'Generate skill from code example file',
|
||||
});
|
||||
|
||||
additionalContext = Option.String('--context', {
|
||||
description: 'Additional context for generation',
|
||||
});
|
||||
|
||||
targetAgent = Option.String('--agent,-a', {
|
||||
description: 'Target agent for generated skill',
|
||||
});
|
||||
|
||||
// Similar skills option
|
||||
skillName = Option.String({ required: false });
|
||||
|
||||
// Common options
|
||||
limit = Option.String('--limit,-l', {
|
||||
description: 'Maximum number of results',
|
||||
});
|
||||
|
||||
minRelevance = Option.String('--min-relevance', {
|
||||
description: 'Minimum relevance score (0-1)',
|
||||
});
|
||||
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output in JSON format',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output file for generated skill',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const aiConfig = this.getAIConfig();
|
||||
const manager = new AIManager(aiConfig);
|
||||
|
||||
if (!this.json) {
|
||||
const providerName = manager.getProviderName();
|
||||
if (providerName === 'mock') {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'⚠ Using mock AI provider (limited functionality)\n' +
|
||||
' Set ANTHROPIC_API_KEY or OPENAI_API_KEY for real AI features\n'
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
switch (this.subcommand) {
|
||||
case 'search':
|
||||
return await this.handleSearch(manager);
|
||||
case 'generate':
|
||||
case 'gen':
|
||||
return await this.handleGenerate(manager);
|
||||
case 'similar':
|
||||
return await this.handleSimilar(manager);
|
||||
default:
|
||||
console.error(
|
||||
chalk.red(`Unknown subcommand: ${this.subcommand}\n`)
|
||||
);
|
||||
console.log('Valid subcommands: search, generate, similar');
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleSearch(manager: AIManager): Promise<number> {
|
||||
const query = this.query || this.skillName;
|
||||
if (!query) {
|
||||
console.error(chalk.red('Search query required (--query or positional argument)'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skills = await this.loadSkills();
|
||||
if (skills.length === 0) {
|
||||
console.log(
|
||||
chalk.yellow('No skills found. Run "skillkit recommend --update" first.')
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const spinner = ora('Searching with AI...').start();
|
||||
|
||||
try {
|
||||
const results = await manager.searchSkills(query, skills, {
|
||||
limit: this.limit ? parseInt(this.limit, 10) : 10,
|
||||
minRelevance: this.minRelevance
|
||||
? parseFloat(this.minRelevance)
|
||||
: 0.5,
|
||||
includeReasoning: !this.json,
|
||||
});
|
||||
|
||||
spinner.stop();
|
||||
|
||||
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(`\nAI Search Results (${results.length} found):\n`));
|
||||
|
||||
for (const result of results) {
|
||||
const score = Math.round(result.relevance * 100);
|
||||
const scoreColor =
|
||||
score >= 70 ? chalk.green : score >= 50 ? chalk.yellow : chalk.dim;
|
||||
|
||||
console.log(
|
||||
` ${scoreColor(`${score}%`)} ${chalk.bold(result.skill.name)}`
|
||||
);
|
||||
|
||||
if (result.skill.description) {
|
||||
console.log(` ${chalk.dim(result.skill.description)}`);
|
||||
}
|
||||
|
||||
if (result.reasoning) {
|
||||
console.log(` ${chalk.dim('→ ' + result.reasoning)}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Search failed');
|
||||
console.error(
|
||||
chalk.red(error instanceof Error ? error.message : String(error))
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleGenerate(manager: AIManager): Promise<number> {
|
||||
const description = this.description;
|
||||
if (!description) {
|
||||
console.error(chalk.red('Description required (--description)'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
let codeExamples: string[] = [];
|
||||
if (this.fromCode) {
|
||||
const codePath = resolve(this.fromCode);
|
||||
try {
|
||||
const code = await fs.readFile(codePath, 'utf-8');
|
||||
codeExamples = [code];
|
||||
} catch {
|
||||
console.error(chalk.red(`Failed to read code file: ${codePath}`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
const example: SkillExample = {
|
||||
description,
|
||||
context: this.additionalContext,
|
||||
codeExamples,
|
||||
targetAgent: this.targetAgent,
|
||||
};
|
||||
|
||||
const spinner = ora('Generating skill with AI...').start();
|
||||
|
||||
try {
|
||||
const generated = await manager.generateSkill(example, {
|
||||
targetAgent: this.targetAgent,
|
||||
includeTests: true,
|
||||
includeDocumentation: true,
|
||||
});
|
||||
|
||||
spinner.stop();
|
||||
|
||||
const validation = manager.validateGenerated(generated);
|
||||
if (!validation.valid) {
|
||||
console.log(chalk.yellow('\n⚠ Generated skill has validation warnings:'));
|
||||
for (const error of validation.errors) {
|
||||
console.log(chalk.dim(` • ${error}`));
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(generated, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.green('\n✓ Generated skill successfully\n'));
|
||||
console.log(chalk.cyan('Name:') + ` ${generated.name}`);
|
||||
console.log(chalk.cyan('Description:') + ` ${generated.description}`);
|
||||
console.log(
|
||||
chalk.cyan('Tags:') + ` ${generated.tags.join(', ')}`
|
||||
);
|
||||
console.log(
|
||||
chalk.cyan('Confidence:') +
|
||||
` ${Math.round(generated.confidence * 100)}%`
|
||||
);
|
||||
|
||||
if (generated.reasoning) {
|
||||
console.log(chalk.cyan('Reasoning:') + ` ${generated.reasoning}`);
|
||||
}
|
||||
|
||||
console.log('\n' + chalk.dim('Content:'));
|
||||
console.log(chalk.dim('─'.repeat(60)));
|
||||
console.log(generated.content);
|
||||
console.log(chalk.dim('─'.repeat(60)));
|
||||
|
||||
if (this.output) {
|
||||
const outputPath = resolve(this.output);
|
||||
await fs.writeFile(outputPath, generated.content, 'utf-8');
|
||||
console.log(chalk.green(`\n✓ Saved to: ${outputPath}`));
|
||||
} else {
|
||||
console.log(
|
||||
chalk.dim('\nSave with: --output <filename>')
|
||||
);
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Generation failed');
|
||||
console.error(
|
||||
chalk.red(error instanceof Error ? error.message : String(error))
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async handleSimilar(manager: AIManager): Promise<number> {
|
||||
const skillName = this.skillName;
|
||||
if (!skillName) {
|
||||
console.error(chalk.red('Skill name required'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skills = await this.loadSkills();
|
||||
if (skills.length === 0) {
|
||||
console.log(
|
||||
chalk.yellow('No skills found. Run "skillkit recommend --update" first.')
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
const targetSkill = skills.find(
|
||||
(s) => s.name.toLowerCase() === skillName.toLowerCase()
|
||||
);
|
||||
|
||||
if (!targetSkill) {
|
||||
console.error(chalk.red(`Skill not found: ${skillName}`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const spinner = ora('Finding similar skills...').start();
|
||||
|
||||
try {
|
||||
const results = await manager.findSimilar(targetSkill, skills, {
|
||||
limit: this.limit ? parseInt(this.limit, 10) : 10,
|
||||
minRelevance: this.minRelevance
|
||||
? parseFloat(this.minRelevance)
|
||||
: 0.5,
|
||||
includeReasoning: !this.json,
|
||||
});
|
||||
|
||||
spinner.stop();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(results, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (results.length === 0) {
|
||||
console.log(
|
||||
chalk.yellow(`No similar skills found for "${skillName}"`)
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(
|
||||
chalk.cyan(`\nSkills similar to "${skillName}" (${results.length} found):\n`)
|
||||
);
|
||||
|
||||
for (const result of results) {
|
||||
const score = Math.round(result.relevance * 100);
|
||||
const scoreColor =
|
||||
score >= 70 ? chalk.green : score >= 50 ? chalk.yellow : chalk.dim;
|
||||
|
||||
console.log(
|
||||
` ${scoreColor(`${score}%`)} ${chalk.bold(result.skill.name)}`
|
||||
);
|
||||
|
||||
if (result.skill.description) {
|
||||
console.log(` ${chalk.dim(result.skill.description)}`);
|
||||
}
|
||||
|
||||
if (result.reasoning) {
|
||||
console.log(` ${chalk.dim('→ ' + result.reasoning)}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
return 0;
|
||||
} catch (error) {
|
||||
spinner.fail('Search failed');
|
||||
console.error(
|
||||
chalk.red(error instanceof Error ? error.message : String(error))
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async loadSkills(): Promise<SearchableSkill[]> {
|
||||
const index = loadIndexFromCache();
|
||||
if (!index) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return index.skills.map((s) => ({
|
||||
name: s.name,
|
||||
description: s.description,
|
||||
content: '',
|
||||
tags: s.tags,
|
||||
source: s.source,
|
||||
}));
|
||||
}
|
||||
|
||||
private getAIConfig() {
|
||||
const apiKey =
|
||||
process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY;
|
||||
|
||||
return {
|
||||
provider:
|
||||
process.env.ANTHROPIC_API_KEY
|
||||
? ('anthropic' as const)
|
||||
: process.env.OPENAI_API_KEY
|
||||
? ('openai' as const)
|
||||
: ('none' as const),
|
||||
apiKey,
|
||||
model: process.env.ANTHROPIC_API_KEY ? 'claude-3-sonnet-20240229' : undefined,
|
||||
maxTokens: 4096,
|
||||
temperature: 0.7,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import chalk from 'chalk';
|
||||
import { AuditLogger, type AuditQuery, type AuditEventType } from '@skillkit/core';
|
||||
|
||||
export class AuditCommand extends Command {
|
||||
static override paths = [['audit']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'View and manage audit logs',
|
||||
details: `
|
||||
The audit command provides access to the audit log system.
|
||||
All skill operations, team activities, and plugin actions are logged.
|
||||
|
||||
Subcommands:
|
||||
log View recent audit log entries
|
||||
export Export audit logs to file
|
||||
stats Show audit statistics
|
||||
clear Clear old audit entries
|
||||
`,
|
||||
examples: [
|
||||
['View recent logs', '$0 audit log'],
|
||||
['View logs with filters', '$0 audit log --type skill.install --limit 20'],
|
||||
['Export logs to JSON', '$0 audit export --format json --output audit.json'],
|
||||
['Show statistics', '$0 audit stats'],
|
||||
['Clear logs older than 30 days', '$0 audit clear --days 30'],
|
||||
],
|
||||
});
|
||||
|
||||
subcommand = Option.String({ required: true });
|
||||
|
||||
// Query options
|
||||
type = Option.Array('--type,-t', {
|
||||
description: 'Filter by event type',
|
||||
});
|
||||
|
||||
user = Option.String('--user,-u', {
|
||||
description: 'Filter by user',
|
||||
});
|
||||
|
||||
resource = Option.String('--resource,-r', {
|
||||
description: 'Filter by resource',
|
||||
});
|
||||
|
||||
success = Option.Boolean('--success', {
|
||||
description: 'Show only successful operations',
|
||||
});
|
||||
|
||||
failed = Option.Boolean('--failed', {
|
||||
description: 'Show only failed operations',
|
||||
});
|
||||
|
||||
since = Option.String('--since', {
|
||||
description: 'Show events since date (ISO 8601)',
|
||||
});
|
||||
|
||||
until = Option.String('--until', {
|
||||
description: 'Show events until date (ISO 8601)',
|
||||
});
|
||||
|
||||
limit = Option.String('--limit,-l', {
|
||||
description: 'Maximum number of entries',
|
||||
});
|
||||
|
||||
// Export options
|
||||
format = Option.String('--format,-f', {
|
||||
description: 'Export format (json, csv, text)',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output file path',
|
||||
});
|
||||
|
||||
// Clear options
|
||||
days = Option.String('--days', {
|
||||
description: 'Clear entries older than N days',
|
||||
});
|
||||
|
||||
// Common options
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output in JSON format',
|
||||
});
|
||||
|
||||
projectPath = Option.String('--path,-p', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const targetPath = resolve(this.projectPath || process.cwd());
|
||||
const logDir = path.join(targetPath, '.skillkit');
|
||||
const logger = new AuditLogger(logDir);
|
||||
|
||||
try {
|
||||
switch (this.subcommand) {
|
||||
case 'log':
|
||||
case 'list':
|
||||
return await this.handleLog(logger);
|
||||
case 'export':
|
||||
return await this.handleExport(logger);
|
||||
case 'stats':
|
||||
return await this.handleStats(logger);
|
||||
case 'clear':
|
||||
return await this.handleClear(logger);
|
||||
default:
|
||||
console.error(chalk.red(`Unknown subcommand: ${this.subcommand}\n`));
|
||||
console.log('Valid subcommands: log, export, stats, clear');
|
||||
return 1;
|
||||
}
|
||||
} finally {
|
||||
await logger.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
private async handleLog(logger: AuditLogger): Promise<number> {
|
||||
const query = this.buildQuery();
|
||||
const events = await logger.query(query);
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(events, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (events.length === 0) {
|
||||
console.log(chalk.yellow('No audit events found'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan(`\nAudit Log (${events.length} entries):\n`));
|
||||
|
||||
for (const event of events) {
|
||||
const statusIcon = event.success ? chalk.green('✓') : chalk.red('✗');
|
||||
const timestamp = event.timestamp.toLocaleString();
|
||||
|
||||
console.log(
|
||||
`${statusIcon} ${chalk.dim(timestamp)} ${chalk.bold(event.type)}`
|
||||
);
|
||||
console.log(
|
||||
` ${event.action} on ${chalk.cyan(event.resource)}`
|
||||
);
|
||||
|
||||
if (event.user) {
|
||||
console.log(` ${chalk.dim('User:')} ${event.user}`);
|
||||
}
|
||||
|
||||
if (event.duration) {
|
||||
console.log(` ${chalk.dim('Duration:')} ${event.duration}ms`);
|
||||
}
|
||||
|
||||
if (event.error) {
|
||||
console.log(` ${chalk.red('Error:')} ${event.error}`);
|
||||
}
|
||||
|
||||
if (event.details && Object.keys(event.details).length > 0) {
|
||||
console.log(` ${chalk.dim('Details:')} ${JSON.stringify(event.details)}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async handleExport(logger: AuditLogger): Promise<number> {
|
||||
const format = (this.format as 'json' | 'csv' | 'text') || 'json';
|
||||
const query = this.buildQuery();
|
||||
|
||||
const content = await logger.export({ format, query });
|
||||
|
||||
if (this.output) {
|
||||
const outputPath = resolve(this.output);
|
||||
await fs.writeFile(outputPath, content, 'utf-8');
|
||||
console.log(chalk.green(`✓ Exported audit log to: ${outputPath}`));
|
||||
} else {
|
||||
console.log(content);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async handleStats(logger: AuditLogger): Promise<number> {
|
||||
const stats = await logger.stats();
|
||||
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(stats, null, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.log(chalk.cyan('\nAudit Statistics:\n'));
|
||||
console.log(`Total Events: ${chalk.bold(stats.totalEvents.toString())}`);
|
||||
console.log(
|
||||
`Success Rate: ${chalk.bold(`${(stats.successRate * 100).toFixed(1)}%`)}`
|
||||
);
|
||||
|
||||
if (Object.keys(stats.eventsByType).length > 0) {
|
||||
console.log(chalk.cyan('\nEvents by Type:'));
|
||||
const sorted = Object.entries(stats.eventsByType).sort(
|
||||
([, a], [, b]) => b - a
|
||||
);
|
||||
for (const [type, count] of sorted) {
|
||||
console.log(` ${type.padEnd(30)} ${count}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (stats.topResources.length > 0) {
|
||||
console.log(chalk.cyan('\nTop Resources:'));
|
||||
for (const { resource, count } of stats.topResources) {
|
||||
console.log(` ${resource.padEnd(40)} ${count}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (stats.recentErrors.length > 0) {
|
||||
console.log(chalk.cyan(`\nRecent Errors (${stats.recentErrors.length}):`));
|
||||
for (const error of stats.recentErrors.slice(0, 5)) {
|
||||
const timestamp = error.timestamp.toLocaleString();
|
||||
console.log(
|
||||
` ${chalk.red('✗')} ${chalk.dim(timestamp)} ${error.type}`
|
||||
);
|
||||
if (error.error) {
|
||||
console.log(` ${chalk.dim(error.error)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log();
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async handleClear(logger: AuditLogger): Promise<number> {
|
||||
if (!this.days) {
|
||||
console.error(chalk.red('--days option required'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const daysAgo = parseInt(this.days, 10);
|
||||
const cutoffDate = new Date();
|
||||
cutoffDate.setDate(cutoffDate.getDate() - daysAgo);
|
||||
|
||||
const cleared = await logger.clear(cutoffDate);
|
||||
|
||||
console.log(
|
||||
chalk.green(
|
||||
`✓ Cleared ${cleared} audit entries older than ${daysAgo} days`
|
||||
)
|
||||
);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private buildQuery(): AuditQuery {
|
||||
const query: AuditQuery = {};
|
||||
|
||||
if (this.type && this.type.length > 0) {
|
||||
query.types = this.type as AuditEventType[];
|
||||
}
|
||||
|
||||
if (this.user) {
|
||||
query.user = this.user;
|
||||
}
|
||||
|
||||
if (this.resource) {
|
||||
query.resource = this.resource;
|
||||
}
|
||||
|
||||
if (this.success) {
|
||||
query.success = true;
|
||||
} else if (this.failed) {
|
||||
query.success = false;
|
||||
}
|
||||
|
||||
if (this.since) {
|
||||
query.startDate = new Date(this.since);
|
||||
}
|
||||
|
||||
if (this.until) {
|
||||
query.endDate = new Date(this.until);
|
||||
}
|
||||
|
||||
if (this.limit) {
|
||||
query.limit = parseInt(this.limit, 10);
|
||||
} else {
|
||||
query.limit = 50;
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
type CICDProvider = 'github' | 'gitlab' | 'circleci';
|
||||
|
||||
const GITHUB_ACTIONS_WORKFLOW = `name: SkillKit CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
paths:
|
||||
- '.skillkit/**'
|
||||
- 'skills/**'
|
||||
- '.claude/skills/**'
|
||||
- '.cursor/skills/**'
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
paths:
|
||||
- '.skillkit/**'
|
||||
- 'skills/**'
|
||||
- '.claude/skills/**'
|
||||
- '.cursor/skills/**'
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Validate Skills
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install SkillKit
|
||||
run: npm install -g skillkit
|
||||
|
||||
- name: Validate Skills
|
||||
run: skillkit validate --all
|
||||
|
||||
- name: List Skills
|
||||
run: skillkit list
|
||||
|
||||
test:
|
||||
name: Test Skills
|
||||
runs-on: ubuntu-latest
|
||||
needs: validate
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install SkillKit
|
||||
run: npm install -g skillkit
|
||||
|
||||
- name: Run Skill Tests
|
||||
run: skillkit test --all
|
||||
continue-on-error: true
|
||||
|
||||
sync:
|
||||
name: Sync Skills
|
||||
runs-on: ubuntu-latest
|
||||
needs: validate
|
||||
if: github.event_name == 'push'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Install SkillKit
|
||||
run: npm install -g skillkit
|
||||
|
||||
- name: Sync Skills to All Agents
|
||||
run: skillkit sync --yes
|
||||
`;
|
||||
|
||||
const GITLAB_CI = `stages:
|
||||
- validate
|
||||
- test
|
||||
- sync
|
||||
|
||||
variables:
|
||||
NODE_VERSION: "20"
|
||||
|
||||
.skillkit-base:
|
||||
image: node:\${NODE_VERSION}
|
||||
before_script:
|
||||
- npm install -g skillkit
|
||||
rules:
|
||||
- changes:
|
||||
- .skillkit/**/*
|
||||
- skills/**/*
|
||||
- .claude/skills/**/*
|
||||
- .cursor/skills/**/*
|
||||
|
||||
validate:
|
||||
extends: .skillkit-base
|
||||
stage: validate
|
||||
script:
|
||||
- skillkit validate --all
|
||||
- skillkit list
|
||||
|
||||
test:
|
||||
extends: .skillkit-base
|
||||
stage: test
|
||||
script:
|
||||
- skillkit test --all
|
||||
allow_failure: true
|
||||
needs:
|
||||
- validate
|
||||
|
||||
sync:
|
||||
extends: .skillkit-base
|
||||
stage: sync
|
||||
script:
|
||||
- skillkit sync --yes
|
||||
needs:
|
||||
- validate
|
||||
rules:
|
||||
- if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "master"
|
||||
changes:
|
||||
- .skillkit/**/*
|
||||
- skills/**/*
|
||||
- .claude/skills/**/*
|
||||
- .cursor/skills/**/*
|
||||
`;
|
||||
|
||||
const CIRCLECI_CONFIG = `version: 2.1
|
||||
|
||||
executors:
|
||||
node:
|
||||
docker:
|
||||
- image: cimg/node:20.0
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
executor: node
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: Install SkillKit
|
||||
command: npm install -g skillkit
|
||||
- run:
|
||||
name: Validate Skills
|
||||
command: skillkit validate --all
|
||||
- run:
|
||||
name: List Skills
|
||||
command: skillkit list
|
||||
|
||||
test:
|
||||
executor: node
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: Install SkillKit
|
||||
command: npm install -g skillkit
|
||||
- run:
|
||||
name: Run Skill Tests
|
||||
command: skillkit test --all || true
|
||||
|
||||
sync:
|
||||
executor: node
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: Install SkillKit
|
||||
command: npm install -g skillkit
|
||||
- run:
|
||||
name: Sync Skills
|
||||
command: skillkit sync --yes
|
||||
|
||||
workflows:
|
||||
skillkit:
|
||||
jobs:
|
||||
- validate:
|
||||
filters:
|
||||
branches:
|
||||
only:
|
||||
- main
|
||||
- master
|
||||
- test:
|
||||
requires:
|
||||
- validate
|
||||
- sync:
|
||||
requires:
|
||||
- validate
|
||||
filters:
|
||||
branches:
|
||||
only:
|
||||
- main
|
||||
- master
|
||||
`;
|
||||
|
||||
/**
|
||||
* CICD command - initialize CI/CD workflows for skill validation and testing
|
||||
*/
|
||||
export class CICDCommand extends Command {
|
||||
static override paths = [['cicd', 'init']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Initialize CI/CD workflows for skill validation',
|
||||
details: `
|
||||
The cicd command sets up continuous integration workflows to automatically
|
||||
validate and test skills on every push or pull request.
|
||||
|
||||
Supported providers: github, gitlab, circleci
|
||||
`,
|
||||
examples: [
|
||||
['Initialize GitHub Actions workflow', '$0 cicd init'],
|
||||
['Initialize GitLab CI', '$0 cicd init --provider gitlab'],
|
||||
['Initialize CircleCI', '$0 cicd init --provider circleci'],
|
||||
['Initialize all providers', '$0 cicd init --all'],
|
||||
['Force overwrite existing files', '$0 cicd init --force'],
|
||||
],
|
||||
});
|
||||
|
||||
// Provider selection
|
||||
provider = Option.String('--provider,-p', 'github', {
|
||||
description: 'CI/CD provider (github, gitlab, circleci)',
|
||||
});
|
||||
|
||||
// Generate for all providers
|
||||
all = Option.Boolean('--all,-a', false, {
|
||||
description: 'Generate workflows for all supported providers',
|
||||
});
|
||||
|
||||
// Force overwrite
|
||||
force = Option.Boolean('--force,-f', false, {
|
||||
description: 'Overwrite existing workflow files',
|
||||
});
|
||||
|
||||
// Project path
|
||||
targetPath = Option.String('--path', {
|
||||
description: 'Project path (default: current directory)',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = this.targetPath || process.cwd();
|
||||
|
||||
const providers: CICDProvider[] = this.all
|
||||
? ['github', 'gitlab', 'circleci']
|
||||
: [this.provider as CICDProvider];
|
||||
|
||||
console.log(chalk.cyan('Initializing CI/CD workflows...'));
|
||||
console.log();
|
||||
|
||||
let success = true;
|
||||
let created = false;
|
||||
|
||||
for (const provider of providers) {
|
||||
const result = this.createWorkflow(projectPath, provider);
|
||||
if (result.skipped) {
|
||||
console.log(chalk.yellow(` ${result.message}`));
|
||||
continue;
|
||||
}
|
||||
if (!result.success) {
|
||||
success = false;
|
||||
console.error(chalk.red(` ${result.message}`));
|
||||
continue;
|
||||
}
|
||||
created = true;
|
||||
console.log(chalk.green(` ✓ ${result.message}`));
|
||||
}
|
||||
|
||||
if (success) {
|
||||
console.log();
|
||||
console.log(
|
||||
created
|
||||
? chalk.green('CI/CD workflows initialized successfully!')
|
||||
: chalk.yellow('CI/CD workflows already exist; nothing to do.')
|
||||
);
|
||||
console.log();
|
||||
if (created) {
|
||||
console.log(chalk.dim('The workflows will run on push/PR to validate your skills.'));
|
||||
console.log(chalk.dim('Commit the generated files to enable CI/CD.'));
|
||||
}
|
||||
}
|
||||
|
||||
return success ? 0 : 1;
|
||||
}
|
||||
|
||||
private createWorkflow(
|
||||
projectPath: string,
|
||||
provider: CICDProvider
|
||||
): { success: boolean; message: string; skipped?: boolean } {
|
||||
switch (provider) {
|
||||
case 'github':
|
||||
return this.createGitHubActions(projectPath);
|
||||
case 'gitlab':
|
||||
return this.createGitLabCI(projectPath);
|
||||
case 'circleci':
|
||||
return this.createCircleCI(projectPath);
|
||||
default:
|
||||
return { success: false, message: `Unknown provider: ${provider}` };
|
||||
}
|
||||
}
|
||||
|
||||
private createGitHubActions(projectPath: string): { success: boolean; message: string; skipped?: boolean } {
|
||||
const workflowDir = join(projectPath, '.github', 'workflows');
|
||||
const workflowFile = join(workflowDir, 'skillkit.yml');
|
||||
|
||||
if (existsSync(workflowFile) && !this.force) {
|
||||
return {
|
||||
success: true,
|
||||
message: `GitHub Actions workflow already exists (use --force to overwrite)`,
|
||||
skipped: true,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
mkdirSync(workflowDir, { recursive: true });
|
||||
writeFileSync(workflowFile, GITHUB_ACTIONS_WORKFLOW);
|
||||
return { success: true, message: `Created ${workflowFile}` };
|
||||
} catch (error) {
|
||||
return { success: false, message: `Failed to create GitHub workflow: ${error}` };
|
||||
}
|
||||
}
|
||||
|
||||
private createGitLabCI(projectPath: string): { success: boolean; message: string; skipped?: boolean } {
|
||||
const ciFile = join(projectPath, '.gitlab-ci.yml');
|
||||
|
||||
if (existsSync(ciFile) && !this.force) {
|
||||
// Check if skillkit jobs already exist for better messaging
|
||||
try {
|
||||
const content = readFileSync(ciFile, 'utf-8');
|
||||
if (content.includes('skillkit')) {
|
||||
return {
|
||||
success: true,
|
||||
message: `.gitlab-ci.yml already contains SkillKit config (use --force to overwrite)`,
|
||||
skipped: true,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
message: `.gitlab-ci.yml already exists (use --force to overwrite)`,
|
||||
skipped: true,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: `Failed to read .gitlab-ci.yml: ${error}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
writeFileSync(ciFile, GITLAB_CI);
|
||||
return { success: true, message: `Created ${ciFile}` };
|
||||
} catch (error) {
|
||||
return { success: false, message: `Failed to create GitLab CI config: ${error}` };
|
||||
}
|
||||
}
|
||||
|
||||
private createCircleCI(projectPath: string): { success: boolean; message: string; skipped?: boolean } {
|
||||
const circleDir = join(projectPath, '.circleci');
|
||||
const configFile = join(circleDir, 'config.yml');
|
||||
|
||||
if (existsSync(configFile) && !this.force) {
|
||||
return {
|
||||
success: true,
|
||||
message: `CircleCI config already exists (use --force to overwrite)`,
|
||||
skipped: true,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
mkdirSync(circleDir, { recursive: true });
|
||||
writeFileSync(configFile, CIRCLECI_CONFIG);
|
||||
return { success: true, message: `Created ${configFile}` };
|
||||
} catch (error) {
|
||||
return { success: false, message: `Failed to create CircleCI config: ${error}` };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
/**
|
||||
* Command CLI
|
||||
*
|
||||
* Manage slash commands and agent integration.
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { readFile, writeFile, mkdir } from 'node:fs/promises';
|
||||
import { resolve, join, dirname, extname } from 'node:path';
|
||||
import * as path from 'node:path';
|
||||
import * as fs from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import {
|
||||
createCommandRegistry,
|
||||
createCommandGenerator,
|
||||
getAgentFormat,
|
||||
supportsSlashCommands,
|
||||
} from '@skillkit/core';
|
||||
import type { SlashCommand, AgentType } from '@skillkit/core';
|
||||
|
||||
export class CommandCmd extends Command {
|
||||
static paths = [['command']];
|
||||
|
||||
static usage = Command.Usage({
|
||||
category: 'Commands',
|
||||
description: 'Manage slash commands and agent integration',
|
||||
details: `
|
||||
This command provides tools for working with slash commands.
|
||||
|
||||
Actions:
|
||||
- list: List registered commands
|
||||
- create: Create a new command from a skill
|
||||
- generate: Generate agent-specific command files
|
||||
- validate: Validate command definitions
|
||||
- export: Export commands to a bundle
|
||||
- import: Import commands from a bundle
|
||||
|
||||
Examples:
|
||||
$ skillkit command list
|
||||
$ skillkit command create my-skill --name my-command
|
||||
$ skillkit command generate --agent claude-code
|
||||
$ skillkit command validate ./commands.json
|
||||
`,
|
||||
examples: [
|
||||
['List all commands', '$0 command list'],
|
||||
['Create command from skill', '$0 command create tdd --name run-tdd'],
|
||||
['Generate for Claude Code', '$0 command generate --agent claude-code'],
|
||||
['Export commands', '$0 command export --output commands.json'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
|
||||
skill = Option.String('--skill,-s', {
|
||||
description: 'Skill to create command from',
|
||||
});
|
||||
|
||||
name = Option.String('--name,-n', {
|
||||
description: 'Command name',
|
||||
});
|
||||
|
||||
description = Option.String('--description,-d', {
|
||||
description: 'Command description',
|
||||
});
|
||||
|
||||
agent = Option.String('--agent,-a', {
|
||||
description: 'Target agent for generation',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output file or directory',
|
||||
});
|
||||
|
||||
input = Option.String('--input,-i', {
|
||||
description: 'Input file',
|
||||
});
|
||||
|
||||
category = Option.String('--category,-c', {
|
||||
description: 'Command category',
|
||||
});
|
||||
|
||||
all = Option.Boolean('--all', false, {
|
||||
description: 'Include all commands (hidden and disabled)',
|
||||
});
|
||||
|
||||
json = Option.Boolean('--json', false, {
|
||||
description: 'Output as JSON',
|
||||
});
|
||||
|
||||
dryRun = Option.Boolean('--dry-run', false, {
|
||||
description: 'Show what would be generated without writing files',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'list':
|
||||
return await this.listCommands();
|
||||
case 'create':
|
||||
return await this.createCommand();
|
||||
case 'generate':
|
||||
return await this.generateCommands();
|
||||
case 'validate':
|
||||
return await this.validateCommands();
|
||||
case 'export':
|
||||
return await this.exportCommands();
|
||||
case 'import':
|
||||
return await this.importCommands();
|
||||
case 'info':
|
||||
return await this.showInfo();
|
||||
default:
|
||||
this.context.stderr.write(
|
||||
`Unknown action: ${this.action}\n` +
|
||||
`Available actions: list, create, generate, validate, export, import, info\n`
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
} catch (error) {
|
||||
this.context.stderr.write(`Error: ${(error as Error).message}\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async listCommands(): Promise<number> {
|
||||
const registry = createCommandRegistry();
|
||||
|
||||
// Load commands from local config
|
||||
await this.loadCommandsFromConfig(registry);
|
||||
|
||||
const commands = registry.search({
|
||||
category: this.category,
|
||||
includeHidden: this.all,
|
||||
includeDisabled: this.all,
|
||||
});
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(commands, null, 2) + '\n');
|
||||
} else {
|
||||
if (commands.length === 0) {
|
||||
this.context.stdout.write('No commands registered.\n');
|
||||
this.context.stdout.write('Use "skillkit command create" to create commands from skills.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(`Registered Commands (${commands.length}):\n\n`);
|
||||
|
||||
// Group by category
|
||||
const categories = new Map<string, typeof commands>();
|
||||
for (const cmd of commands) {
|
||||
const cat = cmd.category || 'uncategorized';
|
||||
if (!categories.has(cat)) {
|
||||
categories.set(cat, []);
|
||||
}
|
||||
categories.get(cat)!.push(cmd);
|
||||
}
|
||||
|
||||
for (const [category, cmds] of categories) {
|
||||
this.context.stdout.write(` ${category.toUpperCase()}\n`);
|
||||
for (const cmd of cmds) {
|
||||
const status = cmd.enabled ? '' : ' (disabled)';
|
||||
const hidden = cmd.hidden ? ' (hidden)' : '';
|
||||
this.context.stdout.write(` /${cmd.name}${status}${hidden}\n`);
|
||||
this.context.stdout.write(` ${cmd.description}\n`);
|
||||
if (cmd.aliases && cmd.aliases.length > 0) {
|
||||
this.context.stdout.write(` Aliases: ${cmd.aliases.join(', ')}\n`);
|
||||
}
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async createCommand(): Promise<number> {
|
||||
if (!this.skill) {
|
||||
this.context.stderr.write('Error: --skill is required for create action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const commandName = this.name || this.skill.toLowerCase().replace(/[^a-z0-9]+/g, '-');
|
||||
|
||||
const command: SlashCommand = {
|
||||
name: commandName,
|
||||
description: this.description || `Execute ${this.skill} skill`,
|
||||
skill: this.skill,
|
||||
category: this.category,
|
||||
examples: [`/${commandName}`],
|
||||
};
|
||||
|
||||
// Save to commands config
|
||||
const configPath = resolve(process.cwd(), '.skillkit', 'commands.json');
|
||||
let commands: SlashCommand[] = [];
|
||||
|
||||
if (existsSync(configPath)) {
|
||||
const content = await readFile(configPath, 'utf-8');
|
||||
const config = JSON.parse(content);
|
||||
commands = config.commands || [];
|
||||
}
|
||||
|
||||
// Check if command already exists
|
||||
const existing = commands.findIndex((c) => c.name === commandName);
|
||||
if (existing >= 0) {
|
||||
// Merge new properties with existing command to preserve metadata
|
||||
const previous = commands[existing];
|
||||
commands[existing] = {
|
||||
...previous,
|
||||
name: commandName,
|
||||
skill: this.skill,
|
||||
description: this.description ?? previous.description ?? command.description,
|
||||
category: this.category ?? previous.category,
|
||||
examples: command.examples?.length ? command.examples : previous.examples,
|
||||
// Preserve existing metadata if not provided
|
||||
aliases: previous.aliases,
|
||||
args: previous.args,
|
||||
tags: previous.tags,
|
||||
hidden: previous.hidden,
|
||||
metadata: previous.metadata,
|
||||
};
|
||||
this.context.stdout.write(`Updated command: /${commandName}\n`);
|
||||
} else {
|
||||
commands.push(command);
|
||||
this.context.stdout.write(`Created command: /${commandName}\n`);
|
||||
}
|
||||
|
||||
// Ensure directory exists
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
|
||||
// Save config
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: '1.0.0', commands }, null, 2)
|
||||
);
|
||||
|
||||
this.context.stdout.write(`Saved to: ${configPath}\n`);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async generateCommands(): Promise<number> {
|
||||
const agent = (this.agent || 'claude-code') as AgentType;
|
||||
|
||||
if (!supportsSlashCommands(agent)) {
|
||||
this.context.stdout.write(`Note: ${agent} has limited slash command support.\n`);
|
||||
}
|
||||
|
||||
const registry = createCommandRegistry();
|
||||
await this.loadCommandsFromConfig(registry);
|
||||
|
||||
const commands = registry.getAll(this.all);
|
||||
|
||||
if (commands.length === 0) {
|
||||
this.context.stderr.write('No commands to generate. Create commands first.\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const generator = createCommandGenerator({
|
||||
includeHidden: this.all,
|
||||
includeDisabled: this.all,
|
||||
});
|
||||
|
||||
const format = getAgentFormat(agent);
|
||||
const outputTarget = this.output
|
||||
? resolve(this.output)
|
||||
: resolve(process.cwd(), format.directory);
|
||||
const outputDir = extname(outputTarget) ? dirname(outputTarget) : outputTarget;
|
||||
|
||||
const result = generator.generate(commands, agent);
|
||||
|
||||
if (typeof result === 'string') {
|
||||
// Single file output (e.g., Cursor rules)
|
||||
const extension = format.extension
|
||||
? format.extension.startsWith('.') ? format.extension : `.${format.extension}`
|
||||
: '.mdc';
|
||||
const filePath = extname(outputTarget)
|
||||
? outputTarget
|
||||
: join(outputTarget, `commands${extension}`);
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write('Would write to: ' + filePath + '\n\n');
|
||||
this.context.stdout.write(result);
|
||||
} else {
|
||||
await mkdir(dirname(filePath), { recursive: true });
|
||||
await writeFile(filePath, result);
|
||||
this.context.stdout.write(`Generated: ${filePath}\n`);
|
||||
}
|
||||
} else {
|
||||
// Multiple file output
|
||||
if (extname(outputTarget)) {
|
||||
this.context.stderr.write(
|
||||
'Error: --output must be a directory for multi-file formats\n'
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write('Would write to: ' + outputDir + '\n\n');
|
||||
for (const [filename, content] of result) {
|
||||
this.context.stdout.write(`--- ${filename} ---\n`);
|
||||
this.context.stdout.write(content.substring(0, 500));
|
||||
if (content.length > 500) {
|
||||
this.context.stdout.write('\n... (truncated)\n');
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
} else {
|
||||
await mkdir(outputDir, { recursive: true });
|
||||
for (const [filename, content] of result) {
|
||||
const filePath = join(outputDir, filename);
|
||||
await writeFile(filePath, content);
|
||||
this.context.stdout.write(`Generated: ${filePath}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generate manifest
|
||||
const manifestPath = join(outputDir, 'manifest.json');
|
||||
const manifest = generator.generateManifest(commands);
|
||||
|
||||
if (!this.dryRun) {
|
||||
await writeFile(manifestPath, manifest);
|
||||
this.context.stdout.write(`Generated: ${manifestPath}\n`);
|
||||
}
|
||||
|
||||
this.context.stdout.write(`\nGenerated ${commands.length} commands for ${agent}\n`);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async validateCommands(): Promise<number> {
|
||||
const inputPath = this.input || resolve(process.cwd(), '.skillkit', 'commands.json');
|
||||
|
||||
if (!existsSync(inputPath)) {
|
||||
this.context.stderr.write(`File not found: ${inputPath}\n`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const content = await readFile(inputPath, 'utf-8');
|
||||
const config = JSON.parse(content);
|
||||
const commands: SlashCommand[] = config.commands || [];
|
||||
|
||||
const registry = createCommandRegistry({ validateOnRegister: false });
|
||||
let valid = 0;
|
||||
let invalid = 0;
|
||||
|
||||
this.context.stdout.write(`Validating ${commands.length} commands...\n\n`);
|
||||
|
||||
for (const command of commands) {
|
||||
const result = registry.validate(command);
|
||||
|
||||
if (result.valid) {
|
||||
valid++;
|
||||
if (!this.json) {
|
||||
this.context.stdout.write(`\u2713 /${command.name}\n`);
|
||||
}
|
||||
} else {
|
||||
invalid++;
|
||||
if (!this.json) {
|
||||
this.context.stdout.write(`\u2717 /${command.name}\n`);
|
||||
for (const error of result.errors) {
|
||||
this.context.stdout.write(` Error: ${error}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.json && result.warnings.length > 0) {
|
||||
for (const warning of result.warnings) {
|
||||
this.context.stdout.write(` Warning: ${warning}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(
|
||||
JSON.stringify({
|
||||
total: commands.length,
|
||||
valid,
|
||||
invalid,
|
||||
}) + '\n'
|
||||
);
|
||||
} else {
|
||||
this.context.stdout.write(`\nValidation complete: ${valid} valid, ${invalid} invalid\n`);
|
||||
}
|
||||
|
||||
return invalid > 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
private async exportCommands(): Promise<number> {
|
||||
const registry = createCommandRegistry();
|
||||
await this.loadCommandsFromConfig(registry);
|
||||
|
||||
const bundle = registry.export(this.all);
|
||||
|
||||
if (this.output) {
|
||||
let outputPath = resolve(this.output);
|
||||
|
||||
// Check if output is a directory or ends with path separator
|
||||
const stat = await fs.stat(outputPath).catch(() => null);
|
||||
if ((stat && stat.isDirectory()) || this.output.endsWith(path.sep)) {
|
||||
outputPath = path.join(outputPath, 'commands.json');
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
||||
await writeFile(outputPath, JSON.stringify(bundle, null, 2));
|
||||
this.context.stdout.write(`Exported ${bundle.commands.length} commands to: ${outputPath}\n`);
|
||||
} else {
|
||||
this.context.stdout.write(JSON.stringify(bundle, null, 2) + '\n');
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async importCommands(): Promise<number> {
|
||||
if (!this.input) {
|
||||
this.context.stderr.write('Error: --input is required for import action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const inputPath = resolve(this.input);
|
||||
if (!existsSync(inputPath)) {
|
||||
this.context.stderr.write(`File not found: ${inputPath}\n`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const content = await readFile(inputPath, 'utf-8');
|
||||
const bundle = JSON.parse(content);
|
||||
|
||||
// Load existing commands
|
||||
const configPath = resolve(process.cwd(), '.skillkit', 'commands.json');
|
||||
let existingCommands: SlashCommand[] = [];
|
||||
|
||||
if (existsSync(configPath)) {
|
||||
const existingContent = await readFile(configPath, 'utf-8');
|
||||
const config = JSON.parse(existingContent);
|
||||
existingCommands = config.commands || [];
|
||||
}
|
||||
|
||||
// Merge commands
|
||||
const commandMap = new Map<string, SlashCommand>();
|
||||
for (const cmd of existingCommands) {
|
||||
commandMap.set(cmd.name, cmd);
|
||||
}
|
||||
for (const cmd of bundle.commands) {
|
||||
commandMap.set(cmd.name, cmd);
|
||||
}
|
||||
|
||||
const mergedCommands = Array.from(commandMap.values());
|
||||
|
||||
// Save
|
||||
await mkdir(dirname(configPath), { recursive: true });
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({ version: '1.0.0', commands: mergedCommands }, null, 2)
|
||||
);
|
||||
|
||||
const imported = bundle.commands.length;
|
||||
this.context.stdout.write(`Imported ${imported} commands\n`);
|
||||
this.context.stdout.write(`Total commands: ${mergedCommands.length}\n`);
|
||||
this.context.stdout.write(`Saved to: ${configPath}\n`);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async showInfo(): Promise<number> {
|
||||
const agent = (this.agent || 'claude-code') as AgentType;
|
||||
const format = getAgentFormat(agent);
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(format, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write(`Agent: ${agent}\n`);
|
||||
this.context.stdout.write(`Directory: ${format.directory}\n`);
|
||||
this.context.stdout.write(`Extension: ${format.extension}\n`);
|
||||
this.context.stdout.write(`Supports Slash Commands: ${format.supportsSlashCommands}\n`);
|
||||
this.context.stdout.write(`Supports Command Files: ${format.supportsCommandFiles}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async loadCommandsFromConfig(
|
||||
registry: ReturnType<typeof createCommandRegistry>
|
||||
): Promise<void> {
|
||||
const configPath = resolve(process.cwd(), '.skillkit', 'commands.json');
|
||||
|
||||
if (existsSync(configPath)) {
|
||||
const content = await readFile(configPath, 'utf-8');
|
||||
const config = JSON.parse(content);
|
||||
const commands: SlashCommand[] = config.commands || [];
|
||||
|
||||
for (const command of commands) {
|
||||
try {
|
||||
registry.register(command);
|
||||
} catch {
|
||||
// Skip invalid commands
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(', ')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
`;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* Hook Command
|
||||
*
|
||||
* Manage skill hooks for automatic triggering
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { createHookManager, type HookEvent, type InjectionMode } from '@skillkit/core';
|
||||
|
||||
export class HookCommand extends Command {
|
||||
static override paths = [['hook']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage skill hooks for automatic triggering',
|
||||
examples: [
|
||||
['List all hooks', '$0 hook list'],
|
||||
['Add a session start hook', '$0 hook add session:start tdd-workflow'],
|
||||
['Add a file save hook with pattern', '$0 hook add file:save code-review --pattern "*.ts"'],
|
||||
['Remove a hook', '$0 hook remove <hook-id>'],
|
||||
['Enable a hook', '$0 hook enable <hook-id>'],
|
||||
['Disable a hook', '$0 hook disable <hook-id>'],
|
||||
['Generate agent hooks', '$0 hook generate --agent claude-code'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
target = Option.String({ required: false });
|
||||
skill = Option.String({ required: false });
|
||||
pattern = Option.String('--pattern,-p', { description: 'File pattern matcher' });
|
||||
agent = Option.String('--agent,-a', { description: 'Target agent for generation' });
|
||||
inject = Option.String('--inject,-i', { description: 'Injection mode: content, reference, prompt' });
|
||||
priority = Option.String('--priority', { description: 'Hook priority (higher = earlier)' });
|
||||
verbose = Option.Boolean('--verbose,-v', { description: 'Show detailed output' });
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'list':
|
||||
return await this.listHooks(projectPath);
|
||||
case 'add':
|
||||
return await this.addHook(projectPath);
|
||||
case 'remove':
|
||||
return await this.removeHook(projectPath);
|
||||
case 'enable':
|
||||
return await this.enableHook(projectPath);
|
||||
case 'disable':
|
||||
return await this.disableHook(projectPath);
|
||||
case 'generate':
|
||||
return await this.generateHooks(projectPath);
|
||||
case 'info':
|
||||
return await this.showHookInfo(projectPath);
|
||||
default:
|
||||
this.context.stderr.write(chalk.red(`Unknown action: ${this.action}\n`));
|
||||
this.context.stderr.write('Available actions: list, add, remove, enable, disable, generate, info\n');
|
||||
return 1;
|
||||
}
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async listHooks(projectPath: string): Promise<number> {
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
|
||||
if (hooks.length === 0) {
|
||||
this.context.stdout.write('No hooks configured.\n');
|
||||
this.context.stdout.write(chalk.gray('Run `skillkit hook add <event> <skill>` to add a hook.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan('Configured Hooks:\n\n'));
|
||||
|
||||
// Group by event
|
||||
const eventGroups = new Map<string, typeof hooks>();
|
||||
for (const hook of hooks) {
|
||||
const group = eventGroups.get(hook.event) || [];
|
||||
group.push(hook);
|
||||
eventGroups.set(hook.event, group);
|
||||
}
|
||||
|
||||
for (const [event, eventHooks] of eventGroups) {
|
||||
this.context.stdout.write(chalk.yellow(`${event}:\n`));
|
||||
for (const hook of eventHooks) {
|
||||
const status = hook.enabled ? chalk.green('●') : chalk.gray('○');
|
||||
this.context.stdout.write(` ${status} ${chalk.white(hook.id.slice(0, 8))} → ${hook.skills.join(', ')}\n`);
|
||||
if (hook.matcher) {
|
||||
this.context.stdout.write(chalk.gray(` Pattern: ${hook.matcher}\n`));
|
||||
}
|
||||
if (this.verbose) {
|
||||
this.context.stdout.write(chalk.gray(` Inject: ${hook.inject}, Priority: ${hook.priority || 0}\n`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.context.stdout.write(`\nTotal: ${hooks.length} hooks\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async addHook(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Event type required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit hook add <event> <skill>\n');
|
||||
this.context.stderr.write('Events: session:start, session:end, file:save, file:open, task:start, commit:pre, commit:post, error:occur, test:fail, build:fail\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.skill) {
|
||||
this.context.stderr.write(chalk.red('Skill name required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit hook add <event> <skill>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const event = this.target as HookEvent;
|
||||
const validEvents: HookEvent[] = [
|
||||
'session:start', 'session:resume', 'session:end',
|
||||
'file:open', 'file:save', 'file:create', 'file:delete',
|
||||
'task:start', 'task:complete',
|
||||
'commit:pre', 'commit:post',
|
||||
'error:occur', 'test:fail', 'test:pass',
|
||||
'build:start', 'build:fail', 'build:success',
|
||||
];
|
||||
|
||||
if (!validEvents.includes(event)) {
|
||||
this.context.stderr.write(chalk.red(`Invalid event: ${this.target}\n`));
|
||||
this.context.stderr.write(`Valid events: ${validEvents.join(', ')}\n`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
|
||||
const hook = manager.registerHook({
|
||||
event,
|
||||
skills: [this.skill],
|
||||
inject: (this.inject as InjectionMode) || 'reference',
|
||||
matcher: this.pattern,
|
||||
priority: this.priority ? parseInt(this.priority, 10) : 0,
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
manager.save();
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Hook added: ${hook.id.slice(0, 8)}\n`));
|
||||
this.context.stdout.write(` Event: ${event}\n`);
|
||||
this.context.stdout.write(` Skill: ${this.skill}\n`);
|
||||
if (this.pattern) {
|
||||
this.context.stdout.write(` Pattern: ${this.pattern}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async removeHook(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Hook ID required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit hook remove <hook-id>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
|
||||
// Find hook by ID prefix
|
||||
const hook = hooks.find((h) => h.id.startsWith(this.target!));
|
||||
if (!hook) {
|
||||
this.context.stderr.write(chalk.red(`Hook not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
manager.unregisterHook(hook.id);
|
||||
manager.save();
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Hook removed: ${hook.id.slice(0, 8)}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async enableHook(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Hook ID required.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
const hook = hooks.find((h) => h.id.startsWith(this.target!));
|
||||
|
||||
if (!hook) {
|
||||
this.context.stderr.write(chalk.red(`Hook not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
manager.enableHook(hook.id);
|
||||
manager.save();
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Hook enabled: ${hook.id.slice(0, 8)}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async disableHook(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Hook ID required.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
const hook = hooks.find((h) => h.id.startsWith(this.target!));
|
||||
|
||||
if (!hook) {
|
||||
this.context.stderr.write(chalk.red(`Hook not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
manager.disableHook(hook.id);
|
||||
manager.save();
|
||||
|
||||
this.context.stdout.write(chalk.yellow(`○ Hook disabled: ${hook.id.slice(0, 8)}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async generateHooks(projectPath: string): Promise<number> {
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
|
||||
if (hooks.length === 0) {
|
||||
this.context.stdout.write('No hooks configured to generate.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
const agent = this.agent || 'claude-code';
|
||||
const generated = manager.generateAgentHooks(agent as any);
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`Generated hooks for ${agent}:\n\n`));
|
||||
|
||||
if (typeof generated === 'string') {
|
||||
this.context.stdout.write(generated);
|
||||
} else {
|
||||
this.context.stdout.write(JSON.stringify(generated, null, 2));
|
||||
}
|
||||
|
||||
this.context.stdout.write('\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async showHookInfo(projectPath: string): Promise<number> {
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Hook ID required.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const manager = createHookManager({ projectPath });
|
||||
const hooks = manager.getAllHooks();
|
||||
const hook = hooks.find((h) => h.id.startsWith(this.target!));
|
||||
|
||||
if (!hook) {
|
||||
this.context.stderr.write(chalk.red(`Hook not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`\nHook: ${hook.id}\n`));
|
||||
this.context.stdout.write(`Event: ${hook.event}\n`);
|
||||
this.context.stdout.write(`Skills: ${hook.skills.join(', ')}\n`);
|
||||
this.context.stdout.write(`Enabled: ${hook.enabled ? 'Yes' : 'No'}\n`);
|
||||
this.context.stdout.write(`Inject: ${hook.inject}\n`);
|
||||
this.context.stdout.write(`Priority: ${hook.priority || 0}\n`);
|
||||
if (hook.matcher) {
|
||||
this.context.stdout.write(`Pattern: ${hook.matcher}\n`);
|
||||
}
|
||||
if (hook.condition) {
|
||||
this.context.stdout.write(`Condition: ${hook.condition}\n`);
|
||||
}
|
||||
if (hook.agentOverrides) {
|
||||
this.context.stdout.write(`Agent Overrides: ${Object.keys(hook.agentOverrides).join(', ')}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// 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';
|
||||
export { SettingsCommand } from './settings.js';
|
||||
export { CICDCommand } from './cicd.js';
|
||||
export { TeamCommand } from './team.js';
|
||||
export { PluginCommand } from './plugin.js';
|
||||
export { MethodologyCommand } from './methodology.js';
|
||||
export { HookCommand } from './hook.js';
|
||||
export { PlanCommand } from './plan.js';
|
||||
export { CommandCmd } from './command.js';
|
||||
export { AICommand } from './ai.js';
|
||||
export { AuditCommand } from './audit.js';
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) + '...';
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
/**
|
||||
* Methodology Command
|
||||
*
|
||||
* Manage methodology packs for AI coding agents
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { createMethodologyManager, createMethodologyLoader } from '@skillkit/core';
|
||||
|
||||
export class MethodologyCommand extends Command {
|
||||
static override paths = [['methodology']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage methodology packs for AI coding agents',
|
||||
examples: [
|
||||
['List available packs', '$0 methodology list'],
|
||||
['Install all methodology packs', '$0 methodology install'],
|
||||
['Install specific pack', '$0 methodology install testing'],
|
||||
['Install specific skill', '$0 methodology install testing/red-green-refactor'],
|
||||
['Sync methodology skills to agents', '$0 methodology sync'],
|
||||
['Search methodology skills', '$0 methodology search tdd'],
|
||||
['Show pack details', '$0 methodology info testing'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
target = Option.String({ required: false });
|
||||
agent = Option.String('--agent,-a', { description: 'Target agent for sync' });
|
||||
dryRun = Option.Boolean('--dry-run', { description: 'Preview without making changes' });
|
||||
verbose = Option.Boolean('--verbose,-v', { description: 'Show detailed output' });
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'list':
|
||||
return await this.listPacks();
|
||||
case 'install':
|
||||
return await this.installPacks(projectPath);
|
||||
case 'uninstall':
|
||||
return await this.uninstallPack(projectPath);
|
||||
case 'sync':
|
||||
return await this.syncSkills(projectPath);
|
||||
case 'search':
|
||||
return await this.searchSkills();
|
||||
case 'info':
|
||||
return await this.showPackInfo();
|
||||
case 'installed':
|
||||
return await this.listInstalled(projectPath);
|
||||
default:
|
||||
this.context.stderr.write(chalk.red(`Unknown action: ${this.action}\n`));
|
||||
this.context.stderr.write('Available actions: list, install, uninstall, sync, search, info, installed\n');
|
||||
return 1;
|
||||
}
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async listPacks(): Promise<number> {
|
||||
const loader = createMethodologyLoader();
|
||||
const packs = await loader.loadAllPacks();
|
||||
|
||||
if (packs.length === 0) {
|
||||
this.context.stdout.write('No methodology packs available.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan('Available Methodology Packs:\n\n'));
|
||||
|
||||
for (const pack of packs) {
|
||||
this.context.stdout.write(chalk.green(` ${pack.name}`) + ` v${pack.version}\n`);
|
||||
this.context.stdout.write(chalk.gray(` ${pack.description}\n`));
|
||||
this.context.stdout.write(` Skills: ${pack.skills.join(', ')}\n`);
|
||||
this.context.stdout.write(` Tags: ${pack.tags.join(', ')}\n`);
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
|
||||
this.context.stdout.write(`Total: ${packs.length} packs\n`);
|
||||
this.context.stdout.write(chalk.gray('\nRun `skillkit methodology install` to install all packs.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async installPacks(projectPath: string): Promise<number> {
|
||||
const manager = createMethodologyManager({ projectPath });
|
||||
const loader = manager.getLoader();
|
||||
|
||||
if (this.target) {
|
||||
// Check if it's a skill ID (pack/skill) or pack name
|
||||
if (this.target.includes('/')) {
|
||||
// Install single skill
|
||||
this.context.stdout.write(`Installing skill: ${chalk.cyan(this.target)}...\n`);
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write(chalk.yellow('[dry-run] Would install skill.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = await manager.installSkill(this.target);
|
||||
|
||||
if (result.success) {
|
||||
this.context.stdout.write(chalk.green(`✓ Skill installed: ${this.target}\n`));
|
||||
} else {
|
||||
for (const failed of result.failed) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${failed.name}: ${failed.error}\n`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
// Install single pack
|
||||
this.context.stdout.write(`Installing pack: ${chalk.cyan(this.target)}...\n`);
|
||||
|
||||
if (this.dryRun) {
|
||||
const pack = await loader.loadPack(this.target);
|
||||
if (pack) {
|
||||
this.context.stdout.write(chalk.yellow(`[dry-run] Would install ${pack.skills.length} skills.\n`));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = await manager.installPack(this.target);
|
||||
|
||||
if (result.success) {
|
||||
this.context.stdout.write(chalk.green(`✓ Pack "${this.target}" installed!\n`));
|
||||
this.context.stdout.write(` Installed: ${result.installed.length} skills\n`);
|
||||
if (result.skipped.length > 0) {
|
||||
this.context.stdout.write(` Skipped (already installed): ${result.skipped.length}\n`);
|
||||
}
|
||||
} else {
|
||||
this.context.stderr.write(chalk.red(`✗ Failed to install pack\n`));
|
||||
for (const failed of result.failed) {
|
||||
this.context.stderr.write(chalk.red(` - ${failed.name}: ${failed.error}\n`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Install all packs
|
||||
this.context.stdout.write('Installing all methodology packs...\n\n');
|
||||
|
||||
if (this.dryRun) {
|
||||
const packs = await loader.loadAllPacks();
|
||||
let totalSkills = 0;
|
||||
for (const pack of packs) {
|
||||
this.context.stdout.write(chalk.yellow(`[dry-run] Would install ${pack.name} (${pack.skills.length} skills)\n`));
|
||||
totalSkills += pack.skills.length;
|
||||
}
|
||||
this.context.stdout.write(chalk.yellow(`\n[dry-run] Would install ${totalSkills} skills total.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = await manager.installAllPacks();
|
||||
|
||||
if (result.success) {
|
||||
this.context.stdout.write(chalk.green('\n✓ All methodology packs installed!\n'));
|
||||
this.context.stdout.write(` Installed: ${result.installed.length} skills\n`);
|
||||
if (result.skipped.length > 0) {
|
||||
this.context.stdout.write(` Skipped (already installed): ${result.skipped.length}\n`);
|
||||
}
|
||||
} else {
|
||||
this.context.stdout.write(chalk.yellow('\n⚠ Some skills failed to install:\n'));
|
||||
for (const failed of result.failed) {
|
||||
this.context.stderr.write(chalk.red(` - ${failed.name}: ${failed.error}\n`));
|
||||
}
|
||||
this.context.stdout.write(`\n Installed: ${result.installed.length} skills\n`);
|
||||
}
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.gray('\nRun `skillkit methodology sync` to sync to detected agents.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async uninstallPack(projectPath: string): Promise<number> {
|
||||
const manager = createMethodologyManager({ projectPath });
|
||||
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Pack name required for uninstall.\n'));
|
||||
this.context.stderr.write('Usage: skillkit methodology uninstall <pack-name>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write(chalk.yellow(`[dry-run] Would uninstall pack: ${this.target}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
await manager.uninstallPack(this.target);
|
||||
this.context.stdout.write(chalk.green(`✓ Pack "${this.target}" uninstalled.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async syncSkills(projectPath: string): Promise<number> {
|
||||
const manager = createMethodologyManager({ projectPath, autoSync: false });
|
||||
|
||||
this.context.stdout.write('Syncing methodology skills to detected agents...\n\n');
|
||||
|
||||
if (this.dryRun) {
|
||||
const installed = manager.listInstalledSkills();
|
||||
this.context.stdout.write(chalk.yellow(`[dry-run] Would sync ${installed.length} skills.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = await manager.syncAll();
|
||||
|
||||
if (result.synced.length > 0) {
|
||||
this.context.stdout.write(chalk.green('✓ Sync complete!\n'));
|
||||
for (const sync of result.synced) {
|
||||
this.context.stdout.write(` ${sync.skill} → ${sync.agents.join(', ')}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
if (result.failed.length > 0) {
|
||||
this.context.stdout.write(chalk.yellow('\n⚠ Some syncs failed:\n'));
|
||||
for (const fail of result.failed) {
|
||||
this.context.stderr.write(chalk.red(` ${fail.skill} (${fail.agent}): ${fail.error}\n`));
|
||||
}
|
||||
}
|
||||
|
||||
if (result.synced.length === 0 && result.failed.length === 0) {
|
||||
this.context.stdout.write('No installed skills to sync. Run `skillkit methodology install` first.\n');
|
||||
}
|
||||
|
||||
return result.success ? 0 : 1;
|
||||
}
|
||||
|
||||
private async searchSkills(): Promise<number> {
|
||||
const loader = createMethodologyLoader();
|
||||
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Search query required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit methodology search <query>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skills = await loader.searchSkills(this.target);
|
||||
|
||||
if (skills.length === 0) {
|
||||
this.context.stdout.write(`No skills found matching "${this.target}".\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`Found ${skills.length} skills matching "${this.target}":\n\n`));
|
||||
|
||||
for (const skill of skills) {
|
||||
this.context.stdout.write(chalk.green(` ${skill.id}`) + ` v${skill.version}\n`);
|
||||
this.context.stdout.write(chalk.gray(` ${skill.description || 'No description'}\n`));
|
||||
if (skill.tags.length > 0) {
|
||||
this.context.stdout.write(` Tags: ${skill.tags.join(', ')}\n`);
|
||||
}
|
||||
if (this.verbose && skill.metadata.triggers) {
|
||||
this.context.stdout.write(` Triggers: ${skill.metadata.triggers.join(', ')}\n`);
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async showPackInfo(): Promise<number> {
|
||||
const loader = createMethodologyLoader();
|
||||
|
||||
if (!this.target) {
|
||||
this.context.stderr.write(chalk.red('Pack name required.\n'));
|
||||
this.context.stderr.write('Usage: skillkit methodology info <pack-name>\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const pack = await loader.loadPack(this.target);
|
||||
|
||||
if (!pack) {
|
||||
this.context.stderr.write(chalk.red(`Pack not found: ${this.target}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`\nPack: ${pack.name}\n`));
|
||||
this.context.stdout.write(`Version: ${pack.version}\n`);
|
||||
this.context.stdout.write(`Description: ${pack.description}\n`);
|
||||
this.context.stdout.write(`Tags: ${pack.tags.join(', ')}\n`);
|
||||
this.context.stdout.write(`Author: ${pack.author || 'Unknown'}\n`);
|
||||
this.context.stdout.write(`License: ${pack.license || 'Unknown'}\n`);
|
||||
this.context.stdout.write(`Compatibility: ${pack.compatibility.join(', ')}\n`);
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`\nSkills (${pack.skills.length}):\n`));
|
||||
|
||||
const skills = await loader.loadPackSkills(this.target);
|
||||
for (const skill of skills) {
|
||||
this.context.stdout.write(chalk.green(` ${skill.id.split('/')[1]}\n`));
|
||||
this.context.stdout.write(chalk.gray(` ${skill.description || 'No description'}\n`));
|
||||
if (this.verbose) {
|
||||
if (skill.metadata.triggers) {
|
||||
this.context.stdout.write(` Triggers: ${skill.metadata.triggers.join(', ')}\n`);
|
||||
}
|
||||
if (skill.metadata.difficulty) {
|
||||
this.context.stdout.write(` Difficulty: ${skill.metadata.difficulty}\n`);
|
||||
}
|
||||
if (skill.metadata.estimatedTime) {
|
||||
this.context.stdout.write(` Est. Time: ${skill.metadata.estimatedTime} min\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.gray(`\nRun \`skillkit methodology install ${this.target}\` to install this pack.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async listInstalled(projectPath: string): Promise<number> {
|
||||
const manager = createMethodologyManager({ projectPath });
|
||||
|
||||
const installedPacks = manager.listInstalledPacks();
|
||||
const installedSkills = manager.listInstalledSkills();
|
||||
|
||||
if (installedPacks.length === 0 && installedSkills.length === 0) {
|
||||
this.context.stdout.write('No methodology skills installed.\n');
|
||||
this.context.stdout.write(chalk.gray('Run `skillkit methodology install` to install methodology packs.\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (installedPacks.length > 0) {
|
||||
this.context.stdout.write(chalk.cyan('Installed Packs:\n'));
|
||||
for (const pack of installedPacks) {
|
||||
this.context.stdout.write(chalk.green(` ${pack.name}`) + ` v${pack.version}\n`);
|
||||
this.context.stdout.write(` Skills: ${pack.skills.length}\n`);
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
}
|
||||
|
||||
if (installedSkills.length > 0) {
|
||||
this.context.stdout.write(chalk.cyan('Installed Skills:\n'));
|
||||
for (const skill of installedSkills) {
|
||||
const syncStatus = skill.syncedAgents.length > 0
|
||||
? chalk.green(`synced to ${skill.syncedAgents.length} agents`)
|
||||
: chalk.yellow('not synced');
|
||||
this.context.stdout.write(` ${chalk.green(skill.id)} v${skill.version} [${syncStatus}]\n`);
|
||||
}
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.gray(`\nTotal: ${installedSkills.length} skills installed.\n`));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
/**
|
||||
* Plan Command
|
||||
*
|
||||
* Manage structured development plans.
|
||||
* Parse, validate, execute, and generate plans.
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import {
|
||||
createPlanParser,
|
||||
createPlanValidator,
|
||||
createPlanGenerator,
|
||||
createPlanExecutor,
|
||||
dryRunExecutor,
|
||||
shellExecutor,
|
||||
TASK_TEMPLATES,
|
||||
} from '@skillkit/core';
|
||||
|
||||
export class PlanCommand extends Command {
|
||||
static paths = [['plan']];
|
||||
|
||||
static usage = Command.Usage({
|
||||
category: 'Development',
|
||||
description: 'Manage structured development plans',
|
||||
details: `
|
||||
This command provides tools for working with structured development plans.
|
||||
|
||||
Actions:
|
||||
- parse: Parse a markdown plan to structured format
|
||||
- validate: Validate a plan for completeness
|
||||
- execute: Execute a plan (with optional dry-run)
|
||||
- generate: Generate a plan from task list
|
||||
- templates: List available task templates
|
||||
- create: Create a new empty plan
|
||||
|
||||
Examples:
|
||||
$ skillkit plan parse ./plan.md
|
||||
$ skillkit plan validate ./plan.md
|
||||
$ skillkit plan execute ./plan.md --dry-run
|
||||
$ skillkit plan generate "Add auth" --tasks "Setup,Login,Logout"
|
||||
$ skillkit plan templates
|
||||
`,
|
||||
examples: [
|
||||
['Parse a markdown plan', '$0 plan parse ./development-plan.md'],
|
||||
['Validate a plan', '$0 plan validate ./plan.md --strict'],
|
||||
['Dry-run execute a plan', '$0 plan execute ./plan.md --dry-run'],
|
||||
['List task templates', '$0 plan templates'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
|
||||
file = Option.String('--file,-f', {
|
||||
description: 'Plan file path',
|
||||
});
|
||||
|
||||
output = Option.String('--output,-o', {
|
||||
description: 'Output file path',
|
||||
});
|
||||
|
||||
name = Option.String('--name,-n', {
|
||||
description: 'Plan name',
|
||||
});
|
||||
|
||||
goal = Option.String('--goal,-g', {
|
||||
description: 'Plan goal',
|
||||
});
|
||||
|
||||
tasks = Option.String('--tasks,-t', {
|
||||
description: 'Comma-separated list of task names',
|
||||
});
|
||||
|
||||
template = Option.String('--template', {
|
||||
description: 'Task template to use',
|
||||
});
|
||||
|
||||
techStack = Option.String('--tech-stack', {
|
||||
description: 'Comma-separated tech stack',
|
||||
});
|
||||
|
||||
dryRun = Option.Boolean('--dry-run', false, {
|
||||
description: 'Dry run execution (no actual changes)',
|
||||
});
|
||||
|
||||
strict = Option.Boolean('--strict', false, {
|
||||
description: 'Strict validation (treat warnings as errors)',
|
||||
});
|
||||
|
||||
stopOnError = Option.Boolean('--stop-on-error', true, {
|
||||
description: 'Stop execution on first error',
|
||||
});
|
||||
|
||||
verbose = Option.Boolean('--verbose,-v', false, {
|
||||
description: 'Verbose output',
|
||||
});
|
||||
|
||||
json = Option.Boolean('--json', false, {
|
||||
description: 'Output as JSON',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'parse':
|
||||
return await this.parsePlan();
|
||||
case 'validate':
|
||||
return await this.validatePlan();
|
||||
case 'execute':
|
||||
return await this.executePlan();
|
||||
case 'generate':
|
||||
return await this.generatePlan();
|
||||
case 'templates':
|
||||
return await this.listTemplates();
|
||||
case 'create':
|
||||
return await this.createPlan();
|
||||
default:
|
||||
this.context.stderr.write(
|
||||
`Unknown action: ${this.action}\n` +
|
||||
`Available actions: parse, validate, execute, generate, templates, create\n`
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
} catch (error) {
|
||||
this.context.stderr.write(`Error: ${(error as Error).message}\n`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async parsePlan(): Promise<number> {
|
||||
if (!this.file) {
|
||||
this.context.stderr.write('Error: --file is required for parse action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const filePath = resolve(this.file);
|
||||
const content = await readFile(filePath, 'utf-8');
|
||||
|
||||
const parser = createPlanParser();
|
||||
const plan = parser.parse(content);
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(plan, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write(`Plan: ${plan.name}\n`);
|
||||
this.context.stdout.write(`Goal: ${plan.goal}\n`);
|
||||
this.context.stdout.write(`Status: ${plan.status}\n`);
|
||||
this.context.stdout.write(`Tasks: ${plan.tasks.length}\n\n`);
|
||||
|
||||
for (const task of plan.tasks) {
|
||||
this.context.stdout.write(` Task ${task.id}: ${task.name}\n`);
|
||||
this.context.stdout.write(` Steps: ${task.steps.length}\n`);
|
||||
if (task.estimatedMinutes) {
|
||||
this.context.stdout.write(` Estimated: ${task.estimatedMinutes} min\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.output) {
|
||||
const outputPath = resolve(this.output);
|
||||
await writeFile(outputPath, JSON.stringify(plan, null, 2));
|
||||
this.context.stdout.write(`\nSaved to: ${outputPath}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async validatePlan(): Promise<number> {
|
||||
if (!this.file) {
|
||||
this.context.stderr.write('Error: --file is required for validate action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const filePath = resolve(this.file);
|
||||
const content = await readFile(filePath, 'utf-8');
|
||||
|
||||
const parser = createPlanParser();
|
||||
const plan = parser.parse(content);
|
||||
|
||||
const validator = createPlanValidator({ strict: this.strict });
|
||||
const result = validator.validate(plan);
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write(`Validation: ${result.valid ? 'PASSED' : 'FAILED'}\n\n`);
|
||||
|
||||
this.context.stdout.write(`Statistics:\n`);
|
||||
this.context.stdout.write(` Total tasks: ${result.stats.totalTasks}\n`);
|
||||
this.context.stdout.write(` Total steps: ${result.stats.totalSteps}\n`);
|
||||
this.context.stdout.write(` Estimated time: ${result.stats.estimatedMinutes} minutes\n`);
|
||||
this.context.stdout.write(` Tasks with tests: ${result.stats.tasksWithTests}\n`);
|
||||
this.context.stdout.write(` Avg steps/task: ${result.stats.avgStepsPerTask}\n\n`);
|
||||
|
||||
if (result.issues.length > 0) {
|
||||
this.context.stdout.write(`Issues:\n`);
|
||||
for (const issue of result.issues) {
|
||||
const icon =
|
||||
issue.type === 'error' ? '\u274C' : issue.type === 'warning' ? '\u26A0\uFE0F' : '\u2139\uFE0F';
|
||||
const location = issue.taskId ? `Task ${issue.taskId}` : 'Plan';
|
||||
this.context.stdout.write(` ${icon} [${location}] ${issue.message}\n`);
|
||||
if (issue.suggestion && this.verbose) {
|
||||
this.context.stdout.write(` Suggestion: ${issue.suggestion}\n`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.context.stdout.write('No issues found.\n');
|
||||
}
|
||||
}
|
||||
|
||||
return result.valid ? 0 : 1;
|
||||
}
|
||||
|
||||
private async executePlan(): Promise<number> {
|
||||
if (!this.file) {
|
||||
this.context.stderr.write('Error: --file is required for execute action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const filePath = resolve(this.file);
|
||||
const content = await readFile(filePath, 'utf-8');
|
||||
|
||||
const parser = createPlanParser();
|
||||
const plan = parser.parse(content);
|
||||
|
||||
// Validate first
|
||||
const validator = createPlanValidator({ strict: this.strict });
|
||||
const validation = validator.validate(plan);
|
||||
|
||||
if (!validation.valid) {
|
||||
this.context.stderr.write('Plan validation failed. Fix errors before executing.\n');
|
||||
for (const issue of validation.issues.filter((i) => i.type === 'error')) {
|
||||
this.context.stderr.write(` \u274C ${issue.message}\n`);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Create executor
|
||||
const executor = createPlanExecutor({
|
||||
stepExecutor: this.dryRun ? dryRunExecutor : shellExecutor,
|
||||
});
|
||||
|
||||
// Add progress listener
|
||||
executor.addListener((event, _plan, task) => {
|
||||
if (this.verbose) {
|
||||
if (event === 'plan:task_started' && task) {
|
||||
this.context.stdout.write(`Starting task ${task.id}: ${task.name}\n`);
|
||||
} else if (event === 'plan:task_completed' && task) {
|
||||
this.context.stdout.write(`Completed task ${task.id}: ${task.name}\n`);
|
||||
} else if (event === 'plan:task_failed' && task) {
|
||||
this.context.stderr.write(`Failed task ${task.id}: ${task.name}\n`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.context.stdout.write(`Executing plan: ${plan.name}\n`);
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write('(Dry run mode - no actual changes)\n');
|
||||
}
|
||||
this.context.stdout.write('\n');
|
||||
|
||||
const result = await executor.execute(plan, {
|
||||
dryRun: this.dryRun,
|
||||
stopOnError: this.stopOnError,
|
||||
onProgress: (taskId, step, status) => {
|
||||
if (this.verbose) {
|
||||
this.context.stdout.write(` Task ${taskId}, Step ${step}: ${status}\n`);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
this.context.stdout.write('\n');
|
||||
|
||||
if (this.json) {
|
||||
this.context.stdout.write(
|
||||
JSON.stringify(
|
||||
{
|
||||
...result,
|
||||
taskResults: Object.fromEntries(result.taskResults),
|
||||
},
|
||||
null,
|
||||
2
|
||||
) + '\n'
|
||||
);
|
||||
} else {
|
||||
this.context.stdout.write(`Execution: ${result.success ? 'SUCCESS' : 'FAILED'}\n`);
|
||||
this.context.stdout.write(`Duration: ${result.durationMs}ms\n`);
|
||||
this.context.stdout.write(`Completed: ${result.completedTasks.length} tasks\n`);
|
||||
this.context.stdout.write(`Failed: ${result.failedTasks.length} tasks\n`);
|
||||
this.context.stdout.write(`Skipped: ${result.skippedTasks.length} tasks\n`);
|
||||
|
||||
if (result.errors && result.errors.length > 0) {
|
||||
this.context.stdout.write('\nErrors:\n');
|
||||
for (const error of result.errors) {
|
||||
this.context.stderr.write(` - ${error}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result.success ? 0 : 1;
|
||||
}
|
||||
|
||||
private async generatePlan(): Promise<number> {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write('Error: --name is required for generate action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const generator = createPlanGenerator({
|
||||
includeTests: true,
|
||||
includeCommits: true,
|
||||
techStack: this.techStack?.split(',').map((s) => s.trim()).filter((s) => s !== ''),
|
||||
});
|
||||
|
||||
let plan;
|
||||
|
||||
if (this.tasks) {
|
||||
const taskNames = this.tasks.split(',').map((s) => s.trim()).filter((s) => s !== '');
|
||||
plan = generator.fromTaskList(this.name, this.goal || 'Complete the tasks', taskNames, {
|
||||
template: this.template as keyof typeof TASK_TEMPLATES,
|
||||
techStack: this.techStack?.split(',').map((s) => s.trim()).filter((s) => s !== ''),
|
||||
});
|
||||
} else {
|
||||
plan = generator.createPlan(this.name, this.goal || 'Complete the project');
|
||||
if (this.techStack) {
|
||||
plan.techStack = this.techStack.split(',').map((s) => s.trim()).filter((s) => s !== '');
|
||||
}
|
||||
}
|
||||
|
||||
const markdown = generator.toMarkdown(plan);
|
||||
|
||||
if (this.output) {
|
||||
const outputPath = resolve(this.output);
|
||||
await writeFile(outputPath, markdown);
|
||||
this.context.stdout.write(`Plan saved to: ${outputPath}\n`);
|
||||
} else if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(plan, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write(markdown);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async listTemplates(): Promise<number> {
|
||||
if (this.json) {
|
||||
this.context.stdout.write(JSON.stringify(TASK_TEMPLATES, null, 2) + '\n');
|
||||
} else {
|
||||
this.context.stdout.write('Available Task Templates:\n\n');
|
||||
|
||||
for (const [name, template] of Object.entries(TASK_TEMPLATES)) {
|
||||
this.context.stdout.write(` ${name}\n`);
|
||||
this.context.stdout.write(` ${template.description}\n`);
|
||||
this.context.stdout.write(` Steps: ${template.steps.length}\n`);
|
||||
this.context.stdout.write(` Estimated: ${template.estimatedMinutes} min\n\n`);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async createPlan(): Promise<number> {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write('Error: --name is required for create action\n');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const generator = createPlanGenerator({
|
||||
includeTests: true,
|
||||
includeCommits: true,
|
||||
});
|
||||
|
||||
const plan = generator.createPlan(this.name, this.goal || 'Complete the project');
|
||||
|
||||
if (this.techStack) {
|
||||
plan.techStack = this.techStack.split(',').map((s) => s.trim()).filter((s) => s !== '');
|
||||
}
|
||||
|
||||
const markdown = generator.toMarkdown(plan);
|
||||
|
||||
const outputPath = this.output || resolve(`${this.name.toLowerCase().replace(/\s+/g, '-')}-plan.md`);
|
||||
await writeFile(outputPath, markdown);
|
||||
this.context.stdout.write(`Plan created: ${outputPath}\n`);
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* Plugin Command
|
||||
*
|
||||
* Manage SkillKit plugins
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { join, isAbsolute, resolve, sep } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { existsSync, mkdirSync, copyFileSync, cpSync, rmSync } from 'node:fs';
|
||||
import chalk from 'chalk';
|
||||
import { createPluginManager, loadPlugin, loadPluginsFromDirectory } from '@skillkit/core';
|
||||
|
||||
export class PluginCommand extends Command {
|
||||
static override paths = [['plugin']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage SkillKit plugins',
|
||||
examples: [
|
||||
['List installed plugins', '$0 plugin list'],
|
||||
['Install a plugin', '$0 plugin install --source ./my-plugin'],
|
||||
['Install from npm', '$0 plugin install --source skillkit-plugin-gitlab'],
|
||||
['Uninstall a plugin', '$0 plugin uninstall --name my-plugin'],
|
||||
['Enable a plugin', '$0 plugin enable --name my-plugin'],
|
||||
['Disable a plugin', '$0 plugin disable --name my-plugin'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
source = Option.String('--source,-s', { description: 'Plugin source (file path or npm package)' });
|
||||
name = Option.String('--name,-n', { description: 'Plugin name' });
|
||||
global = Option.Boolean('--global,-g', { description: 'Use global plugin directory' });
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = this.global
|
||||
? join(homedir(), '.skillkit')
|
||||
: process.cwd();
|
||||
const pluginManager = createPluginManager(projectPath);
|
||||
|
||||
// Auto-load plugins from directory
|
||||
const pluginsDir = this.global
|
||||
? join(projectPath, 'plugins')
|
||||
: join(projectPath, '.skillkit', 'plugins');
|
||||
try {
|
||||
const plugins = await loadPluginsFromDirectory(pluginsDir);
|
||||
for (const plugin of plugins) {
|
||||
if (pluginManager.isPluginEnabled(plugin.metadata.name)) {
|
||||
await pluginManager.register(plugin);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Plugins directory may not exist
|
||||
}
|
||||
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'list':
|
||||
return this.listPlugins(pluginManager);
|
||||
case 'install':
|
||||
return await this.installPlugin(pluginManager);
|
||||
case 'uninstall':
|
||||
return await this.uninstallPlugin(pluginManager);
|
||||
case 'enable':
|
||||
return this.enablePlugin(pluginManager);
|
||||
case 'disable':
|
||||
return this.disablePlugin(pluginManager);
|
||||
case 'info':
|
||||
return this.pluginInfo(pluginManager);
|
||||
default:
|
||||
this.context.stderr.write(chalk.red(`Unknown action: ${this.action}\n`));
|
||||
this.context.stderr.write('Available actions: list, install, uninstall, enable, disable, info\n');
|
||||
return 1;
|
||||
}
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private listPlugins(pluginManager: ReturnType<typeof createPluginManager>): number {
|
||||
const plugins = pluginManager.listPlugins();
|
||||
|
||||
if (plugins.length === 0) {
|
||||
this.context.stdout.write('No plugins installed.\n');
|
||||
this.context.stdout.write('Use `skillkit plugin install --source <source>` to install a plugin.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`Installed Plugins (${plugins.length}):\n\n`));
|
||||
|
||||
for (const plugin of plugins) {
|
||||
const enabled = pluginManager.isPluginEnabled(plugin.name);
|
||||
const status = enabled
|
||||
? chalk.green('enabled')
|
||||
: chalk.gray('disabled');
|
||||
|
||||
this.context.stdout.write(chalk.cyan(` ${plugin.name}`) + ` v${plugin.version} [${status}]\n`);
|
||||
if (plugin.description) {
|
||||
this.context.stdout.write(chalk.gray(` ${plugin.description}\n`));
|
||||
}
|
||||
}
|
||||
|
||||
// Show registered extensions
|
||||
const translators = pluginManager.getAllTranslators();
|
||||
const providers = pluginManager.getAllProviders();
|
||||
const commands = pluginManager.getAllCommands();
|
||||
|
||||
if (translators.size > 0 || providers.size > 0 || commands.length > 0) {
|
||||
this.context.stdout.write(chalk.cyan('\nRegistered Extensions:\n'));
|
||||
if (translators.size > 0) {
|
||||
this.context.stdout.write(` Translators: ${Array.from(translators.keys()).join(', ')}\n`);
|
||||
}
|
||||
if (providers.size > 0) {
|
||||
this.context.stdout.write(` Providers: ${Array.from(providers.keys()).join(', ')}\n`);
|
||||
}
|
||||
if (commands.length > 0) {
|
||||
this.context.stdout.write(` Commands: ${commands.map((c) => c.name).join(', ')}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate plugin name to prevent path traversal attacks
|
||||
* Allows scoped npm names like @scope/name (mirrors loader.ts validation)
|
||||
*/
|
||||
private isValidPluginName(name: string): boolean {
|
||||
if (!name) return false;
|
||||
|
||||
// Reject backslashes, path traversal sequences, and names starting with '.'
|
||||
if (name.includes('\\') || name.includes('..') || name === '.' || name.startsWith('.')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Allow scoped npm names (@scope/name) or simple names (no slashes)
|
||||
// Use the same regex pattern as loader.ts validatePlugin
|
||||
return /^(?:@[a-z0-9-]+\/)?[a-z0-9-]+$/.test(name);
|
||||
}
|
||||
|
||||
private async installPlugin(pluginManager: ReturnType<typeof createPluginManager>): Promise<number> {
|
||||
if (!this.source) {
|
||||
this.context.stderr.write(chalk.red('--source is required for install\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Expand tilde to home directory for all operations
|
||||
const resolvedSource = this.source.startsWith('~')
|
||||
? join(homedir(), this.source.slice(1))
|
||||
: this.source;
|
||||
|
||||
this.context.stdout.write(`Installing plugin from ${this.source}...\n`);
|
||||
|
||||
const plugin = await loadPlugin(resolvedSource);
|
||||
|
||||
// Validate plugin name from metadata
|
||||
const pluginName = plugin.metadata.name;
|
||||
if (!this.isValidPluginName(pluginName)) {
|
||||
this.context.stderr.write(chalk.red(`Invalid plugin name: ${pluginName}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Determine plugins directory
|
||||
const projectPath = this.global
|
||||
? join(homedir(), '.skillkit')
|
||||
: process.cwd();
|
||||
const pluginsDir = this.global
|
||||
? join(projectPath, 'plugins')
|
||||
: join(projectPath, '.skillkit', 'plugins');
|
||||
|
||||
// Persist plugin files to disk if source is a local file/directory
|
||||
const isLocalPath =
|
||||
this.source.startsWith('./') ||
|
||||
this.source.startsWith('../') ||
|
||||
this.source.startsWith('/') ||
|
||||
this.source.startsWith('~') ||
|
||||
this.source.includes('\\') ||
|
||||
isAbsolute(this.source);
|
||||
|
||||
if (isLocalPath && existsSync(resolvedSource)) {
|
||||
const targetDir = join(pluginsDir, pluginName);
|
||||
|
||||
// Verify targetDir is within pluginsDir (defense in depth)
|
||||
const resolvedTarget = resolve(targetDir);
|
||||
const resolvedPluginsDir = resolve(pluginsDir);
|
||||
if (!resolvedTarget.startsWith(resolvedPluginsDir + sep)) {
|
||||
this.context.stderr.write(chalk.red('Invalid plugin name\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Create plugins directory if needed
|
||||
if (!existsSync(pluginsDir)) {
|
||||
mkdirSync(pluginsDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Copy plugin to plugins directory
|
||||
const { statSync } = await import('node:fs');
|
||||
const sourceStat = statSync(resolvedSource);
|
||||
|
||||
if (sourceStat.isDirectory()) {
|
||||
// Copy entire directory
|
||||
cpSync(resolvedSource, targetDir, { recursive: true });
|
||||
} else {
|
||||
// Copy single file with a loader-recognized name
|
||||
if (!existsSync(targetDir)) {
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
}
|
||||
// Preserve .mjs for ESM plugins, use .js for others
|
||||
let destFileName: string;
|
||||
if (resolvedSource.endsWith('.json')) {
|
||||
destFileName = 'plugin.json';
|
||||
} else if (resolvedSource.endsWith('.mjs')) {
|
||||
destFileName = 'index.mjs';
|
||||
} else {
|
||||
destFileName = 'index.js';
|
||||
}
|
||||
copyFileSync(resolvedSource, join(targetDir, destFileName));
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.dim(` Copied to ${targetDir}\n`));
|
||||
}
|
||||
|
||||
await pluginManager.register(plugin);
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Plugin "${plugin.metadata.name}" installed!\n`));
|
||||
this.context.stdout.write(` Version: ${plugin.metadata.version}\n`);
|
||||
if (plugin.metadata.description) {
|
||||
this.context.stdout.write(` ${plugin.metadata.description}\n`);
|
||||
}
|
||||
|
||||
// Show what was registered
|
||||
if (plugin.translators?.length) {
|
||||
this.context.stdout.write(` Translators: ${plugin.translators.map((t) => t.agentType).join(', ')}\n`);
|
||||
}
|
||||
if (plugin.providers?.length) {
|
||||
this.context.stdout.write(` Providers: ${plugin.providers.map((p) => p.providerName).join(', ')}\n`);
|
||||
}
|
||||
if (plugin.commands?.length) {
|
||||
this.context.stdout.write(` Commands: ${plugin.commands.map((c) => c.name).join(', ')}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async uninstallPlugin(pluginManager: ReturnType<typeof createPluginManager>): Promise<number> {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for uninstall\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Validate plugin name to prevent path traversal attacks
|
||||
if (!this.isValidPluginName(this.name)) {
|
||||
this.context.stderr.write(chalk.red('Invalid plugin name\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
await pluginManager.unregister(this.name);
|
||||
|
||||
// Remove plugin files from disk
|
||||
const projectPath = this.global
|
||||
? join(homedir(), '.skillkit')
|
||||
: process.cwd();
|
||||
const pluginsDir = this.global
|
||||
? join(projectPath, 'plugins')
|
||||
: join(projectPath, '.skillkit', 'plugins');
|
||||
const pluginDir = join(pluginsDir, this.name);
|
||||
|
||||
// Verify pluginDir is within pluginsDir (defense in depth)
|
||||
const resolvedPluginDir = resolve(pluginDir);
|
||||
const resolvedPluginsDir = resolve(pluginsDir);
|
||||
if (!resolvedPluginDir.startsWith(resolvedPluginsDir + sep)) {
|
||||
this.context.stderr.write(chalk.red('Invalid plugin name\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (existsSync(pluginDir)) {
|
||||
rmSync(pluginDir, { recursive: true, force: true });
|
||||
this.context.stdout.write(chalk.dim(` Removed ${pluginDir}\n`));
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Plugin "${this.name}" uninstalled.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private enablePlugin(pluginManager: ReturnType<typeof createPluginManager>): number {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for enable\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
pluginManager.enablePlugin(this.name);
|
||||
this.context.stdout.write(chalk.green(`✓ Plugin "${this.name}" enabled.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private disablePlugin(pluginManager: ReturnType<typeof createPluginManager>): number {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for disable\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
pluginManager.disablePlugin(this.name);
|
||||
this.context.stdout.write(chalk.green(`✓ Plugin "${this.name}" disabled.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private pluginInfo(pluginManager: ReturnType<typeof createPluginManager>): number {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for info\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const plugin = pluginManager.getPlugin(this.name);
|
||||
if (!plugin) {
|
||||
this.context.stderr.write(chalk.red(`Plugin "${this.name}" not found.\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const { metadata } = plugin;
|
||||
const enabled = pluginManager.isPluginEnabled(this.name);
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`${metadata.name}`) + ` v${metadata.version}\n`);
|
||||
this.context.stdout.write(`Status: ${enabled ? 'enabled' : 'disabled'}\n`);
|
||||
if (metadata.description) {
|
||||
this.context.stdout.write(`Description: ${metadata.description}\n`);
|
||||
}
|
||||
if (metadata.author) {
|
||||
this.context.stdout.write(`Author: ${metadata.author}\n`);
|
||||
}
|
||||
if (metadata.homepage) {
|
||||
this.context.stdout.write(`Homepage: ${metadata.homepage}\n`);
|
||||
}
|
||||
if (metadata.keywords?.length) {
|
||||
this.context.stdout.write(`Keywords: ${metadata.keywords.join(', ')}\n`);
|
||||
}
|
||||
if (metadata.dependencies?.length) {
|
||||
this.context.stdout.write(`Dependencies: ${metadata.dependencies.join(', ')}\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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) + '...';
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { loadConfig, saveConfig, type SkillkitConfig, type AgentType } from '@skillkit/core';
|
||||
|
||||
const VALID_AGENTS: AgentType[] = [
|
||||
'claude-code', 'cursor', 'codex', 'gemini-cli', 'opencode',
|
||||
'antigravity', 'amp', 'clawdbot', 'droid', 'github-copilot',
|
||||
'goose', 'kilo', 'kiro-cli', 'roo', 'trae', 'windsurf', 'universal',
|
||||
];
|
||||
|
||||
/**
|
||||
* Settings command - view and modify SkillKit configuration
|
||||
*/
|
||||
export class SettingsCommand extends Command {
|
||||
static override paths = [['settings'], ['config']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'View and modify SkillKit settings',
|
||||
details: `
|
||||
View or modify SkillKit configuration. Settings are stored in skillkit.yaml.
|
||||
|
||||
Without arguments, shows all current settings.
|
||||
With --set, modifies a specific setting.
|
||||
`,
|
||||
examples: [
|
||||
['Show all settings', '$0 settings'],
|
||||
['Set default agent', '$0 settings --set agent=claude-code'],
|
||||
['Enable auto-sync', '$0 settings --set autoSync=true'],
|
||||
['Set cache directory', '$0 settings --set cacheDir=~/.cache/skillkit'],
|
||||
['Show settings as JSON', '$0 settings --json'],
|
||||
['Save to global config', '$0 settings --set agent=cursor --global'],
|
||||
],
|
||||
});
|
||||
|
||||
// Set a setting
|
||||
set = Option.String('--set,-s', {
|
||||
description: 'Set a config value (key=value)',
|
||||
});
|
||||
|
||||
// Get a specific setting
|
||||
get = Option.String('--get,-g', {
|
||||
description: 'Get a specific setting value',
|
||||
});
|
||||
|
||||
// JSON output
|
||||
json = Option.Boolean('--json,-j', false, {
|
||||
description: 'Output as JSON',
|
||||
});
|
||||
|
||||
// Global config
|
||||
global = Option.Boolean('--global', false, {
|
||||
description: 'Use global config (~/.config/skillkit/)',
|
||||
});
|
||||
|
||||
// Reset to defaults
|
||||
reset = Option.Boolean('--reset', false, {
|
||||
description: 'Reset all settings to defaults',
|
||||
});
|
||||
|
||||
async execute(): Promise<number> {
|
||||
// Load current config (respect --global flag)
|
||||
const config = loadConfig(this.global);
|
||||
|
||||
// Reset to defaults
|
||||
if (this.reset) {
|
||||
const defaultConfig: SkillkitConfig = {
|
||||
version: 1,
|
||||
agent: 'universal',
|
||||
autoSync: true,
|
||||
};
|
||||
saveConfig(defaultConfig, this.global);
|
||||
console.log(chalk.green('Settings reset to defaults'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Get a specific setting
|
||||
if (this.get) {
|
||||
// Check if the key is a known setting (not just if value is undefined)
|
||||
const knownKeys = [
|
||||
'agent', 'autoSync', 'cacheDir', 'skillsDir',
|
||||
'enabledSkills', 'disabledSkills', 'marketplaceSources', 'defaultTimeout'
|
||||
];
|
||||
if (!knownKeys.includes(this.get)) {
|
||||
console.error(chalk.red(`Unknown setting: ${this.get}`));
|
||||
return 1;
|
||||
}
|
||||
const value = this.getConfigValue(config, this.get);
|
||||
if (this.json) {
|
||||
// Use null instead of undefined so the key is preserved in JSON output
|
||||
console.log(JSON.stringify({ [this.get]: value ?? null }));
|
||||
} else {
|
||||
console.log(value ?? '(not set)');
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Set a setting
|
||||
if (this.set) {
|
||||
const [key, ...valueParts] = this.set.split('=');
|
||||
const value = valueParts.join('=');
|
||||
|
||||
if (!key || !this.set.includes('=')) {
|
||||
console.error(chalk.red('Invalid format. Use: --set key=value'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const result = this.setConfigValue(config, key, value);
|
||||
if (!result.success) {
|
||||
console.error(chalk.red(result.error));
|
||||
return 1;
|
||||
}
|
||||
|
||||
saveConfig(config, this.global);
|
||||
console.log(chalk.green(`${key} = ${value}`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Show all settings
|
||||
if (this.json) {
|
||||
console.log(JSON.stringify(config, null, 2));
|
||||
} else {
|
||||
console.log(chalk.cyan('SkillKit Settings'));
|
||||
console.log(chalk.dim('─'.repeat(40)));
|
||||
console.log();
|
||||
|
||||
const settings = [
|
||||
{ key: 'agent', label: 'Default Agent', value: config.agent },
|
||||
{ key: 'autoSync', label: 'Auto Sync', value: config.autoSync ? 'enabled' : 'disabled' },
|
||||
{ key: 'cacheDir', label: 'Cache Dir', value: config.cacheDir || '~/.skillkit/cache' },
|
||||
{ key: 'skillsDir', label: 'Skills Dir', value: config.skillsDir || '(default)' },
|
||||
{ key: 'defaultTimeout', label: 'Timeout', value: config.defaultTimeout ? `${config.defaultTimeout}ms` : '(default)' },
|
||||
];
|
||||
|
||||
for (const setting of settings) {
|
||||
console.log(` ${chalk.white(setting.label.padEnd(14))} ${chalk.dim(setting.value)}`);
|
||||
}
|
||||
|
||||
if (config.enabledSkills?.length) {
|
||||
console.log();
|
||||
console.log(` ${chalk.white('Enabled Skills'.padEnd(14))} ${chalk.dim(config.enabledSkills.join(', '))}`);
|
||||
}
|
||||
|
||||
if (config.disabledSkills?.length) {
|
||||
console.log(` ${chalk.white('Disabled Skills'.padEnd(14))} ${chalk.dim(config.disabledSkills.join(', '))}`);
|
||||
}
|
||||
|
||||
if (config.marketplaceSources?.length) {
|
||||
console.log(` ${chalk.white('Marketplaces'.padEnd(14))} ${chalk.dim(config.marketplaceSources.join(', '))}`);
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log(chalk.dim('Use --set key=value to modify settings'));
|
||||
console.log(chalk.dim('Available keys: agent, autoSync, cacheDir, skillsDir, defaultTimeout'));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private getConfigValue(config: SkillkitConfig, key: string): unknown {
|
||||
switch (key) {
|
||||
case 'agent':
|
||||
return config.agent;
|
||||
case 'autoSync':
|
||||
return config.autoSync;
|
||||
case 'cacheDir':
|
||||
return config.cacheDir;
|
||||
case 'skillsDir':
|
||||
return config.skillsDir;
|
||||
case 'enabledSkills':
|
||||
return config.enabledSkills;
|
||||
case 'disabledSkills':
|
||||
return config.disabledSkills;
|
||||
case 'marketplaceSources':
|
||||
return config.marketplaceSources;
|
||||
case 'defaultTimeout':
|
||||
return config.defaultTimeout;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private setConfigValue(
|
||||
config: SkillkitConfig,
|
||||
key: string,
|
||||
value: string
|
||||
): { success: boolean; error?: string } {
|
||||
switch (key) {
|
||||
case 'agent':
|
||||
if (!VALID_AGENTS.includes(value as AgentType)) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Invalid agent. Valid options: ${VALID_AGENTS.join(', ')}`,
|
||||
};
|
||||
}
|
||||
config.agent = value as AgentType;
|
||||
break;
|
||||
|
||||
case 'autoSync':
|
||||
if (!['true', 'false', 'enabled', 'disabled'].includes(value.toLowerCase())) {
|
||||
return { success: false, error: 'autoSync must be true/false or enabled/disabled' };
|
||||
}
|
||||
config.autoSync = value.toLowerCase() === 'true' || value.toLowerCase() === 'enabled';
|
||||
break;
|
||||
|
||||
case 'cacheDir':
|
||||
config.cacheDir = value || undefined;
|
||||
break;
|
||||
|
||||
case 'skillsDir':
|
||||
config.skillsDir = value || undefined;
|
||||
break;
|
||||
|
||||
case 'defaultTimeout': {
|
||||
const timeout = parseInt(value, 10);
|
||||
if (isNaN(timeout) || timeout <= 0) {
|
||||
return { success: false, error: 'defaultTimeout must be a positive number (milliseconds)' };
|
||||
}
|
||||
config.defaultTimeout = timeout;
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
return { success: false, error: `Unknown setting: ${key}` };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
@@ -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`;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
/**
|
||||
* Team Command
|
||||
*
|
||||
* Manage team skill sharing and collaboration
|
||||
*/
|
||||
|
||||
import { Command, Option } from 'clipanion';
|
||||
import chalk from 'chalk';
|
||||
import { createTeamManager, createSkillBundle, exportBundle, importBundle } from '@skillkit/core';
|
||||
import { join } from 'node:path';
|
||||
|
||||
export class TeamCommand extends Command {
|
||||
static override paths = [['team']];
|
||||
|
||||
static override usage = Command.Usage({
|
||||
description: 'Manage team skill sharing and collaboration',
|
||||
examples: [
|
||||
['Initialize team', '$0 team init --name "My Team" --registry https://github.com/myteam/skills'],
|
||||
['Share a skill', '$0 team share --name my-skill'],
|
||||
['Import a skill', '$0 team import --name shared-skill'],
|
||||
['List shared skills', '$0 team list'],
|
||||
['Sync with remote', '$0 team sync'],
|
||||
['Create a bundle', '$0 team bundle-create --name my-bundle --skills skill1,skill2'],
|
||||
['Export a bundle', '$0 team bundle-export --name my-bundle --output ./bundle.json'],
|
||||
['Import a bundle', '$0 team bundle-import --source ./bundle.json'],
|
||||
],
|
||||
});
|
||||
|
||||
action = Option.String({ required: true });
|
||||
name = Option.String('--name', { description: 'Team name (for init), skill name, or bundle name' });
|
||||
registry = Option.String('--registry', { description: 'Registry URL (for init)' });
|
||||
description = Option.String('--description,-d', { description: 'Description (for share/bundle)' });
|
||||
tags = Option.String('--tags,-t', { description: 'Comma-separated tags (for share)' });
|
||||
skills = Option.String('--skills', { description: 'Comma-separated skill names (for bundle)' });
|
||||
output = Option.String('--output,-o', { description: 'Output path (for bundle-export)' });
|
||||
source = Option.String('--source,-s', { description: 'Source path (for bundle-import)' });
|
||||
overwrite = Option.Boolean('--overwrite', { description: 'Overwrite existing (for import)' });
|
||||
dryRun = Option.Boolean('--dry-run', { description: 'Preview without changes' });
|
||||
|
||||
async execute(): Promise<number> {
|
||||
const projectPath = process.cwd();
|
||||
const teamManager = createTeamManager(projectPath);
|
||||
|
||||
try {
|
||||
switch (this.action) {
|
||||
case 'init':
|
||||
return await this.initTeam(teamManager);
|
||||
case 'share':
|
||||
return await this.shareSkill(teamManager);
|
||||
case 'import':
|
||||
return await this.importSkill(teamManager);
|
||||
case 'list':
|
||||
return await this.listSkills(teamManager);
|
||||
case 'sync':
|
||||
return await this.syncTeam(teamManager);
|
||||
case 'remove':
|
||||
return await this.removeSkill(teamManager);
|
||||
case 'bundle-create':
|
||||
return await this.createBundle(teamManager);
|
||||
case 'bundle-export':
|
||||
return await this.exportSkillBundle(teamManager);
|
||||
case 'bundle-import':
|
||||
return await this.importSkillBundle();
|
||||
default:
|
||||
this.context.stderr.write(chalk.red(`Unknown action: ${this.action}\n`));
|
||||
this.context.stderr.write('Available actions: init, share, import, list, sync, remove, bundle-create, bundle-export, bundle-import\n');
|
||||
return 1;
|
||||
}
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private async initTeam(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name is required for init\n'));
|
||||
return 1;
|
||||
}
|
||||
if (!this.registry) {
|
||||
this.context.stderr.write(chalk.red('--registry is required for init\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const config = await teamManager.init({
|
||||
teamName: this.name,
|
||||
registryUrl: this.registry,
|
||||
});
|
||||
|
||||
this.context.stdout.write(chalk.green('✓ Team initialized!\n'));
|
||||
this.context.stdout.write(` Team ID: ${config.teamId}\n`);
|
||||
this.context.stdout.write(` Registry: ${config.registryUrl}\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async shareSkill(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <skill-name> is required for share\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const shared = await teamManager.shareSkill({
|
||||
skillName: this.name,
|
||||
description: this.description,
|
||||
tags: this.tags?.split(',').map((t) => t.trim()),
|
||||
});
|
||||
|
||||
this.context.stdout.write(chalk.green('✓ Skill shared!\n'));
|
||||
this.context.stdout.write(` Name: ${shared.name}\n`);
|
||||
this.context.stdout.write(` Version: ${shared.version}\n`);
|
||||
this.context.stdout.write(` Source: ${shared.source}\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async importSkill(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <skill-name> is required for import\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const result = await teamManager.importSkill(this.name, {
|
||||
overwrite: this.overwrite,
|
||||
dryRun: this.dryRun,
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${result.error}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write(chalk.cyan(`[dry-run] Would import to: ${result.path}\n`));
|
||||
} else {
|
||||
this.context.stdout.write(chalk.green(`✓ Skill imported to: ${result.path}\n`));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async listSkills(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skills = teamManager.listSharedSkills();
|
||||
|
||||
this.context.stdout.write(chalk.cyan(`Team: ${config.teamName}\n`));
|
||||
this.context.stdout.write(chalk.gray(`Registry: ${config.registryUrl}\n\n`));
|
||||
|
||||
if (skills.length === 0) {
|
||||
this.context.stdout.write('No shared skills yet. Use `skillkit team share` to share a skill.\n');
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.context.stdout.write(`Shared Skills (${skills.length}):\n`);
|
||||
for (const skill of skills) {
|
||||
this.context.stdout.write(chalk.cyan(` ${skill.name}`) + ` v${skill.version}\n`);
|
||||
if (skill.description) {
|
||||
this.context.stdout.write(chalk.gray(` ${skill.description}\n`));
|
||||
}
|
||||
this.context.stdout.write(` by ${skill.author} | ${skill.downloads || 0} downloads\n`);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async syncTeam(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(`Syncing with ${config.registryUrl}...\n`);
|
||||
|
||||
const result = await teamManager.sync();
|
||||
|
||||
this.context.stdout.write(chalk.green('✓ Sync complete!\n'));
|
||||
if (result.added.length > 0) {
|
||||
this.context.stdout.write(` Added: ${result.added.join(', ')}\n`);
|
||||
}
|
||||
if (result.updated.length > 0) {
|
||||
this.context.stdout.write(` Updated: ${result.updated.join(', ')}\n`);
|
||||
}
|
||||
if (result.added.length === 0 && result.updated.length === 0) {
|
||||
this.context.stdout.write(' Already up to date.\n');
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async removeSkill(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <skill-name> is required for remove\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const removed = teamManager.removeSkill(this.name);
|
||||
if (!removed) {
|
||||
this.context.stderr.write(chalk.red(`Skill "${this.name}" not found in team registry.\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Skill "${this.name}" removed from team registry.\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async createBundle(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <bundle-name> is required for bundle-create\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.skills) {
|
||||
this.context.stderr.write(chalk.red('--skills <skill1,skill2,...> is required for bundle-create\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const skillNames = this.skills.split(',').map((s) => s.trim());
|
||||
const projectPath = process.cwd();
|
||||
const skillsDir = join(projectPath, 'skills');
|
||||
|
||||
// Create the bundle
|
||||
const bundle = createSkillBundle(this.name, config.teamName, this.description);
|
||||
|
||||
let addedCount = 0;
|
||||
for (const skillName of skillNames) {
|
||||
const skillPath = join(skillsDir, skillName);
|
||||
try {
|
||||
bundle.addSkill(skillPath);
|
||||
addedCount++;
|
||||
this.context.stdout.write(chalk.gray(` + ${skillName}\n`));
|
||||
} catch (err) {
|
||||
this.context.stderr.write(chalk.yellow(` ⚠ Skipping ${skillName}: ${err instanceof Error ? err.message : 'Unknown error'}\n`));
|
||||
}
|
||||
}
|
||||
|
||||
if (addedCount === 0) {
|
||||
this.context.stderr.write(chalk.red('No skills were added to the bundle.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Export to default location
|
||||
const outputPath = this.output || join(projectPath, '.skillkit', 'bundles', `${this.name}.json`);
|
||||
const result = exportBundle(bundle, outputPath);
|
||||
|
||||
if (!result.success) {
|
||||
this.context.stderr.write(chalk.red(`✗ ${result.error}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.green(`\n✓ Bundle "${this.name}" created with ${addedCount} skills!\n`));
|
||||
this.context.stdout.write(` Checksum: ${bundle.getChecksum()}\n`);
|
||||
this.context.stdout.write(` Output: ${result.path}\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async exportSkillBundle(teamManager: ReturnType<typeof createTeamManager>): Promise<number> {
|
||||
const config = teamManager.load();
|
||||
if (!config) {
|
||||
this.context.stderr.write(chalk.red('Team not initialized. Run `skillkit team init` first.\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.name) {
|
||||
this.context.stderr.write(chalk.red('--name <bundle-name> is required for bundle-export\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (!this.output) {
|
||||
this.context.stderr.write(chalk.red('--output <path> is required for bundle-export\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
const bundlePath = join(projectPath, '.skillkit', 'bundles', `${this.name}.json`);
|
||||
|
||||
// Check if bundle exists
|
||||
const { existsSync, readFileSync, writeFileSync } = await import('node:fs');
|
||||
if (!existsSync(bundlePath)) {
|
||||
this.context.stderr.write(chalk.red(`Bundle "${this.name}" not found. Create it first with bundle-create.\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Copy bundle to output
|
||||
const content = readFileSync(bundlePath, 'utf-8');
|
||||
writeFileSync(this.output, content, 'utf-8');
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Bundle exported to: ${this.output}\n`));
|
||||
return 0;
|
||||
}
|
||||
|
||||
private async importSkillBundle(): Promise<number> {
|
||||
if (!this.source) {
|
||||
this.context.stderr.write(chalk.red('--source <path> is required for bundle-import\n'));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const { existsSync } = await import('node:fs');
|
||||
if (!existsSync(this.source)) {
|
||||
this.context.stderr.write(chalk.red(`Bundle file not found: ${this.source}\n`));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const projectPath = process.cwd();
|
||||
const skillsDir = join(projectPath, 'skills');
|
||||
|
||||
if (this.dryRun) {
|
||||
this.context.stdout.write(chalk.cyan('[dry-run] Would import bundle to: ' + skillsDir + '\n'));
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = importBundle(this.source, skillsDir, { overwrite: this.overwrite });
|
||||
|
||||
if (!result.success && result.imported.length === 0) {
|
||||
this.context.stderr.write(chalk.red('✗ Failed to import bundle:\n'));
|
||||
for (const error of result.errors) {
|
||||
this.context.stderr.write(chalk.red(` - ${error}\n`));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
this.context.stdout.write(chalk.green(`✓ Imported ${result.imported.length} skills from bundle!\n`));
|
||||
for (const name of result.imported) {
|
||||
this.context.stdout.write(chalk.gray(` + ${name}\n`));
|
||||
}
|
||||
if (result.errors.length > 0) {
|
||||
this.context.stdout.write(chalk.yellow('\nWarnings:\n'));
|
||||
for (const error of result.errors) {
|
||||
this.context.stdout.write(chalk.yellow(` - ${error}\n`));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { Command, Option } from 'clipanion';
|
||||
import { resolve } from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import ora from 'ora';
|
||||
import {
|
||||
loadWorkflowByName,
|
||||
loadWorkflow,
|
||||
validateWorkflow,
|
||||
createWorkflowOrchestrator,
|
||||
createSkillExecutor,
|
||||
createSimulatedSkillExecutor,
|
||||
type AgentType,
|
||||
} 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)',
|
||||
});
|
||||
|
||||
// Agent to use for execution
|
||||
agent = Option.String('--agent,-a', {
|
||||
description: 'Agent to use for skill execution (e.g., claude-code, codex)',
|
||||
});
|
||||
|
||||
// Simulate execution (for testing)
|
||||
simulate = Option.Boolean('--simulate', false, {
|
||||
description: 'Simulate execution without running skills (for testing)',
|
||||
});
|
||||
|
||||
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 the skill executor (real or simulated)
|
||||
const skillExecutor = this.simulate
|
||||
? createSimulatedSkillExecutor({
|
||||
delay: 500,
|
||||
onExecute: (skillName) => {
|
||||
if (this.verbose && !this.json) {
|
||||
console.log(chalk.dim(` [Simulated] ${skillName}`));
|
||||
}
|
||||
},
|
||||
})
|
||||
: createSkillExecutor({
|
||||
projectPath: targetPath,
|
||||
preferredAgent: this.agent as AgentType | undefined,
|
||||
fallbackToAvailable: true,
|
||||
onExecutionEvent: (event) => {
|
||||
if (this.verbose && !this.json) {
|
||||
switch (event.type) {
|
||||
case 'skill_found':
|
||||
console.log(chalk.dim(` Found: ${event.message}`));
|
||||
break;
|
||||
case 'skill_not_found':
|
||||
console.log(chalk.red(` Not found: ${event.skillName}`));
|
||||
break;
|
||||
case 'agent_selected':
|
||||
console.log(chalk.dim(` Agent: ${event.agent}`));
|
||||
break;
|
||||
case 'execution_complete':
|
||||
if (!event.success) {
|
||||
console.log(chalk.red(` Error: ${event.error}`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Create orchestrator with real skill executor
|
||||
const orchestrator = createWorkflowOrchestrator(
|
||||
skillExecutor,
|
||||
(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.'));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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';
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"composite": false
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist", "**/*.test.ts"]
|
||||
}
|
||||
@@ -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',
|
||||
});
|
||||
@@ -0,0 +1,340 @@
|
||||
# @skillkit/core
|
||||
|
||||
[](https://www.npmjs.com/package/@skillkit/core)
|
||||
[](https://opensource.org/licenses/Apache-2.0)
|
||||
|
||||
**Core engine for SkillKit** - skill discovery, cross-agent translation, recommendations, session memory, testing, and workflow orchestration.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @skillkit/core
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Skill Discovery**: Find and parse SKILL.md files from any source
|
||||
- **Cross-Agent Translation**: Convert skills between 17 agent formats (Claude Code, Cursor, Windsurf, etc.)
|
||||
- **Project Context Detection**: Analyze project stack, dependencies, and configurations
|
||||
- **Smart Recommendations**: AI-powered skill suggestions based on project profile
|
||||
- **Session Memory**: Capture and persist learnings across AI coding sessions
|
||||
- **Skill Testing**: Test framework with assertions for skill validation
|
||||
- **Workflow Orchestration**: Compose skills into multi-step workflows
|
||||
- **Marketplace Aggregation**: Browse and search curated skill repositories
|
||||
- **Team Collaboration**: Share skill bundles with Git-based remote sync
|
||||
- **Plugin System**: Extend with custom translators, providers, and commands
|
||||
- **Methodologies**: 5 development frameworks (Agile, TDD, DevOps, Design Thinking, Feature Flags)
|
||||
- **Multi-Agent Orchestration**: Coordinate teams of AI agents with task assignment
|
||||
- **Plan System**: Parse, validate, and execute structured development plans
|
||||
- **Hooks & Automation**: Auto-trigger skills on file changes, git events
|
||||
|
||||
## Usage
|
||||
|
||||
### Skill Discovery
|
||||
|
||||
```typescript
|
||||
import { findAllSkills, discoverSkills, parseSkill } from '@skillkit/core';
|
||||
|
||||
// Find all installed skills
|
||||
const skills = findAllSkills(['.claude/skills', '.cursor/skills']);
|
||||
|
||||
// Discover skills from a repository
|
||||
const repoSkills = await discoverSkills('anthropics/skills');
|
||||
|
||||
// Parse a single skill file
|
||||
const skill = parseSkill('./my-skill/SKILL.md');
|
||||
```
|
||||
|
||||
### Cross-Agent Translation
|
||||
|
||||
```typescript
|
||||
import { translateSkill, translateSkillFile, TranslatorRegistry } from '@skillkit/core';
|
||||
|
||||
// Translate skill content to Cursor format
|
||||
const result = translateSkill(skillContent, 'cursor');
|
||||
console.log(result.content); // MDC format for Cursor
|
||||
|
||||
// Translate a skill file
|
||||
const translated = await translateSkillFile('./skill.md', 'windsurf');
|
||||
|
||||
// Get available translators
|
||||
const registry = new TranslatorRegistry();
|
||||
const formats = registry.getSupportedFormats();
|
||||
```
|
||||
|
||||
### Project Context & Recommendations
|
||||
|
||||
```typescript
|
||||
import { ProjectDetector, RecommendationEngine, ContextManager } from '@skillkit/core';
|
||||
|
||||
// Detect project context
|
||||
const detector = new ProjectDetector();
|
||||
const profile = await detector.analyze('./my-project');
|
||||
// profile.stack includes: languages, frameworks, libraries, testing tools, etc.
|
||||
|
||||
// Get skill recommendations
|
||||
const engine = new RecommendationEngine();
|
||||
const recommendations = engine.recommend(profile, availableSkills);
|
||||
// Returns skills sorted by match score
|
||||
|
||||
// Manage project context
|
||||
const ctx = new ContextManager('./my-project');
|
||||
await ctx.init();
|
||||
const context = ctx.getContext();
|
||||
```
|
||||
|
||||
### Session Memory
|
||||
|
||||
```typescript
|
||||
import {
|
||||
createMemoryCompressor,
|
||||
createMemoryInjector,
|
||||
LearningStore,
|
||||
ObservationStore,
|
||||
} from '@skillkit/core';
|
||||
|
||||
// Compress observations into learnings
|
||||
const compressor = createMemoryCompressor('./my-project');
|
||||
const learnings = compressor.compress();
|
||||
|
||||
// Inject relevant memories into prompts
|
||||
const injector = createMemoryInjector('./my-project');
|
||||
const memories = injector.search('authentication patterns');
|
||||
|
||||
// Manage learnings directly
|
||||
const store = new LearningStore('./my-project');
|
||||
const learning = store.add({
|
||||
title: 'React hooks best practices',
|
||||
content: 'Always cleanup effects...',
|
||||
tags: ['react', 'hooks'],
|
||||
});
|
||||
```
|
||||
|
||||
### Skill Testing
|
||||
|
||||
```typescript
|
||||
import { SkillTestRunner, parseTestCases } from '@skillkit/core';
|
||||
|
||||
// Run skill tests
|
||||
const runner = new SkillTestRunner('./my-project');
|
||||
const results = await runner.runAll();
|
||||
|
||||
// Run specific tests
|
||||
const result = await runner.run('./my-skill', {
|
||||
tags: ['unit'],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Parse test cases from skill
|
||||
const testCases = parseTestCases(skillContent);
|
||||
```
|
||||
|
||||
### Workflow Orchestration
|
||||
|
||||
```typescript
|
||||
import { WorkflowOrchestrator, parseWorkflow, WorkflowStore } from '@skillkit/core';
|
||||
|
||||
// Parse and run a workflow
|
||||
const workflow = parseWorkflow('./workflow.yaml');
|
||||
const orchestrator = new WorkflowOrchestrator(workflow);
|
||||
await orchestrator.execute();
|
||||
|
||||
// Manage workflows
|
||||
const store = new WorkflowStore('./my-project');
|
||||
const workflows = store.list();
|
||||
```
|
||||
|
||||
### Marketplace
|
||||
|
||||
```typescript
|
||||
import { createMarketplaceAggregator, MarketplaceSource } from '@skillkit/core';
|
||||
|
||||
// Browse skill marketplace
|
||||
const marketplace = createMarketplaceAggregator();
|
||||
const results = await marketplace.search({ query: 'react' });
|
||||
|
||||
// Filter by tags
|
||||
const filtered = await marketplace.search({
|
||||
query: 'authentication',
|
||||
tags: ['security', 'auth'],
|
||||
limit: 10,
|
||||
});
|
||||
```
|
||||
|
||||
### Team Collaboration
|
||||
|
||||
```typescript
|
||||
import { TeamManager, SkillBundle } from '@skillkit/core';
|
||||
|
||||
// Initialize team
|
||||
const teamManager = new TeamManager('./my-project');
|
||||
await teamManager.init('Engineering Team');
|
||||
|
||||
// Create skill bundle
|
||||
const bundle = await teamManager.createBundle('onboarding', {
|
||||
skills: ['git-workflow', 'code-review'],
|
||||
description: 'New developer onboarding',
|
||||
});
|
||||
|
||||
// Share bundle
|
||||
await teamManager.shareBundle(bundle);
|
||||
|
||||
// Sync with remote registry
|
||||
await teamManager.syncWithRemote('https://github.com/myorg/skills');
|
||||
```
|
||||
|
||||
### Plugin System
|
||||
|
||||
```typescript
|
||||
import { PluginManager, TranslatorPlugin } from '@skillkit/core';
|
||||
|
||||
// Load plugins
|
||||
const pluginManager = new PluginManager('./my-project');
|
||||
await pluginManager.loadAll();
|
||||
|
||||
// Install plugin
|
||||
await pluginManager.install('custom-translator');
|
||||
|
||||
// Create custom plugin
|
||||
const myPlugin: TranslatorPlugin = {
|
||||
name: 'my-agent',
|
||||
parse: async (content) => ({ /* canonical skill */ }),
|
||||
generate: async (skill) => '/* custom format */',
|
||||
};
|
||||
```
|
||||
|
||||
### Methodologies
|
||||
|
||||
```typescript
|
||||
import { MethodologyManager } from '@skillkit/core';
|
||||
|
||||
// List available methodologies
|
||||
const methodologies = await MethodologyManager.list();
|
||||
|
||||
// Load methodology
|
||||
const tdd = await MethodologyManager.load('tdd');
|
||||
// Returns: { name: 'TDD', skills: ['red-green-refactor', 'test-first'], ... }
|
||||
```
|
||||
|
||||
### Multi-Agent Orchestration
|
||||
|
||||
```typescript
|
||||
import { TeamOrchestrator, TaskManager } from '@skillkit/core';
|
||||
|
||||
// Create agent team
|
||||
const orchestrator = new TeamOrchestrator();
|
||||
const team = await orchestrator.createTeam({
|
||||
name: 'feature-dev',
|
||||
leader: { id: 'architect', name: 'System Architect' },
|
||||
teammates: [
|
||||
{ id: 'frontend', name: 'Frontend Dev', capabilities: ['react'] },
|
||||
{ id: 'backend', name: 'Backend Dev', capabilities: ['api'] },
|
||||
],
|
||||
});
|
||||
|
||||
// Manage tasks
|
||||
const taskManager = new TaskManager();
|
||||
const task = taskManager.createTask('Build login', 'Create login endpoint', spec);
|
||||
await taskManager.assignTask(task.id, 'backend');
|
||||
|
||||
// Get stats
|
||||
const stats = taskManager.getStats();
|
||||
```
|
||||
|
||||
### Plan System
|
||||
|
||||
```typescript
|
||||
import { PlanParser, PlanValidator, PlanExecutor } from '@skillkit/core';
|
||||
|
||||
// Parse plan from markdown
|
||||
const parser = new PlanParser();
|
||||
const plan = await parser.parseFile('./plan.md');
|
||||
|
||||
// Validate plan
|
||||
const validator = new PlanValidator();
|
||||
const validation = validator.validate(plan);
|
||||
|
||||
// Execute plan
|
||||
const executor = new PlanExecutor();
|
||||
const result = await executor.execute(plan, { dryRun: false });
|
||||
```
|
||||
|
||||
### Hooks & Automation
|
||||
|
||||
```typescript
|
||||
import { HookRegistry } from '@skillkit/core';
|
||||
|
||||
// Register hooks
|
||||
const hooks = new HookRegistry('./my-project');
|
||||
await hooks.register('pre-commit', {
|
||||
event: 'pre-commit',
|
||||
skill: 'code-review',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
// Trigger hook
|
||||
await hooks.trigger('pre-commit', { files: ['src/index.ts'] });
|
||||
```
|
||||
|
||||
## Supported Agents
|
||||
|
||||
The translator supports all 17 SkillKit-compatible agents:
|
||||
|
||||
| Agent | Format |
|
||||
|-------|--------|
|
||||
| Claude Code | SKILL.md |
|
||||
| Cursor | MDC (.mdc) |
|
||||
| Codex | SKILL.md |
|
||||
| Gemini CLI | SKILL.md |
|
||||
| Windsurf | Markdown |
|
||||
| GitHub Copilot | Markdown |
|
||||
| OpenCode, Antigravity, Amp, Goose, Kilo, Kiro, Roo, Trae | SKILL.md |
|
||||
| Universal | SKILL.md |
|
||||
|
||||
## API Reference
|
||||
|
||||
### Skill Types
|
||||
|
||||
```typescript
|
||||
interface CanonicalSkill {
|
||||
name: string;
|
||||
description?: string;
|
||||
version?: string;
|
||||
author?: string;
|
||||
tags?: string[];
|
||||
globs?: string[];
|
||||
alwaysApply?: boolean;
|
||||
content: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface TranslationResult {
|
||||
content: string;
|
||||
format: string;
|
||||
warnings?: string[];
|
||||
}
|
||||
```
|
||||
|
||||
### Context Types
|
||||
|
||||
```typescript
|
||||
interface ProjectProfile {
|
||||
name: string;
|
||||
type: 'web-app' | 'api' | 'cli' | 'library' | 'unknown';
|
||||
stack: {
|
||||
languages: Detection[];
|
||||
frameworks: Detection[];
|
||||
libraries: Detection[];
|
||||
testing: Detection[];
|
||||
databases: Detection[];
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Full documentation: https://github.com/rohitg00/skillkit
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"name": "@skillkit/core",
|
||||
"version": "1.6.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": {
|
||||
"@types/minimatch": "^6.0.0",
|
||||
"minimatch": "^10.1.1",
|
||||
"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"
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { AIManager } from '../manager.js';
|
||||
import type { SearchableSkill, SkillExample } from '../types.js';
|
||||
|
||||
describe('AIManager', () => {
|
||||
let manager: AIManager;
|
||||
let testSkills: SearchableSkill[];
|
||||
|
||||
beforeEach(() => {
|
||||
manager = new AIManager({
|
||||
provider: 'mock',
|
||||
});
|
||||
|
||||
testSkills = [
|
||||
{
|
||||
name: 'test-driven-development',
|
||||
description: 'Write tests before code using TDD methodology',
|
||||
content: 'TDD skill content',
|
||||
tags: ['testing', 'tdd', 'quality'],
|
||||
source: 'test-repo',
|
||||
},
|
||||
{
|
||||
name: 'code-review',
|
||||
description: 'Perform thorough code reviews',
|
||||
content: 'Code review skill content',
|
||||
tags: ['review', 'quality', 'collaboration'],
|
||||
source: 'test-repo',
|
||||
},
|
||||
{
|
||||
name: 'debugging-guide',
|
||||
description: 'Systematic approach to debugging issues',
|
||||
content: 'Debugging skill content',
|
||||
tags: ['debugging', 'troubleshooting'],
|
||||
source: 'test-repo',
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
describe('searchSkills', () => {
|
||||
it('should search skills by query', async () => {
|
||||
const results = await manager.searchSkills('testing', testSkills, {
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
expect(results[0].skill.name).toBe('test-driven-development');
|
||||
expect(results[0].relevance).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should respect limit option', async () => {
|
||||
const results = await manager.searchSkills('code', testSkills, {
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
expect(results.length).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('should filter by min relevance', async () => {
|
||||
const results = await manager.searchSkills('testing', testSkills, {
|
||||
minRelevance: 0.8,
|
||||
});
|
||||
|
||||
for (const result of results) {
|
||||
expect(result.relevance).toBeGreaterThanOrEqual(0.8);
|
||||
}
|
||||
});
|
||||
|
||||
it('should include reasoning when requested', async () => {
|
||||
const results = await manager.searchSkills('testing', testSkills, {
|
||||
includeReasoning: true,
|
||||
});
|
||||
|
||||
if (results.length > 0) {
|
||||
expect(results[0].reasoning).toBeDefined();
|
||||
expect(results[0].reasoning.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('searchByIntent', () => {
|
||||
it('should search by user intent', async () => {
|
||||
const results = await manager.searchByIntent(
|
||||
'I want to improve my testing workflow',
|
||||
testSkills,
|
||||
{ minRelevance: 0 }
|
||||
);
|
||||
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
const names = results.map((r) => r.skill.name);
|
||||
expect(names).toContain('test-driven-development');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findSimilar', () => {
|
||||
it('should find similar skills', async () => {
|
||||
const targetSkill = testSkills[0];
|
||||
const results = await manager.findSimilar(targetSkill, testSkills, {
|
||||
minRelevance: 0,
|
||||
});
|
||||
|
||||
expect(results.length).toBeGreaterThan(0);
|
||||
results.forEach((r) => {
|
||||
expect(r.skill.name).not.toBe(targetSkill.name);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateSkill', () => {
|
||||
it('should generate skill from example', async () => {
|
||||
const example: SkillExample = {
|
||||
description: 'Help with API testing',
|
||||
context: 'REST APIs using Jest',
|
||||
};
|
||||
|
||||
const generated = await manager.generateSkill(example);
|
||||
|
||||
expect(generated.name).toBeDefined();
|
||||
expect(generated.name.length).toBeGreaterThan(0);
|
||||
expect(generated.description).toBe(example.description);
|
||||
expect(generated.content).toBeDefined();
|
||||
expect(generated.tags).toBeDefined();
|
||||
expect(generated.confidence).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should include target agent metadata', async () => {
|
||||
const example: SkillExample = {
|
||||
description: 'Test skill',
|
||||
};
|
||||
|
||||
const generated = await manager.generateSkill(example, {
|
||||
targetAgent: 'claude-code',
|
||||
});
|
||||
|
||||
expect(generated.content).toContain('agent: claude-code');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateFromCode', () => {
|
||||
it('should generate skill from code example', async () => {
|
||||
const code = `
|
||||
function add(a: number, b: number): number {
|
||||
return a + b;
|
||||
}
|
||||
`;
|
||||
const description = 'Simple addition function';
|
||||
|
||||
const generated = await manager.generateFromCode(code, description);
|
||||
|
||||
expect(generated.name).toBeDefined();
|
||||
expect(generated.description).toBe(description);
|
||||
expect(generated.content).toContain('Example');
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateFromTemplate', () => {
|
||||
it('should generate skill from template', async () => {
|
||||
const generated = await manager.generateFromTemplate(
|
||||
'api-testing',
|
||||
{ framework: 'Jest', type: 'REST' }
|
||||
);
|
||||
|
||||
expect(generated.name).toBeDefined();
|
||||
expect(generated.content).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateGenerated', () => {
|
||||
it('should validate valid generated skill', () => {
|
||||
const skill = {
|
||||
name: 'valid-skill-name',
|
||||
description: 'This is a valid description with enough length',
|
||||
content: 'This is valid content with enough length to pass validation checks',
|
||||
tags: ['test', 'valid'],
|
||||
confidence: 0.8,
|
||||
reasoning: 'Valid reasoning',
|
||||
};
|
||||
|
||||
const result = manager.validateGenerated(skill);
|
||||
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should reject skill with short name', () => {
|
||||
const skill = {
|
||||
name: 'ab',
|
||||
description: 'Valid description',
|
||||
content: 'Valid content with enough length',
|
||||
tags: [],
|
||||
confidence: 0.8,
|
||||
reasoning: '',
|
||||
};
|
||||
|
||||
const result = manager.validateGenerated(skill);
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain(
|
||||
'Skill name must be at least 3 characters'
|
||||
);
|
||||
});
|
||||
|
||||
it('should reject skill with low confidence', () => {
|
||||
const skill = {
|
||||
name: 'valid-name',
|
||||
description: 'Valid description',
|
||||
content: 'Valid content with enough length',
|
||||
tags: [],
|
||||
confidence: 0.4,
|
||||
reasoning: '',
|
||||
};
|
||||
|
||||
const result = manager.validateGenerated(skill);
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain(
|
||||
'Skill confidence is too low (< 0.6)'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getProviderName', () => {
|
||||
it('should return provider name', () => {
|
||||
const name = manager.getProviderName();
|
||||
expect(name).toBe('mock');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateConfig', () => {
|
||||
it('should update configuration', () => {
|
||||
manager.updateConfig({
|
||||
temperature: 0.5,
|
||||
});
|
||||
|
||||
// Provider should be recreated
|
||||
expect(manager.getProviderName()).toBe('mock');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import type {
|
||||
AIProvider,
|
||||
AIGenerateOptions,
|
||||
GeneratedSkill,
|
||||
SkillExample,
|
||||
} from './types.js';
|
||||
|
||||
export class AISkillGenerator {
|
||||
constructor(private provider: AIProvider) {}
|
||||
|
||||
async generate(
|
||||
example: SkillExample,
|
||||
options: AIGenerateOptions = {}
|
||||
): Promise<GeneratedSkill> {
|
||||
const skill = await this.provider.generateSkill(example);
|
||||
|
||||
if (options.targetAgent && skill.content) {
|
||||
skill.content = this.addAgentMetadata(skill.content, options.targetAgent);
|
||||
}
|
||||
|
||||
return skill;
|
||||
}
|
||||
|
||||
async generateFromCode(
|
||||
code: string,
|
||||
description: string,
|
||||
options: AIGenerateOptions = {}
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generate(
|
||||
{
|
||||
description,
|
||||
codeExamples: [code],
|
||||
},
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
async generateFromTemplate(
|
||||
templateName: string,
|
||||
variables: Record<string, string>,
|
||||
options: AIGenerateOptions = {}
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generate(
|
||||
{
|
||||
description: `Create a skill based on the ${templateName} template with the following customization: ${JSON.stringify(variables)}`,
|
||||
context: `Template: ${templateName}`,
|
||||
},
|
||||
options
|
||||
);
|
||||
}
|
||||
|
||||
private addAgentMetadata(content: string, agent: string): string {
|
||||
const metadata = `---
|
||||
agent: ${agent}
|
||||
generated: ${new Date().toISOString()}
|
||||
---
|
||||
|
||||
${content}`;
|
||||
return metadata;
|
||||
}
|
||||
|
||||
validateGenerated(skill: GeneratedSkill): {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
} {
|
||||
const errors: string[] = [];
|
||||
|
||||
if (!skill.name || skill.name.length < 3) {
|
||||
errors.push('Skill name must be at least 3 characters');
|
||||
}
|
||||
|
||||
if (!skill.description || skill.description.length < 10) {
|
||||
errors.push('Skill description must be at least 10 characters');
|
||||
}
|
||||
|
||||
if (!skill.content || skill.content.length < 50) {
|
||||
errors.push('Skill content must be at least 50 characters');
|
||||
}
|
||||
|
||||
if (skill.confidence < 0.6) {
|
||||
errors.push('Skill confidence is too low (< 0.6)');
|
||||
}
|
||||
|
||||
return {
|
||||
valid: errors.length === 0,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './types.js';
|
||||
export * from './search.js';
|
||||
export * from './generator.js';
|
||||
export * from './manager.js';
|
||||
export * from './providers/index.js';
|
||||
@@ -0,0 +1,104 @@
|
||||
import type {
|
||||
AIConfig,
|
||||
AIProvider,
|
||||
AISearchOptions,
|
||||
AISearchResult,
|
||||
AIGenerateOptions,
|
||||
GeneratedSkill,
|
||||
SearchableSkill,
|
||||
SkillExample,
|
||||
} from './types.js';
|
||||
import { AISearch } from './search.js';
|
||||
import { AISkillGenerator } from './generator.js';
|
||||
import { MockAIProvider } from './providers/mock.js';
|
||||
|
||||
export class AIManager {
|
||||
private provider: AIProvider;
|
||||
private search: AISearch;
|
||||
private generator: AISkillGenerator;
|
||||
|
||||
constructor(private config: AIConfig) {
|
||||
this.provider = this.createProvider();
|
||||
this.search = new AISearch(this.provider);
|
||||
this.generator = new AISkillGenerator(this.provider);
|
||||
}
|
||||
|
||||
async searchSkills(
|
||||
query: string,
|
||||
skills: SearchableSkill[],
|
||||
options?: AISearchOptions
|
||||
): Promise<AISearchResult[]> {
|
||||
return this.search.search(query, skills, options);
|
||||
}
|
||||
|
||||
async searchByIntent(
|
||||
intent: string,
|
||||
skills: SearchableSkill[],
|
||||
options?: AISearchOptions
|
||||
): Promise<AISearchResult[]> {
|
||||
return this.search.searchByIntent(intent, skills, options);
|
||||
}
|
||||
|
||||
async findSimilar(
|
||||
skill: SearchableSkill,
|
||||
allSkills: SearchableSkill[],
|
||||
options?: AISearchOptions
|
||||
): Promise<AISearchResult[]> {
|
||||
return this.search.findSimilar(skill, allSkills, options);
|
||||
}
|
||||
|
||||
async generateSkill(
|
||||
example: SkillExample,
|
||||
options?: AIGenerateOptions
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generator.generate(example, options);
|
||||
}
|
||||
|
||||
async generateFromCode(
|
||||
code: string,
|
||||
description: string,
|
||||
options?: AIGenerateOptions
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generator.generateFromCode(code, description, options);
|
||||
}
|
||||
|
||||
async generateFromTemplate(
|
||||
templateName: string,
|
||||
variables: Record<string, string>,
|
||||
options?: AIGenerateOptions
|
||||
): Promise<GeneratedSkill> {
|
||||
return this.generator.generateFromTemplate(templateName, variables, options);
|
||||
}
|
||||
|
||||
validateGenerated(skill: GeneratedSkill): {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
} {
|
||||
return this.generator.validateGenerated(skill);
|
||||
}
|
||||
|
||||
private createProvider(): AIProvider {
|
||||
if (this.config.provider === 'none' || !this.config.apiKey) {
|
||||
return new MockAIProvider();
|
||||
}
|
||||
|
||||
switch (this.config.provider) {
|
||||
case 'anthropic':
|
||||
case 'openai':
|
||||
return new MockAIProvider();
|
||||
default:
|
||||
return new MockAIProvider();
|
||||
}
|
||||
}
|
||||
|
||||
getProviderName(): string {
|
||||
return this.provider.name;
|
||||
}
|
||||
|
||||
updateConfig(config: Partial<AIConfig>): void {
|
||||
this.config = { ...this.config, ...config };
|
||||
this.provider = this.createProvider();
|
||||
this.search = new AISearch(this.provider);
|
||||
this.generator = new AISkillGenerator(this.provider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import type {
|
||||
AIProvider,
|
||||
AISearchResult,
|
||||
GeneratedSkill,
|
||||
SearchableSkill,
|
||||
SkillExample,
|
||||
} from '../types.js';
|
||||
|
||||
export abstract class BaseAIProvider implements AIProvider {
|
||||
abstract name: string;
|
||||
|
||||
abstract search(
|
||||
query: string,
|
||||
skills: SearchableSkill[]
|
||||
): Promise<AISearchResult[]>;
|
||||
|
||||
abstract generateSkill(example: SkillExample): Promise<GeneratedSkill>;
|
||||
|
||||
protected buildSearchPrompt(query: string, skills: SearchableSkill[]): string {
|
||||
const skillsList = skills
|
||||
.map(
|
||||
(s, i) =>
|
||||
`${i + 1}. ${s.name}${s.description ? ` - ${s.description}` : ''}${s.tags ? ` [${s.tags.join(', ')}]` : ''}`
|
||||
)
|
||||
.join('\n');
|
||||
|
||||
return `You are a skill search assistant. Given a user query and a list of available skills, identify the most relevant skills.
|
||||
|
||||
User Query: "${query}"
|
||||
|
||||
Available Skills:
|
||||
${skillsList}
|
||||
|
||||
For each relevant skill (up to 10), provide:
|
||||
1. Skill index number
|
||||
2. Relevance score (0-1)
|
||||
3. Brief reasoning
|
||||
|
||||
Format your response as JSON:
|
||||
[
|
||||
{
|
||||
"index": <number>,
|
||||
"relevance": <0-1>,
|
||||
"reasoning": "<explanation>"
|
||||
}
|
||||
]`;
|
||||
}
|
||||
|
||||
protected buildGeneratePrompt(example: SkillExample): string {
|
||||
let prompt = `You are a skill generation assistant. Generate a complete skill based on the following specification:
|
||||
|
||||
Description: ${example.description}`;
|
||||
|
||||
if (example.context) {
|
||||
prompt += `\n\nContext: ${example.context}`;
|
||||
}
|
||||
|
||||
if (example.codeExamples && example.codeExamples.length > 0) {
|
||||
prompt += `\n\nCode Examples:\n${example.codeExamples.map((code, i) => `Example ${i + 1}:\n\`\`\`\n${code}\n\`\`\``).join('\n\n')}`;
|
||||
}
|
||||
|
||||
if (example.expectedBehavior) {
|
||||
prompt += `\n\nExpected Behavior: ${example.expectedBehavior}`;
|
||||
}
|
||||
|
||||
prompt += `
|
||||
|
||||
Generate a skill in SKILL.md format with:
|
||||
1. Clear name (kebab-case)
|
||||
2. Comprehensive description
|
||||
3. Detailed instructions
|
||||
4. Relevant tags
|
||||
5. Usage examples if applicable
|
||||
|
||||
Format your response as JSON:
|
||||
{
|
||||
"name": "<skill-name>",
|
||||
"description": "<description>",
|
||||
"content": "<full SKILL.md content>",
|
||||
"tags": ["<tag1>", "<tag2>"],
|
||||
"confidence": <0-1>,
|
||||
"reasoning": "<why this skill design>"
|
||||
}`;
|
||||
|
||||
return prompt;
|
||||
}
|
||||
|
||||
protected parseSearchResponse(
|
||||
response: string,
|
||||
skills: SearchableSkill[]
|
||||
): AISearchResult[] {
|
||||
try {
|
||||
const parsed = JSON.parse(response);
|
||||
return parsed.map((item: any) => ({
|
||||
skill: skills[item.index - 1],
|
||||
relevance: item.relevance,
|
||||
reasoning: item.reasoning,
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
protected parseGenerateResponse(response: string): GeneratedSkill {
|
||||
try {
|
||||
const parsed = JSON.parse(response);
|
||||
return {
|
||||
name: parsed.name,
|
||||
description: parsed.description,
|
||||
content: parsed.content,
|
||||
tags: parsed.tags || [],
|
||||
confidence: parsed.confidence || 0.7,
|
||||
reasoning: parsed.reasoning || '',
|
||||
};
|
||||
} catch {
|
||||
throw new Error('Failed to parse skill generation response');
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user