Compare commits

...
Author SHA1 Message Date
Rohit Ghumare 553a918b69 fix: handle more relative path patterns in loadPlugin
- Use isAbsolute() for cross-platform absolute path detection
- Add check for paths containing '/' (excluding @scope packages)
- Simplify pattern to source.startsWith('.') for all dot-prefixed paths
- Now correctly handles: plugins/x.js, ../foo, ./bar, .hidden
2026-01-23 22:31:26 +00:00
Rohit Ghumare 380188cef1 fix: allow scoped npm names in isValidPluginName
Update isValidPluginName to allow scoped npm package names like @scope/name
while still preventing path traversal attacks. Uses the same regex pattern
as loader.ts validatePlugin for consistency.

Valid names: my-plugin, @scope/plugin-name
Invalid names: ../evil, .hidden, name\\path, @../evil/name
2026-01-23 22:27:37 +00:00
Rohit Ghumare dcf12f6826 fix: address PR review issues - round 5
CRITICAL fixes:
- plugin.ts: Add path traversal protection in uninstallPlugin with name validation
  and resolved path checks
- bundle.ts: Fix parseSkillContent to not drop first file when content starts
  with "--- file ---" header

MAJOR fixes:
- plugin.ts: Add isValidPluginName() helper and validate plugin.metadata.name
  before using in file paths
- plugin.ts: Preserve .mjs extension for single-file ESM plugins
- bundle.ts: Use cross-platform path containment checks with relative() and sep
  instead of hardcoded '/'
- loader.ts: Add support for .mjs files (index.mjs, plugin.mjs)

MINOR fixes:
- plugin.ts: Expand tilde (~) path BEFORE calling loadPlugin
- settings.ts: Use null instead of undefined in JSON output for --get so key
  is preserved
2026-01-23 22:21:03 +00:00
Rohit Ghumare 50e8a389de fix: address PR review issues - round 4
CRITICAL fixes:
- loader.ts: Wrap statSync in try/catch in loadPluginsFromDirectory to handle
  permission denied and broken symlinks
- bundle.ts: Block path traversal attacks via skill names in importBundle by
  validating skill names don't contain / \ or start with .

MAJOR fixes:
- bundle.ts: Use dirname() instead of join('..') for output directory calculation

MINOR fixes:
- plugin.ts: Expand tilde paths (~) before existsSync for proper file operations
- settings.ts: Show defaultTimeout and marketplaceSources in default output
- bundle.ts: Prevent duplicate skill names in bundle with early error
- bundle.ts: Handle single-file skills properly in detectAgents
2026-01-23 22:03:38 +00:00
Rohit Ghumare be06956fd4 fix: address PR review feedback (round 3)
- plugin.ts: Add '../' and '~' to isLocalPath detection, use
  loader-recognized names (index.js, plugin.json) for single-file copy
- plugin.ts: Remove unused 'basename' import
- settings.ts: Change defaultTimeout validation from < 0 to <= 0
- settings.ts: Use knownKeys whitelist for unknown key detection
- loader.ts: Wrap statSync in try/catch for scanDirectory
- loader.ts: Validate required fields (name, version) before pushing
- loader.ts: Update regex to allow scoped npm names (@scope/name)
- bundle.ts: Resolve targetDir to absolute path for path containment
- Plugins.tsx: Only ignore ENOENT errors, rethrow others
- Plugins.tsx: Load plugins in togglePlugin before enable/disable
2026-01-23 21:48:24 +00:00
Rohit Ghumare 402d179c06 fix: address PR review feedback (round 2)
- Security: Add path traversal protection in bundle import
- Fix Plugins.tsx to load plugins from directory before listing
- Fix plugin.ts to persist plugin files to disk on install/uninstall
- Fix Settings.tsx auto-detect vs universal display inconsistency
- Add null check for registry in team/manager.ts sync()
- Thread TeamConfig.auth through provider clone calls
- Fix GitLab CI rules vs only conflict (use rules instead of only)
- Make loadConfig() accept global parameter for --global flag
- Fix relative path detection in plugins/loader.ts (../plugins)
2026-01-23 21:28:50 +00:00
Rohit Ghumare f3467dd5d3 fix: address PR review comments from CodeRabbit and Devin
Plugin command fixes:
- Fix double-nested .skillkit path when using --global flag

Settings command fixes:
- Add defaultTimeout to help text for available keys
- Wrap const timeout in block scope for switch case
- Fix --set flag validation to require equals sign

Core package fixes:
- Remove .ts from supported plugin extensions (runtime imports fail)
- Store skill name instead of full path in bundle manifest
- Use ESM import for execSync instead of require()
- Replace custom YAML parser with yaml library for proper nested structure handling

TUI screen fixes:
- Guard against empty plugins array in navigation
- Fix empty object pattern in Settings.tsx
- Surface config load failures in Settings screen
- Add manager.load() before sync/import in Team screen
- Guard against empty skills array in Team navigation
- Clamp selection index after skills update

CI/CD command fixes:
- Properly handle skipped workflows (not reported as success)
- Show different final message when nothing was created
- Wrap readFileSync in try/catch for GitLab CI
2026-01-23 20:55:48 +00:00
Rohit Ghumare 08ab52971e fix: address PR review comments from Devin
- Fix skill-executor.ts: handle undefined agentToUse when strategy is 'cli'
  Previously, if strategy was 'cli' but no CLI agent was available, the
  code would fall through and call executeWithAgent with undefined agent,
  causing a runtime error.

- Fix cicd.ts: prevent GitLab CI config overwrite without --force
  Previously, if .gitlab-ci.yml existed but didn't contain 'skillkit',
  it would be overwritten without checking --force. Now it properly
  returns early with a helpful message, consistent with CircleCI behavior.
2026-01-23 20:26:47 +00:00
Rohit Ghumare 56c7d02103 feat: add team collaboration and plugin system
Team Collaboration (Phase 10):
- TeamManager for skill sharing with remote registries
- Skill bundles (create, export, import)
- Team CLI commands: init, share, import, list, sync, remove, bundle-*
- Team TUI screen with navigation key 'a'

Plugin System (Phase 11):
- PluginManager with lifecycle hooks
- Plugin loader (files, npm packages, directories)
- TranslatorPlugin for custom agent formats
- ProviderPlugin for custom skill sources
- CommandPlugin for custom CLI commands
- Plugin CLI commands: list, install, uninstall, enable, disable, info
- Plugins TUI screen with navigation key 'p'

Additional:
- CI/CD command for template generation
- Settings command improvements
- Updated CLAUDE.md with all 11 phases complete
- 359 tests passing
2026-01-23 20:17:59 +00:00
27 changed files with 4183 additions and 38 deletions
+8
View File
@@ -29,6 +29,10 @@ import {
TestCommand,
MarketplaceCommand,
MemoryCommand,
SettingsCommand,
CICDCommand,
TeamCommand,
PluginCommand,
} from '@skillkit/cli';
const __filename = fileURLToPath(import.meta.url);
@@ -71,5 +75,9 @@ 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.runExit(process.argv.slice(2));
+380
View File
@@ -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}` };
}
}
}
+4
View File
@@ -21,3 +21,7 @@ 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';
+342
View File
@@ -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;
}
}
+228
View File
@@ -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 };
}
}
+360
View File
@@ -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;
}
}
+51 -7
View File
@@ -7,6 +7,9 @@ import {
loadWorkflow,
validateWorkflow,
createWorkflowOrchestrator,
createSkillExecutor,
createSimulatedSkillExecutor,
type AgentType,
} from '@skillkit/core';
/**
@@ -63,6 +66,16 @@ export class WorkflowRunCommand extends Command {
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());
@@ -113,14 +126,45 @@ export class WorkflowRunCommand extends Command {
const spinner = ora();
let currentWave = -1;
// Create orchestrator with mock executor (for now)
// 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(
async (_skillName, _config) => {
// TODO: Integrate with actual skill execution
// For now, simulate execution
await new Promise((resolve) => setTimeout(resolve, 500));
return { success: true };
},
skillExecutor,
(event) => {
if (this.json) return;
+23 -1
View File
@@ -15,10 +15,32 @@ export function getGlobalConfigPath(): string {
return join(homedir(), '.config', 'skillkit', CONFIG_FILE);
}
export function loadConfig(): SkillkitConfig {
export function loadConfig(global = false): SkillkitConfig {
const projectPath = getProjectConfigPath();
const globalPath = getGlobalConfigPath();
// If global is explicitly requested, only load from global path
if (global) {
if (existsSync(globalPath)) {
try {
const content = readFileSync(globalPath, 'utf-8');
const data = parseYaml(content);
const parsed = SkillkitConfig.safeParse(data);
if (parsed.success) {
return parsed.data;
}
} catch {
// Ignore parse errors
}
}
return {
version: 1,
agent: 'universal',
autoSync: true,
};
}
// Default behavior: project config takes precedence over global
if (existsSync(projectPath)) {
try {
const content = readFileSync(projectPath, 'utf-8');
+8
View File
@@ -24,3 +24,11 @@ export {
type AgentExecutionResult,
type ExecutionStrategy,
} from './agents.js';
// Skill Executor for Workflows
export {
createSkillExecutor,
createSimulatedSkillExecutor,
type SkillExecutorOptions,
type SkillExecutionEvent,
} from './skill-executor.js';
@@ -0,0 +1,251 @@
/**
* Skill Executor for Workflows
*
* Provides a real skill executor that finds skills by name
* and executes them using available agent CLIs.
*/
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { findSkill, readSkillContent, SKILL_DISCOVERY_PATHS } from '../skills.js';
import type { AgentType } from '../types.js';
import {
executeWithAgent,
getAvailableCLIAgents,
formatSkillAsPrompt,
getExecutionStrategy,
getManualExecutionInstructions,
} from './agents.js';
import type { SkillExecutor } from '../workflow/orchestrator.js';
/**
* Options for creating a skill executor
*/
export interface SkillExecutorOptions {
/** Project path to search for skills */
projectPath?: string;
/** Preferred agent to use for execution */
preferredAgent?: AgentType;
/** Timeout for skill execution (ms) */
timeout?: number;
/** Whether to fall back to other agents if preferred is unavailable */
fallbackToAvailable?: boolean;
/** Callback for execution events */
onExecutionEvent?: (event: SkillExecutionEvent) => void;
}
/**
* Skill execution event
*/
export interface SkillExecutionEvent {
type: 'skill_found' | 'skill_not_found' | 'agent_selected' | 'execution_start' | 'execution_complete';
skillName: string;
agent?: AgentType;
message?: string;
success?: boolean;
error?: string;
}
/**
* Get search directories for skills
*/
function getSearchDirs(projectPath: string): string[] {
const dirs: string[] = [];
// Project-local paths
for (const searchPath of SKILL_DISCOVERY_PATHS) {
const fullPath = join(projectPath, searchPath);
if (existsSync(fullPath)) {
dirs.push(fullPath);
}
}
// Global paths
const home = homedir();
const globalPaths = [
join(home, '.claude', 'skills'),
join(home, '.cursor', 'skills'),
join(home, '.codex', 'skills'),
join(home, '.skillkit', 'skills'),
];
for (const globalPath of globalPaths) {
if (existsSync(globalPath)) {
dirs.push(globalPath);
}
}
return dirs;
}
/**
* Create a skill executor for workflow orchestration
*
* This returns a function compatible with the WorkflowOrchestrator's SkillExecutor type.
*/
export function createSkillExecutor(options: SkillExecutorOptions = {}): SkillExecutor {
const {
projectPath = process.cwd(),
preferredAgent,
timeout = 300000, // 5 minutes
fallbackToAvailable = true,
onExecutionEvent,
} = options;
return async (skillName: string, config?: Record<string, unknown>): Promise<{ success: boolean; error?: string }> => {
// Find the skill
const searchDirs = getSearchDirs(projectPath);
const skill = findSkill(skillName, searchDirs);
if (!skill) {
onExecutionEvent?.({
type: 'skill_not_found',
skillName,
message: `Skill "${skillName}" not found in any search directory`,
});
return {
success: false,
error: `Skill "${skillName}" not found. Search paths: ${searchDirs.join(', ')}`,
};
}
onExecutionEvent?.({
type: 'skill_found',
skillName,
message: `Found skill at: ${skill.path}`,
});
// Read skill content
const content = readSkillContent(skill.path);
if (!content) {
return {
success: false,
error: `Could not read skill content from: ${skill.path}`,
};
}
// Determine which agent to use
let agentToUse: AgentType | undefined = preferredAgent;
if (!agentToUse || fallbackToAvailable) {
const availableAgents = await getAvailableCLIAgents();
if (preferredAgent && availableAgents.includes(preferredAgent)) {
agentToUse = preferredAgent;
} else if (availableAgents.length > 0) {
// Prefer claude-code if available, otherwise use first available
agentToUse = availableAgents.includes('claude-code') ? 'claude-code' : availableAgents[0];
}
}
// If no CLI agent available, provide manual instructions or error
if (!agentToUse) {
const strategy = getExecutionStrategy(preferredAgent || 'universal');
const instructions = getManualExecutionInstructions(preferredAgent || 'universal', skill.path);
if (strategy === 'ide' || strategy === 'manual') {
onExecutionEvent?.({
type: 'execution_complete',
skillName,
success: false,
message: 'No CLI agent available',
error: `No CLI agent available for execution.\n${instructions}`,
});
return {
success: false,
error: `No CLI agent available for automated execution. ${instructions}`,
};
}
// strategy is 'cli' but the preferred agent's CLI is not installed
const errorMsg = preferredAgent
? `The preferred agent "${preferredAgent}" supports CLI execution but its CLI is not installed.`
: 'No CLI agent is available for execution.';
onExecutionEvent?.({
type: 'execution_complete',
skillName,
success: false,
message: 'CLI not installed',
error: `${errorMsg}\n${instructions}`,
});
return {
success: false,
error: `${errorMsg} ${instructions}`,
};
}
onExecutionEvent?.({
type: 'agent_selected',
skillName,
agent: agentToUse,
message: `Using agent: ${agentToUse}`,
});
// Format the prompt with skill content and any config
let taskDescription: string | undefined;
if (config?.task) {
taskDescription = String(config.task);
}
const prompt = formatSkillAsPrompt(skillName, content, taskDescription);
onExecutionEvent?.({
type: 'execution_start',
skillName,
agent: agentToUse,
message: `Starting execution with ${agentToUse}`,
});
// Execute with the agent
const result = await executeWithAgent(agentToUse!, prompt, {
cwd: projectPath,
timeout,
});
onExecutionEvent?.({
type: 'execution_complete',
skillName,
agent: agentToUse,
success: result.success,
error: result.error,
message: result.success ? 'Execution completed successfully' : `Execution failed: ${result.error}`,
});
return {
success: result.success,
error: result.error,
};
};
}
/**
* Create a simulated skill executor for testing/dry-run
*
* This executor doesn't actually run skills but simulates execution.
*/
export function createSimulatedSkillExecutor(options: {
delay?: number;
shouldFail?: (skillName: string) => boolean;
onExecute?: (skillName: string) => void;
} = {}): SkillExecutor {
const { delay = 100, shouldFail, onExecute } = options;
return async (skillName: string, _config?: Record<string, unknown>): Promise<{ success: boolean; error?: string }> => {
onExecute?.(skillName);
// Simulate execution time
await new Promise((resolve) => setTimeout(resolve, delay));
const failed = shouldFail?.(skillName) ?? false;
return {
success: !failed,
error: failed ? `Simulated failure for skill: ${skillName}` : undefined,
};
};
}
+6
View File
@@ -39,3 +39,9 @@ export * from './cicd/index.js';
// Memory System (Cross-Agent Session Memory)
export * from './memory/index.js';
// Team Collaboration (Skill Sharing)
export * from './team/index.js';
// Plugin System (Extensibility)
export * from './plugins/index.js';
+22
View File
@@ -0,0 +1,22 @@
/**
* Plugin System
*
* Enables extensibility through:
* - Custom translators for new agent formats
* - Custom providers for new skill sources
* - Custom commands for CLI extensions
* - Hooks for skill lifecycle events
*/
export { PluginManager, createPluginManager } from './manager.js';
export { PluginLoader, loadPlugin, loadPluginsFromDirectory } from './loader.js';
export type {
Plugin,
PluginMetadata,
PluginHooks,
TranslatorPlugin,
ProviderPlugin,
CommandPlugin,
PluginContext,
PluginConfig,
} from './types.js';
+332
View File
@@ -0,0 +1,332 @@
/**
* Plugin Loader
*
* Loads plugins from various sources:
* - Local files
* - npm packages
* - Git repositories
*/
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { join, extname, basename, isAbsolute } from 'node:path';
import { pathToFileURL } from 'node:url';
import type { Plugin, PluginMetadata } from './types.js';
/**
* Plugin Loader class
*/
export class PluginLoader {
/**
* Load a plugin from a file path
*/
async loadFromFile(filePath: string): Promise<Plugin> {
if (!existsSync(filePath)) {
throw new Error(`Plugin file not found: ${filePath}`);
}
const ext = extname(filePath);
if (ext !== '.js' && ext !== '.mjs') {
throw new Error(`Unsupported plugin file type: ${ext}. Only .js and .mjs files are supported.`);
}
try {
// Use dynamic import for ES modules
const fileUrl = pathToFileURL(filePath).href;
const module = await import(fileUrl);
// Plugin can be default export or named export
const plugin = module.default || module.plugin;
if (!plugin || !plugin.metadata) {
throw new Error('Invalid plugin: missing metadata');
}
return this.validatePlugin(plugin);
} catch (err) {
throw new Error(
`Failed to load plugin from ${filePath}: ${
err instanceof Error ? err.message : 'Unknown error'
}`
);
}
}
/**
* Load a plugin from an npm package
*/
async loadFromPackage(packageName: string): Promise<Plugin> {
try {
// Try to resolve the package
const module = await import(packageName);
const plugin = module.default || module.plugin;
if (!plugin || !plugin.metadata) {
throw new Error('Invalid plugin: missing metadata');
}
return this.validatePlugin(plugin);
} catch (err) {
throw new Error(
`Failed to load plugin from package ${packageName}: ${
err instanceof Error ? err.message : 'Unknown error'
}`
);
}
}
/**
* Load a plugin from a JSON definition (for simple plugins)
*/
loadFromJson(jsonPath: string): Plugin {
if (!existsSync(jsonPath)) {
throw new Error(`Plugin JSON not found: ${jsonPath}`);
}
try {
const content = readFileSync(jsonPath, 'utf-8');
const data = JSON.parse(content);
if (!data.metadata) {
throw new Error('Invalid plugin JSON: missing metadata');
}
// JSON plugins can only define metadata, hooks need code
const plugin: Plugin = {
metadata: data.metadata,
};
return this.validatePlugin(plugin);
} catch (err) {
throw new Error(
`Failed to load plugin from ${jsonPath}: ${
err instanceof Error ? err.message : 'Unknown error'
}`
);
}
}
/**
* Scan a directory for plugins
*/
async scanDirectory(dirPath: string): Promise<PluginMetadata[]> {
if (!existsSync(dirPath)) {
return [];
}
const plugins: PluginMetadata[] = [];
const entries = readdirSync(dirPath);
for (const entry of entries) {
const fullPath = join(dirPath, entry);
// Guard against unreadable entries (permission denied, broken symlinks)
let stat;
try {
stat = statSync(fullPath);
} catch {
// Skip unreadable entries
continue;
}
if (stat.isDirectory()) {
// Check for package.json or plugin.json
const pkgPath = join(fullPath, 'package.json');
const pluginPath = join(fullPath, 'plugin.json');
if (existsSync(pkgPath)) {
try {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
// Validate required fields before pushing
if ((pkg.skillkitPlugin || pkg.keywords?.includes('skillkit-plugin')) &&
pkg.name && typeof pkg.name === 'string' &&
pkg.version && typeof pkg.version === 'string') {
plugins.push({
name: pkg.name,
version: pkg.version,
description: pkg.description,
author: pkg.author,
homepage: pkg.homepage,
});
}
} catch {
// Skip invalid packages
}
} else if (existsSync(pluginPath)) {
try {
const data = JSON.parse(readFileSync(pluginPath, 'utf-8'));
// Validate metadata has required fields
if (data.metadata &&
data.metadata.name && typeof data.metadata.name === 'string' &&
data.metadata.version && typeof data.metadata.version === 'string') {
plugins.push(data.metadata);
}
} catch {
// Skip invalid plugins
}
}
} else if (stat.isFile()) {
// Check for plugin files
const ext = extname(entry);
if (ext === '.js' || ext === '.mjs') {
const name = basename(entry, ext);
if (name.includes('plugin') || name.startsWith('skillkit-')) {
plugins.push({
name,
version: '0.0.0', // Unknown until loaded
description: `Plugin file: ${entry}`,
});
}
}
}
}
return plugins;
}
/**
* Validate a plugin structure
*/
private validatePlugin(plugin: Plugin): Plugin {
const { metadata } = plugin;
// Validate required metadata
if (!metadata.name) {
throw new Error('Plugin metadata must include a name');
}
if (!metadata.version) {
throw new Error('Plugin metadata must include a version');
}
// Validate name format (allow scoped npm names like @scope/name)
if (!/^(?:@[a-z0-9-]+\/)?[a-z0-9-]+$/.test(metadata.name)) {
throw new Error(
'Plugin name must be lowercase alphanumeric with hyphens only (scoped names like @scope/name are allowed)'
);
}
// Validate version format (loose semver check)
if (!/^\d+\.\d+\.\d+/.test(metadata.version)) {
throw new Error('Plugin version must be semver format (e.g., 1.0.0)');
}
// Validate translators
if (plugin.translators) {
for (const t of plugin.translators) {
if (!t.agentType || !t.translator) {
throw new Error('Translator plugin must include agentType and translator');
}
}
}
// Validate providers
if (plugin.providers) {
for (const p of plugin.providers) {
if (!p.providerName || !p.provider) {
throw new Error('Provider plugin must include providerName and provider');
}
}
}
// Validate commands
if (plugin.commands) {
for (const c of plugin.commands) {
if (!c.name || !c.handler) {
throw new Error('Command plugin must include name and handler');
}
}
}
return plugin;
}
}
/**
* Load a plugin from a file
*/
export async function loadPlugin(source: string): Promise<Plugin> {
const loader = new PluginLoader();
// Determine source type
// Check for local file paths: absolute, relative (./, .., paths with /), Windows paths, or tilde
const isLocalPath =
source.startsWith('.') || // ./, ../, .hidden
isAbsolute(source) || // /abs/path or C:\path
(source.includes('/') && !source.startsWith('@')) || // plugins/x.js (but not @scope/pkg)
source.includes('\\') || // Windows backslash
source.startsWith('~'); // ~/path
if (isLocalPath) {
// File path
if (source.endsWith('.json')) {
return loader.loadFromJson(source);
}
return loader.loadFromFile(source);
} else if (source.startsWith('@') || /^[a-z0-9-]+$/.test(source)) {
// npm package
return loader.loadFromPackage(source);
} else {
throw new Error(`Cannot determine plugin source type: ${source}`);
}
}
/**
* Load all plugins from a directory
*/
export async function loadPluginsFromDirectory(dirPath: string): Promise<Plugin[]> {
const loader = new PluginLoader();
const plugins: Plugin[] = [];
if (!existsSync(dirPath)) {
return plugins;
}
const entries = readdirSync(dirPath);
for (const entry of entries) {
const fullPath = join(dirPath, entry);
// Guard against unreadable entries (permission denied, broken symlinks)
let stat;
try {
stat = statSync(fullPath);
} catch {
// Skip unreadable entries
continue;
}
try {
if (stat.isDirectory()) {
// Try to load from directory (check ESM .mjs files first, then .js)
const indexMjsPath = join(fullPath, 'index.mjs');
const indexPath = join(fullPath, 'index.js');
const mainMjsPath = join(fullPath, 'plugin.mjs');
const mainPath = join(fullPath, 'plugin.js');
const jsonPath = join(fullPath, 'plugin.json');
if (existsSync(indexMjsPath)) {
plugins.push(await loader.loadFromFile(indexMjsPath));
} else if (existsSync(indexPath)) {
plugins.push(await loader.loadFromFile(indexPath));
} else if (existsSync(mainMjsPath)) {
plugins.push(await loader.loadFromFile(mainMjsPath));
} else if (existsSync(mainPath)) {
plugins.push(await loader.loadFromFile(mainPath));
} else if (existsSync(jsonPath)) {
plugins.push(loader.loadFromJson(jsonPath));
}
} else if (stat.isFile()) {
const ext = extname(entry);
if (ext === '.js' || ext === '.mjs') {
plugins.push(await loader.loadFromFile(fullPath));
} else if (ext === '.json' && entry.includes('plugin')) {
plugins.push(loader.loadFromJson(fullPath));
}
}
} catch (err) {
// Log but continue loading other plugins
console.warn(`Failed to load plugin from ${fullPath}: ${err}`);
}
}
return plugins;
}
+385
View File
@@ -0,0 +1,385 @@
/**
* Plugin Manager
*
* Manages plugin registration, lifecycle, and execution
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import type {
Plugin,
PluginMetadata,
PluginHooks,
PluginContext,
PluginConfig,
CommandPlugin,
} from './types.js';
import type { AgentType } from '../types.js';
import type { CanonicalSkill, FormatTranslator } from '../translator/types.js';
import type { GitProviderAdapter } from '../providers/base.js';
const PLUGINS_DIR = '.skillkit/plugins';
const PLUGINS_CONFIG_FILE = 'plugins.json';
interface PluginsState {
version: number;
plugins: Record<string, {
enabled: boolean;
config: PluginConfig;
loadedAt?: string;
}>;
}
/**
* Plugin Manager class
*/
export class PluginManager {
private projectPath: string;
private plugins: Map<string, Plugin> = new Map();
private translators: Map<string, FormatTranslator> = new Map();
private providers: Map<string, GitProviderAdapter> = new Map();
private commands: Map<string, CommandPlugin> = new Map();
private hooks: Map<string, PluginHooks> = new Map();
private state: PluginsState;
private context: PluginContext;
constructor(projectPath: string) {
this.projectPath = projectPath;
this.state = this.loadState();
this.context = this.createContext();
}
/**
* Register a plugin
*/
async register(plugin: Plugin): Promise<void> {
const name = plugin.metadata.name;
// Check if already registered
if (this.plugins.has(name)) {
throw new Error(`Plugin "${name}" is already registered`);
}
// Check dependencies
if (plugin.metadata.dependencies) {
for (const dep of plugin.metadata.dependencies) {
if (!this.plugins.has(dep)) {
throw new Error(`Plugin "${name}" requires "${dep}" which is not loaded`);
}
}
}
// Initialize plugin
if (plugin.init) {
await plugin.init(this.context);
}
// Register translators
if (plugin.translators) {
for (const t of plugin.translators) {
this.translators.set(t.agentType, t.translator);
}
}
// Register providers
if (plugin.providers) {
for (const p of plugin.providers) {
this.providers.set(p.providerName, p.provider);
}
}
// Register commands
if (plugin.commands) {
for (const c of plugin.commands) {
this.commands.set(c.name, c);
if (c.aliases) {
for (const alias of c.aliases) {
this.commands.set(alias, c);
}
}
}
}
// Register hooks
if (plugin.hooks) {
this.hooks.set(name, plugin.hooks);
// Call onLoad hook
if (plugin.hooks.onLoad) {
await plugin.hooks.onLoad(this.context);
}
}
// Store plugin
this.plugins.set(name, plugin);
// Update state
this.state.plugins[name] = {
enabled: true,
config: {},
loadedAt: new Date().toISOString(),
};
this.saveState();
}
/**
* Unregister a plugin
*/
async unregister(name: string): Promise<void> {
const plugin = this.plugins.get(name);
if (!plugin) {
throw new Error(`Plugin "${name}" is not registered`);
}
// Call onUnload hook
const hooks = this.hooks.get(name);
if (hooks?.onUnload) {
await hooks.onUnload();
}
// Cleanup
if (plugin.destroy) {
await plugin.destroy();
}
// Remove translators
if (plugin.translators) {
for (const t of plugin.translators) {
this.translators.delete(t.agentType);
}
}
// Remove providers
if (plugin.providers) {
for (const p of plugin.providers) {
this.providers.delete(p.providerName);
}
}
// Remove commands
if (plugin.commands) {
for (const c of plugin.commands) {
this.commands.delete(c.name);
if (c.aliases) {
for (const alias of c.aliases) {
this.commands.delete(alias);
}
}
}
}
// Remove hooks
this.hooks.delete(name);
// Remove plugin
this.plugins.delete(name);
// Update state
delete this.state.plugins[name];
this.saveState();
}
/**
* Get a registered plugin
*/
getPlugin(name: string): Plugin | undefined {
return this.plugins.get(name);
}
/**
* Get all registered plugins
*/
getAllPlugins(): Plugin[] {
return Array.from(this.plugins.values());
}
/**
* Get plugin metadata for all plugins
*/
listPlugins(): PluginMetadata[] {
return this.getAllPlugins().map((p) => p.metadata);
}
/**
* Get a translator by agent type
*/
getTranslator(agentType: AgentType | string): FormatTranslator | undefined {
return this.translators.get(agentType);
}
/**
* Get all registered translators
*/
getAllTranslators(): Map<string, FormatTranslator> {
return new Map(this.translators);
}
/**
* Get a provider by name
*/
getProvider(name: string): GitProviderAdapter | undefined {
return this.providers.get(name);
}
/**
* Get all registered providers
*/
getAllProviders(): Map<string, GitProviderAdapter> {
return new Map(this.providers);
}
/**
* Get a command by name
*/
getCommand(name: string): CommandPlugin | undefined {
return this.commands.get(name);
}
/**
* Get all registered commands
*/
getAllCommands(): CommandPlugin[] {
return Array.from(new Set(this.commands.values()));
}
/**
* Execute hooks for an event
*/
async executeHook<K extends keyof PluginHooks>(
hookName: K,
...args: Parameters<NonNullable<PluginHooks[K]>>
): Promise<void> {
for (const [, hooks] of this.hooks) {
const hook = hooks[hookName];
if (hook) {
await (hook as (...args: unknown[]) => Promise<void>)(...args);
}
}
}
/**
* Execute beforeTranslate hooks (returns transformed skill)
*/
async executeBeforeTranslate(
skill: CanonicalSkill,
targetAgent: AgentType
): Promise<CanonicalSkill> {
let result = skill;
for (const [, hooks] of this.hooks) {
if (hooks.beforeTranslate) {
result = await hooks.beforeTranslate(result, targetAgent);
}
}
return result;
}
/**
* Execute afterTranslate hooks (returns transformed content)
*/
async executeAfterTranslate(
content: string,
targetAgent: AgentType
): Promise<string> {
let result = content;
for (const [, hooks] of this.hooks) {
if (hooks.afterTranslate) {
result = await hooks.afterTranslate(result, targetAgent);
}
}
return result;
}
/**
* Set plugin configuration
*/
setPluginConfig(name: string, config: PluginConfig): void {
if (!this.state.plugins[name]) {
this.state.plugins[name] = { enabled: true, config };
} else {
this.state.plugins[name].config = config;
}
this.saveState();
}
/**
* Get plugin configuration
*/
getPluginConfig(name: string): PluginConfig | undefined {
return this.state.plugins[name]?.config;
}
/**
* Enable a plugin
*/
enablePlugin(name: string): void {
if (this.state.plugins[name]) {
this.state.plugins[name].enabled = true;
this.saveState();
}
}
/**
* Disable a plugin
*/
disablePlugin(name: string): void {
if (this.state.plugins[name]) {
this.state.plugins[name].enabled = false;
this.saveState();
}
}
/**
* Check if plugin is enabled
*/
isPluginEnabled(name: string): boolean {
return this.state.plugins[name]?.enabled ?? true;
}
// Private helpers
private loadState(): PluginsState {
const statePath = join(this.projectPath, PLUGINS_DIR, PLUGINS_CONFIG_FILE);
if (existsSync(statePath)) {
try {
return JSON.parse(readFileSync(statePath, 'utf-8'));
} catch {
// Return default state on error
}
}
return { version: 1, plugins: {} };
}
private saveState(): void {
const pluginsDir = join(this.projectPath, PLUGINS_DIR);
if (!existsSync(pluginsDir)) {
mkdirSync(pluginsDir, { recursive: true });
}
const statePath = join(pluginsDir, PLUGINS_CONFIG_FILE);
writeFileSync(statePath, JSON.stringify(this.state, null, 2), 'utf-8');
}
private createContext(): PluginContext {
return {
projectPath: this.projectPath,
skillkitVersion: '1.4.0',
config: {},
log: {
info: (msg) => console.log(`[plugin] ${msg}`),
warn: (msg) => console.warn(`[plugin] ${msg}`),
error: (msg) => console.error(`[plugin] ${msg}`),
debug: (msg) => {
if (process.env.DEBUG) console.log(`[plugin:debug] ${msg}`);
},
},
getTranslator: (agentType) => this.translators.get(agentType),
getProvider: (name) => this.providers.get(name),
};
}
}
/**
* Create a plugin manager instance
*/
export function createPluginManager(projectPath: string): PluginManager {
return new PluginManager(projectPath);
}
+147
View File
@@ -0,0 +1,147 @@
/**
* Plugin System Types
*/
import type { AgentType } from '../types.js';
import type { CanonicalSkill, FormatTranslator } from '../translator/types.js';
import type { GitProviderAdapter } from '../providers/base.js';
/**
* Plugin metadata
*/
export interface PluginMetadata {
/** Unique plugin identifier */
name: string;
/** Plugin version (semver) */
version: string;
/** Human-readable description */
description?: string;
/** Plugin author */
author?: string;
/** Plugin homepage or repository URL */
homepage?: string;
/** Required SkillKit version */
skillkitVersion?: string;
/** Plugin dependencies */
dependencies?: string[];
/** Plugin keywords for discovery */
keywords?: string[];
}
/**
* Plugin lifecycle hooks
*/
export interface PluginHooks {
/** Called when a skill is installed */
onSkillInstall?: (skill: CanonicalSkill, agent: AgentType) => Promise<void>;
/** Called when a skill is removed */
onSkillRemove?: (skillName: string, agent: AgentType) => Promise<void>;
/** Called when skills are synced */
onSync?: (agents: AgentType[]) => Promise<void>;
/** Called before translation */
beforeTranslate?: (skill: CanonicalSkill, targetAgent: AgentType) => Promise<CanonicalSkill>;
/** Called after translation */
afterTranslate?: (content: string, targetAgent: AgentType) => Promise<string>;
/** Called when plugin is loaded */
onLoad?: (context: PluginContext) => Promise<void>;
/** Called when plugin is unloaded */
onUnload?: () => Promise<void>;
}
/**
* Translator plugin - adds support for new agent formats
*/
export interface TranslatorPlugin {
type: 'translator';
/** Agent type this translator handles */
agentType: AgentType | string;
/** The translator implementation */
translator: FormatTranslator;
}
/**
* Provider plugin - adds support for new skill sources
*/
export interface ProviderPlugin {
type: 'provider';
/** Provider name (e.g., 'bitbucket', 's3') */
providerName: string;
/** The provider implementation */
provider: GitProviderAdapter;
}
/**
* Command plugin - adds new CLI commands
*/
export interface CommandPlugin {
type: 'command';
/** Command name */
name: string;
/** Command aliases */
aliases?: string[];
/** Command description */
description: string;
/** Command options */
options?: Array<{
name: string;
description: string;
type: 'string' | 'boolean' | 'number';
required?: boolean;
default?: unknown;
}>;
/** Command handler */
handler: (args: Record<string, unknown>, context: PluginContext) => Promise<number>;
}
/**
* Plugin context passed to plugins
*/
export interface PluginContext {
/** Project path */
projectPath: string;
/** SkillKit version */
skillkitVersion: string;
/** Plugin configuration */
config: PluginConfig;
/** Logger instance */
log: {
info: (message: string) => void;
warn: (message: string) => void;
error: (message: string) => void;
debug: (message: string) => void;
};
/** Get a registered translator by agent type */
getTranslator: (agentType: AgentType) => FormatTranslator | undefined;
/** Get a registered provider by name */
getProvider: (name: string) => GitProviderAdapter | undefined;
}
/**
* Plugin configuration
*/
export interface PluginConfig {
/** Plugin-specific settings */
settings?: Record<string, unknown>;
/** Whether plugin is enabled */
enabled?: boolean;
}
/**
* Main plugin interface
*/
export interface Plugin {
/** Plugin metadata */
metadata: PluginMetadata;
/** Plugin hooks */
hooks?: PluginHooks;
/** Translator extensions */
translators?: TranslatorPlugin[];
/** Provider extensions */
providers?: ProviderPlugin[];
/** Command extensions */
commands?: CommandPlugin[];
/** Plugin initialization */
init?: (context: PluginContext) => Promise<void>;
/** Plugin cleanup */
destroy?: () => Promise<void>;
}
+332
View File
@@ -0,0 +1,332 @@
/**
* Skill Bundle
*
* Package multiple skills into a shareable bundle
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'node:fs';
import { join, basename, resolve, relative, dirname, sep } from 'node:path';
import { createHash } from 'node:crypto';
import type { BundleManifest } from './types.js';
import type { AgentType } from '../types.js';
const BUNDLE_VERSION = 1;
/**
* Skill Bundle class for creating and managing skill bundles
*/
export class SkillBundle {
private manifest: BundleManifest;
private skills: Map<string, string> = new Map(); // skillName -> content
constructor(name: string, author: string, description?: string) {
this.manifest = {
version: BUNDLE_VERSION,
name,
description,
author,
createdAt: new Date().toISOString(),
skills: [],
totalSize: 0,
};
}
/**
* Add a skill to the bundle
*/
addSkill(skillPath: string, agents?: AgentType[]): void {
const skillName = basename(skillPath);
// Check for duplicate skill names
if (this.skills.has(skillName)) {
throw new Error(`Skill "${skillName}" already exists in bundle`);
}
const content = this.readSkillContent(skillPath);
this.skills.set(skillName, content);
this.manifest.skills.push({
name: skillName,
path: skillName, // Store only the skill name, not the full path
agents: agents || this.detectAgents(skillPath),
});
this.manifest.totalSize += Buffer.byteLength(content, 'utf-8');
}
/**
* Remove a skill from the bundle
*/
removeSkill(skillName: string): boolean {
const skill = this.manifest.skills.find((s) => s.name === skillName);
if (!skill) return false;
const content = this.skills.get(skillName);
if (content) {
this.manifest.totalSize -= Buffer.byteLength(content, 'utf-8');
}
this.skills.delete(skillName);
this.manifest.skills = this.manifest.skills.filter((s) => s.name !== skillName);
return true;
}
/**
* Get bundle manifest
*/
getManifest(): BundleManifest {
return { ...this.manifest };
}
/**
* Get all skill names in bundle
*/
getSkillNames(): string[] {
return this.manifest.skills.map((s) => s.name);
}
/**
* Get skill content by name
*/
getSkillContent(skillName: string): string | undefined {
return this.skills.get(skillName);
}
/**
* Calculate bundle checksum
*/
getChecksum(): string {
const contents: string[] = [];
for (const [name, content] of this.skills.entries()) {
contents.push(`${name}:${content}`);
}
contents.sort();
return createHash('sha256').update(contents.join('\n')).digest('hex').slice(0, 12);
}
private readSkillContent(skillPath: string): string {
const contents: string[] = [];
const readDir = (dir: string, prefix = ''): void => {
const entries = readdirSync(dir);
for (const entry of entries) {
const fullPath = join(dir, entry);
const relativePath = prefix ? `${prefix}/${entry}` : entry;
const stat = statSync(fullPath);
if (stat.isDirectory()) {
readDir(fullPath, relativePath);
} else if (stat.isFile()) {
const content = readFileSync(fullPath, 'utf-8');
contents.push(`--- ${relativePath} ---\n${content}`);
}
}
};
if (statSync(skillPath).isDirectory()) {
readDir(skillPath);
} else {
contents.push(readFileSync(skillPath, 'utf-8'));
}
return contents.join('\n\n');
}
private detectAgents(skillPath: string): AgentType[] {
const agents: AgentType[] = [];
// Handle single-file skills - check if skillPath is a file
if (existsSync(skillPath) && statSync(skillPath).isFile()) {
const fileName = basename(skillPath).toLowerCase();
if (fileName === 'skill.md') {
return ['claude-code', 'codex', 'gemini-cli', 'universal'];
}
if (fileName === 'skill.mdc') {
return ['cursor'];
}
if (fileName === 'rules.md') {
return ['windsurf'];
}
return ['universal'];
}
// Directory-based skill detection
if (existsSync(join(skillPath, 'SKILL.md'))) {
agents.push('claude-code', 'codex', 'gemini-cli', 'universal');
}
if (existsSync(join(skillPath, 'skill.mdc'))) {
agents.push('cursor');
}
if (existsSync(join(skillPath, 'rules.md'))) {
agents.push('windsurf');
}
return agents.length > 0 ? agents : ['universal'];
}
}
/**
* Create a new skill bundle
*/
export function createSkillBundle(
name: string,
author: string,
description?: string
): SkillBundle {
return new SkillBundle(name, author, description);
}
/**
* Export a bundle to a file
*/
export function exportBundle(
bundle: SkillBundle,
outputPath: string
): { success: boolean; path?: string; error?: string } {
try {
const manifest = bundle.getManifest();
const exportData = {
manifest,
skills: {} as Record<string, string>,
};
for (const skill of manifest.skills) {
const content = bundle.getSkillContent(skill.name);
if (content) {
exportData.skills[skill.name] = content;
}
}
const dir = dirname(outputPath);
if (dir && !existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
// Export as JSON (could be changed to tarball for better compression)
writeFileSync(outputPath, JSON.stringify(exportData, null, 2), 'utf-8');
return { success: true, path: outputPath };
} catch (err) {
return {
success: false,
error: err instanceof Error ? err.message : 'Unknown error',
};
}
}
/**
* Import a bundle from a file
*/
export function importBundle(
bundlePath: string,
targetDir: string,
options: { overwrite?: boolean } = {}
): { success: boolean; imported: string[]; errors: string[] } {
const imported: string[] = [];
const errors: string[] = [];
try {
const content = readFileSync(bundlePath, 'utf-8');
const data = JSON.parse(content) as {
manifest: BundleManifest;
skills: Record<string, string>;
};
// Resolve targetDir to absolute path for consistent path containment checks
const absoluteTargetDir = resolve(targetDir);
for (const skill of data.manifest.skills) {
// Validate skill name to prevent path traversal attacks
if (!skill.name || skill.name.includes('/') || skill.name.includes('\\') ||
skill.name === '..' || skill.name === '.' || skill.name.startsWith('.')) {
errors.push(`Skill has invalid name: ${skill.name}`);
continue;
}
const skillContent = data.skills[skill.name];
if (!skillContent) {
errors.push(`Skill "${skill.name}" has no content in bundle`);
continue;
}
const skillDir = join(absoluteTargetDir, skill.name);
// Double-check the resolved path is within target directory (cross-platform)
const resolvedSkillDir = resolve(skillDir);
const relativeToTarget = relative(absoluteTargetDir, resolvedSkillDir);
if (relativeToTarget.startsWith('..') || relativeToTarget.startsWith(sep)) {
errors.push(`Skill "${skill.name}" would escape target directory`);
continue;
}
// Check if exists
if (existsSync(skillDir) && !options.overwrite) {
errors.push(`Skill "${skill.name}" already exists (use --overwrite)`);
continue;
}
// Create skill directory
if (!existsSync(skillDir)) {
mkdirSync(skillDir, { recursive: true });
}
// Parse and write skill files
const files = parseSkillContent(skillContent);
for (const [filePath, fileContent] of Object.entries(files)) {
// Validate path to prevent path traversal attacks
const fullPath = resolve(skillDir, filePath);
const relativeToSkill = relative(skillDir, fullPath);
// Check for path traversal (cross-platform)
if (relativeToSkill.startsWith('..') || relativeToSkill.startsWith(sep)) {
errors.push(`Skill "${skill.name}" contains invalid file path: ${filePath}`);
continue;
}
const fileDir = dirname(fullPath);
if (!existsSync(fileDir)) {
mkdirSync(fileDir, { recursive: true });
}
writeFileSync(fullPath, fileContent, 'utf-8');
}
imported.push(skill.name);
}
return { success: errors.length === 0, imported, errors };
} catch (err) {
errors.push(err instanceof Error ? err.message : 'Unknown error');
return { success: false, imported, errors };
}
}
/**
* Parse skill content back into individual files
*/
function parseSkillContent(content: string): Record<string, string> {
const files: Record<string, string> = {};
// Match file headers at start of string OR after newline
// This ensures the first file isn't dropped when content starts with "--- file ---"
const sections = content.split(/(?:^|\n)--- ([^\n]+) ---\n/);
// sections[0] is content before first header (empty if content starts with header)
// Then alternating: filePath, fileContent, filePath, fileContent, ...
let i = 1;
while (i < sections.length) {
const filePath = sections[i];
const fileContent = sections[i + 1] || '';
if (filePath && !filePath.startsWith('---')) {
files[filePath.trim()] = fileContent;
}
i += 2;
}
// If no file markers found, assume it's a single SKILL.md
if (Object.keys(files).length === 0 && content.trim()) {
files['SKILL.md'] = content;
}
return files;
}
+20
View File
@@ -0,0 +1,20 @@
/**
* Team Collaboration Module
*
* Enables sharing skills across team members via:
* - Git repositories (shared skill repos)
* - Team skill registries
* - Import/export of skill bundles
*/
export { TeamManager, createTeamManager } from './manager.js';
export { SkillBundle, createSkillBundle, exportBundle, importBundle } from './bundle.js';
export type {
TeamConfig,
TeamMember,
SharedSkill,
TeamRegistry,
BundleManifest,
ShareOptions,
ImportOptions,
} from './types.js';
+447
View File
@@ -0,0 +1,447 @@
/**
* Team Manager
*
* Manages team skill sharing and collaboration
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { execSync } from 'node:child_process';
import { parse as yamlParse, stringify as yamlStringify } from 'yaml';
import type {
TeamConfig,
TeamRegistry,
SharedSkill,
ShareOptions,
ImportOptions,
} from './types.js';
import type { AgentType } from '../types.js';
import { detectProvider } from '../providers/index.js';
const TEAM_CONFIG_FILE = 'team.yaml';
const TEAM_DIR = '.skillkit/team';
/**
* Team Manager for collaboration features
*/
export class TeamManager {
private projectPath: string;
private config: TeamConfig | null = null;
private registry: TeamRegistry | null = null;
constructor(projectPath: string) {
this.projectPath = projectPath;
}
/**
* Initialize team configuration
*/
async init(config: Omit<TeamConfig, 'teamId'>): Promise<TeamConfig> {
const teamId = this.generateTeamId();
const fullConfig: TeamConfig = {
...config,
teamId,
};
// Create team directory
const teamDir = join(this.projectPath, TEAM_DIR);
if (!existsSync(teamDir)) {
mkdirSync(teamDir, { recursive: true });
}
// Save config
this.saveConfig(fullConfig);
this.config = fullConfig;
// Initialize empty registry
const registry: TeamRegistry = {
version: 1,
teamId,
teamName: config.teamName,
skills: [],
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
};
this.saveRegistry(registry);
this.registry = registry;
return fullConfig;
}
/**
* Load existing team configuration
*/
load(): TeamConfig | null {
const configPath = join(this.projectPath, TEAM_DIR, TEAM_CONFIG_FILE);
if (!existsSync(configPath)) {
return null;
}
try {
const content = readFileSync(configPath, 'utf-8');
this.config = this.parseYaml(content) as TeamConfig;
this.loadRegistry();
return this.config;
} catch {
return null;
}
}
/**
* Get current config
*/
getConfig(): TeamConfig | null {
return this.config;
}
/**
* Get current registry
*/
getRegistry(): TeamRegistry | null {
return this.registry;
}
/**
* Share a skill to the team registry
*/
async shareSkill(options: ShareOptions): Promise<SharedSkill> {
if (!this.config || !this.registry) {
throw new Error('Team not initialized. Run `skillkit team init` first.');
}
// Find the skill in local skills directory
const skillPath = this.findLocalSkill(options.skillName);
if (!skillPath) {
throw new Error(`Skill "${options.skillName}" not found locally.`);
}
// Read skill content and metadata
const skillMdPath = join(skillPath, 'SKILL.md');
const skillContent = existsSync(skillMdPath)
? readFileSync(skillMdPath, 'utf-8')
: '';
// Parse frontmatter for metadata
const metadata = this.extractFrontmatter(skillContent);
// Create shared skill entry
const shared: SharedSkill = {
name: options.skillName,
version: (metadata.version as string) || '1.0.0',
description: options.description || (metadata.description as string) || '',
author: this.getAuthor(),
sharedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
source: `${this.config.registryUrl}#${options.skillName}`,
tags: options.tags || (metadata.tags as string[]) || [],
agents: options.agents || this.detectCompatibleAgents(skillPath),
downloads: 0,
};
// Check if skill already exists
const existingIndex = this.registry.skills.findIndex(
(s) => s.name === options.skillName
);
if (existingIndex >= 0) {
// Update existing
shared.sharedAt = this.registry.skills[existingIndex].sharedAt;
shared.downloads = this.registry.skills[existingIndex].downloads;
this.registry.skills[existingIndex] = shared;
} else {
// Add new
this.registry.skills.push(shared);
}
this.registry.updatedAt = new Date().toISOString();
this.saveRegistry(this.registry);
return shared;
}
/**
* List all shared skills in the team registry
*/
listSharedSkills(): SharedSkill[] {
return this.registry?.skills || [];
}
/**
* Search shared skills
*/
searchSkills(query: string): SharedSkill[] {
if (!this.registry) return [];
const lowerQuery = query.toLowerCase();
return this.registry.skills.filter(
(s) =>
s.name.toLowerCase().includes(lowerQuery) ||
s.description?.toLowerCase().includes(lowerQuery) ||
s.tags?.some((t) => t.toLowerCase().includes(lowerQuery))
);
}
/**
* Import a shared skill from the team registry
*/
async importSkill(
skillName: string,
options: ImportOptions = {}
): Promise<{ success: boolean; path?: string; error?: string }> {
if (!this.config || !this.registry) {
return { success: false, error: 'Team not initialized' };
}
const sharedSkill = this.registry.skills.find((s) => s.name === skillName);
if (!sharedSkill) {
return { success: false, error: `Skill "${skillName}" not found in team registry` };
}
// Check if skill exists locally
const localPath = this.findLocalSkill(skillName);
if (localPath && !options.overwrite) {
return {
success: false,
error: `Skill "${skillName}" already exists. Use --overwrite to replace.`,
};
}
if (options.dryRun) {
return {
success: true,
path: join(this.projectPath, '.skillkit', 'skills', skillName),
};
}
// Clone from registry source
try {
const provider = detectProvider(this.config.registryUrl);
if (!provider) {
return { success: false, error: 'Cannot detect provider for registry URL' };
}
// Build clone options with auth if available
const cloneOptions: { depth?: number; ssh?: boolean } = { depth: 1 };
if (this.config.auth?.type === 'ssh') {
cloneOptions.ssh = true;
}
const result = await provider.clone(this.config.registryUrl, skillName, cloneOptions);
if (!result.success) {
return { success: false, error: result.error };
}
// Update download count
sharedSkill.downloads = (sharedSkill.downloads || 0) + 1;
this.saveRegistry(this.registry);
return { success: true, path: result.path };
} catch (err) {
return {
success: false,
error: err instanceof Error ? err.message : 'Unknown error',
};
}
}
/**
* Sync with remote registry
*/
async sync(): Promise<{
added: string[];
updated: string[];
removed: string[];
}> {
if (!this.config) {
throw new Error('Team not initialized');
}
if (!this.registry) {
throw new Error('Team registry not loaded. Call load() first.');
}
const result = { added: [] as string[], updated: [] as string[], removed: [] as string[] };
try {
const provider = detectProvider(this.config.registryUrl);
if (!provider) {
throw new Error('Cannot detect provider for registry URL');
}
// Build clone options with auth if available
const cloneOptions: { depth?: number; ssh?: boolean } = { depth: 1 };
if (this.config.auth?.type === 'ssh') {
cloneOptions.ssh = true;
}
// Fetch remote registry
const fetchResult = await provider.clone(this.config.registryUrl, '', cloneOptions);
if (!fetchResult.success || !fetchResult.path) {
throw new Error(fetchResult.error || 'Failed to fetch remote registry');
}
// Read remote registry
const remoteRegistryPath = join(fetchResult.path, TEAM_DIR, 'registry.yaml');
if (existsSync(remoteRegistryPath)) {
const remoteContent = readFileSync(remoteRegistryPath, 'utf-8');
const remoteRegistry = this.parseYaml(remoteContent) as TeamRegistry;
// Merge registries
const localSkillNames = new Set(this.registry?.skills.map((s) => s.name) || []);
// Find added skills
for (const skill of remoteRegistry.skills) {
if (!localSkillNames.has(skill.name)) {
result.added.push(skill.name);
this.registry?.skills.push(skill);
} else {
// Check if updated
const local = this.registry?.skills.find((s) => s.name === skill.name);
if (local && new Date(skill.updatedAt) > new Date(local.updatedAt)) {
result.updated.push(skill.name);
Object.assign(local, skill);
}
}
}
// Find removed skills (optional - keep local for now)
// for (const skill of this.registry?.skills || []) {
// if (!remoteSkillNames.has(skill.name)) {
// result.removed.push(skill.name);
// }
// }
if (this.registry) {
this.registry.updatedAt = new Date().toISOString();
this.saveRegistry(this.registry);
}
}
// Clean up temp directory
if (fetchResult.tempRoot) {
const { rmSync } = await import('node:fs');
rmSync(fetchResult.tempRoot, { recursive: true, force: true });
}
} catch (err) {
throw new Error(`Sync failed: ${err instanceof Error ? err.message : 'Unknown error'}`);
}
return result;
}
/**
* Remove a skill from the team registry
*/
removeSkill(skillName: string): boolean {
if (!this.registry) return false;
const index = this.registry.skills.findIndex((s) => s.name === skillName);
if (index === -1) return false;
this.registry.skills.splice(index, 1);
this.registry.updatedAt = new Date().toISOString();
this.saveRegistry(this.registry);
return true;
}
// Private helpers
private generateTeamId(): string {
return `team-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
private saveConfig(config: TeamConfig): void {
const configPath = join(this.projectPath, TEAM_DIR, TEAM_CONFIG_FILE);
const dir = dirname(configPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
writeFileSync(configPath, this.toYaml(config), 'utf-8');
}
private loadRegistry(): void {
const registryPath = join(this.projectPath, TEAM_DIR, 'registry.yaml');
if (existsSync(registryPath)) {
const content = readFileSync(registryPath, 'utf-8');
this.registry = this.parseYaml(content) as TeamRegistry;
}
}
private saveRegistry(registry: TeamRegistry): void {
const registryPath = join(this.projectPath, TEAM_DIR, 'registry.yaml');
writeFileSync(registryPath, this.toYaml(registry), 'utf-8');
}
private findLocalSkill(skillName: string): string | null {
const possiblePaths = [
join(this.projectPath, '.skillkit', 'skills', skillName),
join(this.projectPath, 'skills', skillName),
join(this.projectPath, '.claude', 'skills', skillName),
];
for (const p of possiblePaths) {
if (existsSync(p)) {
return p;
}
}
return null;
}
private getAuthor(): string {
// Try to get from git config
try {
const name = execSync('git config user.name', { encoding: 'utf-8' }).trim();
const email = execSync('git config user.email', { encoding: 'utf-8' }).trim();
return email ? `${name} <${email}>` : name;
} catch {
return 'Unknown';
}
}
private detectCompatibleAgents(skillPath: string): AgentType[] {
const agents: AgentType[] = [];
// Check for format-specific files
if (existsSync(join(skillPath, 'SKILL.md'))) {
agents.push('claude-code', 'codex', 'gemini-cli', 'universal');
}
if (existsSync(join(skillPath, 'skill.mdc'))) {
agents.push('cursor');
}
if (existsSync(join(skillPath, 'rules.md'))) {
agents.push('windsurf');
}
return agents.length > 0 ? agents : ['universal'];
}
private extractFrontmatter(content: string): Record<string, unknown> {
const match = content.match(/^---\n([\s\S]*?)\n---/);
if (!match) return {};
try {
return this.parseYaml(match[1]) as Record<string, unknown>;
} catch {
return {};
}
}
private parseYaml(content: string): unknown {
return yamlParse(content);
}
private toYaml(obj: unknown): string {
return yamlStringify(obj, { indent: 2 });
}
}
/**
* Create a team manager instance
*/
export function createTeamManager(projectPath: string): TeamManager {
return new TeamManager(projectPath);
}
+112
View File
@@ -0,0 +1,112 @@
/**
* Team Collaboration Types
*/
import type { AgentType } from '../types.js';
/**
* Team member information
*/
export interface TeamMember {
id: string;
name: string;
email?: string;
role: 'admin' | 'contributor' | 'viewer';
joinedAt: string;
}
/**
* Shared skill metadata
*/
export interface SharedSkill {
name: string;
version: string;
description?: string;
author: string;
sharedAt: string;
updatedAt: string;
source: string; // Git URL or registry path
tags?: string[];
agents: AgentType[];
downloads?: number;
rating?: number;
}
/**
* Team configuration
*/
export interface TeamConfig {
/** Team identifier */
teamId: string;
/** Team name */
teamName: string;
/** Team registry URL (git repo or registry endpoint) */
registryUrl: string;
/** Authentication method */
auth?: {
type: 'token' | 'ssh' | 'none';
token?: string;
keyPath?: string;
};
/** Auto-sync interval in minutes (0 = disabled) */
autoSyncInterval?: number;
/** Members list (for admin features) */
members?: TeamMember[];
}
/**
* Team registry containing shared skills
*/
export interface TeamRegistry {
version: number;
teamId: string;
teamName: string;
skills: SharedSkill[];
updatedAt: string;
createdAt: string;
}
/**
* Bundle manifest for exporting skills
*/
export interface BundleManifest {
version: number;
name: string;
description?: string;
author: string;
createdAt: string;
skills: {
name: string;
path: string;
agents: AgentType[];
}[];
totalSize: number;
}
/**
* Options for sharing a skill
*/
export interface ShareOptions {
/** Skill name to share */
skillName: string;
/** Description override */
description?: string;
/** Tags to add */
tags?: string[];
/** Target agents (default: all compatible) */
agents?: AgentType[];
/** Visibility level */
visibility?: 'team' | 'public';
}
/**
* Options for importing skills
*/
export interface ImportOptions {
/** Overwrite existing skills */
overwrite?: boolean;
/** Target agents to install for */
agents?: AgentType[];
/** Dry run mode */
dryRun?: boolean;
}
+3
View File
@@ -75,6 +75,9 @@ export const SkillkitConfig = z.object({
enabledSkills: z.array(z.string()).optional(),
disabledSkills: z.array(z.string()).optional(),
autoSync: z.boolean().default(true),
cacheDir: z.string().optional(),
marketplaceSources: z.array(z.string()).optional(),
defaultTimeout: z.number().optional(),
});
export type SkillkitConfig = z.infer<typeof SkillkitConfig>;
+8 -2
View File
@@ -14,8 +14,10 @@ import { Execute } from './screens/Execute.js';
import { History } from './screens/History.js';
import { Marketplace } from './screens/Marketplace.js';
import { Memory } from './screens/Memory.js';
import { Team } from './screens/Team.js';
import { Plugins } from './screens/Plugins.js';
export type Screen = 'home' | 'browse' | 'installed' | 'sync' | 'settings' | 'recommend' | 'translate' | 'context' | 'workflow' | 'execute' | 'history' | 'marketplace' | 'memory';
export type Screen = 'home' | 'browse' | 'installed' | 'sync' | 'settings' | 'recommend' | 'translate' | 'context' | 'workflow' | 'execute' | 'history' | 'marketplace' | 'memory' | 'team' | 'plugins';
export function App() {
const [screen, setScreen] = useState<Screen>('home');
@@ -39,6 +41,8 @@ export function App() {
e: 'memory',
i: 'installed',
s: 'sync',
a: 'team',
p: 'plugins',
',': 'settings',
};
@@ -72,6 +76,8 @@ export function App() {
case 'history': return <History cols={cols} rows={rows} />;
case 'marketplace': return <Marketplace cols={cols} rows={rows} />;
case 'memory': return <Memory cols={cols} rows={rows} />;
case 'team': return <Team cols={cols} rows={rows} />;
case 'plugins': return <Plugins cols={cols} rows={rows} />;
}
};
@@ -86,7 +92,7 @@ export function App() {
</Box>
</Box>
<Box>
<Text dimColor>h Home m Market b Browse i Inst w Wflow x Exec y Hist r Rec t Trans c Ctx e Mem s Sync , Cfg q Quit</Text>
<Text dimColor>h Home m Market b Browse i Inst w Wflow x Exec a Team p Plug r Rec t Trans c Ctx e Mem s Sync , Cfg q Quit</Text>
</Box>
</Box>
);
+16 -4
View File
@@ -17,6 +17,9 @@ const NAV: { id: Screen; label: string; key: string }[] = [
{ id: 'workflow', label: 'Workflows', key: 'w' },
{ id: 'execute', label: 'Execute', key: 'x' },
{ id: 'history', label: 'History', key: 'y' },
// Collaboration
{ id: 'team', label: 'Team', key: 'a' },
{ id: 'plugins', label: 'Plugins', key: 'p' },
// Tools
{ id: 'recommend', label: 'Recommend', key: 'r' },
{ id: 'translate', label: 'Translate', key: 't' },
@@ -51,8 +54,8 @@ export function Sidebar({ screen }: SidebarProps) {
<Text> </Text>
{/* Tools (6-9) */}
{NAV.slice(6, 10).map((item) => (
{/* Collaboration (6-7) */}
{NAV.slice(6, 8).map((item) => (
<Text key={item.id} inverse={screen === item.id}>
{screen === item.id ? symbols.bullet : ' '}{item.label}
</Text>
@@ -60,8 +63,17 @@ export function Sidebar({ screen }: SidebarProps) {
<Text> </Text>
{/* Management (10-12) */}
{NAV.slice(10).map((item) => (
{/* Tools (8-11) */}
{NAV.slice(8, 12).map((item) => (
<Text key={item.id} inverse={screen === item.id}>
{screen === item.id ? symbols.bullet : ' '}{item.label}
</Text>
))}
<Text> </Text>
{/* Management (12-14) */}
{NAV.slice(12).map((item) => (
<Text key={item.id} inverse={screen === item.id}>
{screen === item.id ? symbols.bullet : ' '}{item.label}
</Text>
+81 -10
View File
@@ -1,5 +1,7 @@
import { useState, useCallback, useEffect } from 'react';
import { detectProvider } from '@skillkit/core';
import { detectProvider, loadConfig, extractFrontmatter } from '@skillkit/core';
import { readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import type { SkillItem } from '../components/SkillList.js';
export interface RepoInfo {
@@ -7,7 +9,8 @@ export interface RepoInfo {
name: string;
}
const POPULAR_REPOS: RepoInfo[] = [
// Default popular repos - can be extended via config.marketplaceSources
const DEFAULT_REPOS: RepoInfo[] = [
{ source: 'anthropics/skills', name: 'Anthropic Official' },
{ source: 'vercel-labs/agent-skills', name: 'Vercel Labs' },
{ source: 'expo/skills', name: 'Expo / React Native' },
@@ -40,6 +43,53 @@ const POPULAR_REPOS: RepoInfo[] = [
{ source: 'intellectronica/agent-skills', name: 'Context7' },
];
/**
* Get marketplace repos from config or use defaults
*/
function getMarketplaceRepos(): RepoInfo[] {
try {
const config = loadConfig();
if (config.marketplaceSources?.length) {
// Merge config sources with defaults, config takes priority
const configRepos: RepoInfo[] = config.marketplaceSources.map(source => ({
source,
name: source.split('/').pop() || source,
}));
// Add defaults that aren't in config
const existingSources = new Set(configRepos.map(r => r.source));
for (const repo of DEFAULT_REPOS) {
if (!existingSources.has(repo.source)) {
configRepos.push(repo);
}
}
return configRepos;
}
} catch {
// Config load failed, use defaults
}
return DEFAULT_REPOS;
}
/**
* Try to read skill description from frontmatter
*/
function readSkillDescription(skillPath: string): string | undefined {
const skillMdPath = join(skillPath, 'SKILL.md');
if (!existsSync(skillMdPath)) {
return undefined;
}
try {
const content = readFileSync(skillMdPath, 'utf-8');
const frontmatter = extractFrontmatter(content);
if (frontmatter && typeof frontmatter.description === 'string') {
return frontmatter.description;
}
} catch {
// Failed to read, return undefined
}
return undefined;
}
interface FetchedSkill {
name: string;
source: string;
@@ -54,6 +104,7 @@ interface UseMarketplaceResult {
totalCount: number;
repos: RepoInfo[];
currentRepo: string | null;
failedRepos: string[];
refresh: () => void;
search: (query: string) => void;
fetchRepo: (source: string) => Promise<void>;
@@ -67,6 +118,8 @@ export function useMarketplace(): UseMarketplaceResult {
const [error, setError] = useState<string | null>(null);
const [currentRepo, setCurrentRepo] = useState<string | null>(null);
const [fetchedRepos, setFetchedRepos] = useState<Set<string>>(new Set());
const [failedRepos, setFailedRepos] = useState<string[]>([]);
const [repos] = useState<RepoInfo[]>(() => getMarketplaceRepos());
const fetchRepo = useCallback(async (source: string) => {
if (fetchedRepos.has(source)) return;
@@ -87,12 +140,13 @@ export function useMarketplace(): UseMarketplaceResult {
throw new Error(result.error || 'Failed to fetch skills');
}
const repoName = POPULAR_REPOS.find(r => r.source === source)?.name || source;
const repoName = repos.find(r => r.source === source)?.name || source;
const newSkills: FetchedSkill[] = result.discoveredSkills.map(skill => ({
name: skill.name,
source: source,
repoName: repoName,
description: undefined,
// Try to read description from skill frontmatter
description: readSkillDescription(skill.path),
}));
setAllSkills(prev => {
@@ -107,30 +161,44 @@ export function useMarketplace(): UseMarketplaceResult {
rmSync(result.tempRoot, { recursive: true, force: true });
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch repository');
const errorMsg = err instanceof Error ? err.message : 'Failed to fetch repository';
setError(errorMsg);
// Track failed repos for display
setFailedRepos(prev => prev.includes(source) ? prev : [...prev, source]);
} finally {
setLoading(false);
setCurrentRepo(null);
}
}, [fetchedRepos]);
}, [fetchedRepos, repos]);
const fetchAllRepos = useCallback(async () => {
setLoading(true);
setError(null);
const failures: string[] = [];
for (const repo of POPULAR_REPOS) {
for (const repo of repos) {
if (!fetchedRepos.has(repo.source)) {
setCurrentRepo(repo.source);
try {
await fetchRepo(repo.source);
} catch {
} catch (err) {
// Track which repos failed
failures.push(repo.source);
}
}
}
// Update failed repos list
if (failures.length > 0) {
setFailedRepos(prev => {
const combined = [...prev, ...failures];
return [...new Set(combined)]; // deduplicate
});
}
setLoading(false);
setCurrentRepo(null);
}, [fetchRepo, fetchedRepos]);
}, [fetchRepo, fetchedRepos, repos]);
const search = useCallback((query: string) => {
if (!query.trim()) {
@@ -153,6 +221,8 @@ export function useMarketplace(): UseMarketplaceResult {
setFetchedRepos(new Set());
setAllSkills([]);
setFilteredSkills([]);
setFailedRepos([]);
setError(null);
}, []);
useEffect(() => {
@@ -170,8 +240,9 @@ export function useMarketplace(): UseMarketplaceResult {
loading,
error,
totalCount: allSkills.length,
repos: POPULAR_REPOS,
repos,
currentRepo,
failedRepos,
refresh,
search,
fetchRepo,
+232
View File
@@ -0,0 +1,232 @@
import { useState, useEffect } from 'react';
import { Box, Text, useInput } from 'ink';
import { colors, symbols } from '../theme.js';
interface PluginInfo {
name: string;
version: string;
description?: string;
author?: string;
enabled: boolean;
translators?: string[];
providers?: string[];
commands?: string[];
}
interface Props {
cols?: number;
rows?: number;
}
export function Plugins({ rows = 24 }: Props) {
const [plugins, setPlugins] = useState<PluginInfo[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [sel, setSel] = useState(0);
const [message, setMessage] = useState<string | null>(null);
const maxVisible = Math.max(5, rows - 12);
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), plugins.length - maxVisible));
const visible = plugins.slice(start, start + maxVisible);
useEffect(() => {
loadPlugins();
}, []);
const loadPlugins = async () => {
setLoading(true);
setError(null);
try {
const { createPluginManager, loadPluginsFromDirectory } = await import('@skillkit/core');
const { join } = await import('node:path');
const manager = createPluginManager(process.cwd());
// Load plugins from directory first to populate the manager
const pluginsDir = join(process.cwd(), '.skillkit', 'plugins');
try {
const loadedPlugins = await loadPluginsFromDirectory(pluginsDir);
for (const plugin of loadedPlugins) {
if (!manager.getPlugin(plugin.metadata.name)) {
await manager.register(plugin);
}
}
} catch (err: unknown) {
// Only ignore ENOENT (directory doesn't exist), rethrow other errors
if (err && typeof err === 'object' && 'code' in err && err.code !== 'ENOENT') {
throw err;
}
}
const allPlugins = manager.listPlugins();
const pluginInfos: PluginInfo[] = allPlugins.map(p => {
const plugin = manager.getPlugin(p.name);
return {
name: p.name,
version: p.version,
description: p.description,
author: p.author,
enabled: manager.isPluginEnabled(p.name),
translators: plugin?.translators?.map(t => t.agentType as string),
providers: plugin?.providers?.map(pr => pr.providerName),
commands: plugin?.commands?.map(c => c.name),
};
});
setPlugins(pluginInfos);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load plugins');
}
setLoading(false);
};
const togglePlugin = async (pluginName: string, currentEnabled: boolean) => {
setLoading(true);
setMessage(null);
try {
const { createPluginManager, loadPluginsFromDirectory } = await import('@skillkit/core');
const { join } = await import('node:path');
const manager = createPluginManager(process.cwd());
// Load plugins from directory first so enable/disable can find them
const pluginsDir = join(process.cwd(), '.skillkit', 'plugins');
try {
const loadedPlugins = await loadPluginsFromDirectory(pluginsDir);
for (const plugin of loadedPlugins) {
if (!manager.getPlugin(plugin.metadata.name)) {
await manager.register(plugin);
}
}
} catch (err: unknown) {
// Only ignore ENOENT (directory doesn't exist), rethrow other errors
if (err && typeof err === 'object' && 'code' in err && err.code !== 'ENOENT') {
throw err;
}
}
if (currentEnabled) {
manager.disablePlugin(pluginName);
setMessage(`Disabled: ${pluginName}`);
} else {
manager.enablePlugin(pluginName);
setMessage(`Enabled: ${pluginName}`);
}
// Reload
await loadPlugins();
} catch (e) {
setError(e instanceof Error ? e.message : 'Toggle failed');
setLoading(false);
}
};
useInput((input, key) => {
if (loading) return;
if (plugins.length === 0 && (key.upArrow || key.downArrow)) return;
if (key.upArrow) setSel(i => Math.max(0, i - 1));
else if (key.downArrow) setSel(i => Math.min(Math.max(0, plugins.length - 1), i + 1));
else if (input === 'r') loadPlugins();
else if (input === 'e' && plugins[sel]) {
togglePlugin(plugins[sel].name, plugins[sel].enabled);
}
else if (key.return && plugins[sel]) {
togglePlugin(plugins[sel].name, plugins[sel].enabled);
}
});
if (loading) {
return (
<Box flexDirection="column" padding={1}>
<Text color={colors.primary} bold>Plugin Manager</Text>
<Box marginTop={1}>
<Text color={colors.secondaryDim}>{symbols.spinner[0]} Loading...</Text>
</Box>
</Box>
);
}
return (
<Box flexDirection="column" padding={1}>
<Text color={colors.primary} bold>Plugin Manager</Text>
<Text color={colors.secondaryDim} dimColor>Manage SkillKit extensions</Text>
{error && (
<Box marginTop={1}>
<Text color="red">{symbols.error} {error}</Text>
</Box>
)}
{message && (
<Box marginTop={1}>
<Text color="green">{symbols.success} {message}</Text>
</Box>
)}
<Box marginTop={1} flexDirection="column">
<Text color={colors.secondaryDim} bold>
Installed Plugins ({plugins.length})
</Text>
{plugins.length === 0 ? (
<Box marginTop={1} flexDirection="column">
<Text color={colors.secondaryDim} dimColor>No plugins installed.</Text>
<Text color={colors.secondaryDim} dimColor>
Use: skillkit plugin install --source &lt;path-or-package&gt;
</Text>
</Box>
) : (
<Box flexDirection="column" marginTop={1}>
{visible.map((plugin, i) => {
const actualIndex = start + i;
const isSelected = actualIndex === sel;
const statusColor = plugin.enabled ? 'green' : 'gray';
const statusText = plugin.enabled ? 'enabled' : 'disabled';
return (
<Box key={plugin.name} flexDirection="column">
<Text>
{isSelected ? symbols.pointer : ' '}{' '}
<Text color={isSelected ? colors.primary : colors.secondaryDim} bold={isSelected}>
{plugin.name}
</Text>
<Text dimColor> v{plugin.version}</Text>
<Text color={statusColor}> [{statusText}]</Text>
</Text>
{isSelected && (
<Box flexDirection="column" marginLeft={3}>
{plugin.description && (
<Text color={colors.secondaryDim} dimColor>{plugin.description}</Text>
)}
{plugin.author && (
<Text dimColor>Author: {plugin.author}</Text>
)}
{plugin.translators && plugin.translators.length > 0 && (
<Text dimColor>Translators: {plugin.translators.join(', ')}</Text>
)}
{plugin.providers && plugin.providers.length > 0 && (
<Text dimColor>Providers: {plugin.providers.join(', ')}</Text>
)}
{plugin.commands && plugin.commands.length > 0 && (
<Text dimColor>Commands: {plugin.commands.join(', ')}</Text>
)}
</Box>
)}
</Box>
);
})}
</Box>
)}
</Box>
<Box marginTop={1} borderStyle="single" borderColor={colors.borderDim} paddingX={1}>
<Text dimColor>
[↑↓] Navigate [e/Enter] Toggle Enable/Disable [r] Refresh
</Text>
</Box>
</Box>
);
}
+162 -14
View File
@@ -1,44 +1,192 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { Box, Text, useInput } from 'ink';
import TextInput from 'ink-text-input';
import { colors, symbols } from '../theme.js';
import { loadConfig, saveConfig, AgentType as AgentTypeSchema, type SkillkitConfig, type AgentType } from '@skillkit/core';
interface Props {
cols?: number;
rows?: number;
}
const SETTINGS = [
{ id: 'agent', label: 'Default Agent', value: 'auto-detect' },
{ id: 'sync', label: 'Auto Sync', value: 'disabled' },
{ id: 'cache', label: 'Cache Dir', value: '~/.skillkit/cache' },
interface Setting {
id: keyof SkillkitConfig | 'agent' | 'autoSync' | 'cacheDir';
label: string;
type: 'select' | 'toggle' | 'text';
options?: string[];
}
// Get all valid agent types from the Zod schema
const ALL_AGENTS: AgentType[] = AgentTypeSchema.options;
const SETTINGS: Setting[] = [
{ id: 'agent', label: 'Default Agent', type: 'select', options: ['auto-detect', ...ALL_AGENTS] },
{ id: 'autoSync', label: 'Auto Sync', type: 'toggle' },
{ id: 'cacheDir', label: 'Cache Dir', type: 'text' },
];
export function Settings({}: Props) {
export function Settings(_props: Props) {
const [config, setConfig] = useState<SkillkitConfig | null>(null);
const [sel, setSel] = useState(0);
const [editing, setEditing] = useState(false);
const [editValue, setEditValue] = useState('');
const [saved, setSaved] = useState(false);
const [error, setError] = useState<string | null>(null);
useInput((_, key) => {
if (key.upArrow) setSel(i => Math.max(0, i - 1));
else if (key.downArrow) setSel(i => Math.min(SETTINGS.length - 1, i + 1));
// Load config on mount
useEffect(() => {
try {
const loaded = loadConfig();
setConfig(loaded);
} catch (err) {
setError(`Failed to load config: ${err}`);
}
}, []);
const getCurrentValue = (setting: Setting): string => {
if (!config) return '';
switch (setting.id) {
case 'agent':
// Map 'universal' back to 'auto-detect' for display consistency
return config.agent === 'universal' ? 'auto-detect' : (config.agent || 'auto-detect');
case 'autoSync':
return config.autoSync ? 'enabled' : 'disabled';
case 'cacheDir':
return config.cacheDir || '~/.skillkit/cache';
default:
return '';
}
};
const handleSave = (setting: Setting, value: string) => {
if (!config) return;
const newConfig = { ...config };
switch (setting.id) {
case 'agent':
if (value === 'auto-detect') {
newConfig.agent = 'universal';
} else {
newConfig.agent = value as AgentType;
}
break;
case 'autoSync':
newConfig.autoSync = value === 'enabled';
break;
case 'cacheDir':
newConfig.cacheDir = value || undefined;
break;
}
try {
saveConfig(newConfig, false);
setConfig(newConfig);
setSaved(true);
setTimeout(() => setSaved(false), 2000);
} catch (err) {
setError(`Failed to save: ${err}`);
setTimeout(() => setError(null), 3000);
}
};
useInput((input, key) => {
if (editing) {
if (key.return) {
handleSave(SETTINGS[sel], editValue);
setEditing(false);
} else if (key.escape) {
setEditing(false);
}
return;
}
if (key.upArrow) {
setSel(i => Math.max(0, i - 1));
} else if (key.downArrow) {
setSel(i => Math.min(SETTINGS.length - 1, i + 1));
} else if (key.return || input === ' ') {
const setting = SETTINGS[sel];
if (setting.type === 'toggle') {
const current = getCurrentValue(setting);
const newValue = current === 'enabled' ? 'disabled' : 'enabled';
handleSave(setting, newValue);
} else if (setting.type === 'select' && setting.options) {
const current = getCurrentValue(setting);
const idx = setting.options.indexOf(current);
const nextIdx = (idx + 1) % setting.options.length;
handleSave(setting, setting.options[nextIdx]);
} else if (setting.type === 'text') {
setEditValue(getCurrentValue(setting));
setEditing(true);
}
}
});
if (!config) {
return (
<Box flexDirection="column">
<Text bold color={colors.primary}>SETTINGS</Text>
{error ? (
<Text color={colors.danger}>{symbols.error} {error}</Text>
) : (
<Text dimColor>Loading...</Text>
)}
</Box>
);
}
return (
<Box flexDirection="column">
<Text bold color={colors.primary}>SETTINGS</Text>
<Text dimColor>Configure SkillKit</Text>
<Text dimColor>Configure SkillKit (changes save automatically)</Text>
<Box marginTop={1} flexDirection="column">
{SETTINGS.map((s, i) => {
const isSel = i === sel;
const value = getCurrentValue(s);
const isEditing = editing && isSel;
return (
<Text key={s.id} inverse={isSel}>
{isSel ? symbols.pointer : ' '}{s.label.padEnd(16)} <Text color={colors.secondaryDim}>{s.value}</Text>
</Text>
<Box key={s.id}>
<Text inverse={isSel && !isEditing}>
{isSel ? symbols.pointer : ' '}{s.label.padEnd(16)}
</Text>
{isEditing ? (
<Box marginLeft={1}>
<TextInput
value={editValue}
onChange={setEditValue}
onSubmit={() => {
handleSave(s, editValue);
setEditing(false);
}}
/>
</Box>
) : (
<Text color={colors.secondaryDim}> {value}</Text>
)}
{s.type === 'toggle' && isSel && !isEditing && (
<Text dimColor> (space to toggle)</Text>
)}
{s.type === 'select' && isSel && !isEditing && (
<Text dimColor> (enter to cycle)</Text>
)}
</Box>
);
})}
</Box>
<Box marginTop={1}>
<Text dimColor>Enter=edit q=quit</Text>
{saved && <Text color={colors.success}>{symbols.check} Settings saved</Text>}
{error && <Text color={colors.danger}>{symbols.error} {error}</Text>}
{!saved && !error && (
<Text dimColor>
{editing ? 'Enter=save Esc=cancel' : 'Enter/Space=edit q=quit'}
</Text>
)}
</Box>
</Box>
);
+221
View File
@@ -0,0 +1,221 @@
import { useState, useEffect } from 'react';
import { Box, Text, useInput } from 'ink';
import { colors, symbols } from '../theme.js';
interface SharedSkill {
name: string;
version: string;
description?: string;
author: string;
downloads?: number;
tags?: string[];
}
interface TeamConfig {
teamId: string;
teamName: string;
registryUrl: string;
}
interface Props {
cols?: number;
rows?: number;
}
export function Team({ rows = 24 }: Props) {
const [config, setConfig] = useState<TeamConfig | null>(null);
const [skills, setSkills] = useState<SharedSkill[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [sel, setSel] = useState(0);
const [message, setMessage] = useState<string | null>(null);
const maxVisible = Math.max(5, rows - 12);
const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), skills.length - maxVisible));
const visible = skills.slice(start, start + maxVisible);
useEffect(() => {
loadTeam();
}, []);
const loadTeam = async () => {
setLoading(true);
setError(null);
try {
const { createTeamManager } = await import('@skillkit/core');
const manager = createTeamManager(process.cwd());
const teamConfig = manager.load();
if (!teamConfig) {
setConfig(null);
setSkills([]);
setError('Team not initialized. Run `skillkit team init` first.');
} else {
setConfig(teamConfig);
const sharedSkills = manager.listSharedSkills();
setSkills(sharedSkills);
setSel(s => Math.min(s, Math.max(0, sharedSkills.length - 1)));
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load team');
}
setLoading(false);
};
const syncTeam = async () => {
if (!config) return;
setLoading(true);
setMessage(null);
try {
const { createTeamManager } = await import('@skillkit/core');
const manager = createTeamManager(process.cwd());
manager.load(); // Load config before sync
const result = await manager.sync();
const changes = [...result.added, ...result.updated];
if (changes.length > 0) {
setMessage(`Synced: ${changes.join(', ')}`);
} else {
setMessage('Already up to date');
}
// Reload skills
const sharedSkills = manager.listSharedSkills();
setSkills(sharedSkills);
setSel(s => Math.min(s, Math.max(0, sharedSkills.length - 1)));
} catch (e) {
setError(e instanceof Error ? e.message : 'Sync failed');
}
setLoading(false);
};
const importSkill = async (skillName: string) => {
if (!config) return;
setLoading(true);
setMessage(null);
try {
const { createTeamManager } = await import('@skillkit/core');
const manager = createTeamManager(process.cwd());
manager.load(); // Load config before import
const result = await manager.importSkill(skillName, { overwrite: false });
if (result.success) {
setMessage(`Imported: ${skillName}`);
} else {
setError(result.error || 'Import failed');
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Import failed');
}
setLoading(false);
};
useInput((input, key) => {
if (loading) return;
if (skills.length === 0 && (key.upArrow || key.downArrow)) return;
if (key.upArrow) setSel(i => Math.max(0, i - 1));
else if (key.downArrow) setSel(i => Math.min(Math.max(0, skills.length - 1), i + 1));
else if (input === 'r') loadTeam();
else if (input === 's') syncTeam();
else if (key.return && skills[sel]) {
importSkill(skills[sel].name);
}
});
if (loading) {
return (
<Box flexDirection="column" padding={1}>
<Text color={colors.primary} bold>Team Collaboration</Text>
<Box marginTop={1}>
<Text color={colors.secondaryDim}>{symbols.spinner[0]} Loading...</Text>
</Box>
</Box>
);
}
if (!config) {
return (
<Box flexDirection="column" padding={1}>
<Text color={colors.primary} bold>Team Collaboration</Text>
<Box marginTop={1} flexDirection="column">
<Text color={colors.secondaryDim}>{symbols.warning} Team not initialized</Text>
<Text color={colors.secondaryDim} dimColor>
Run: skillkit team init --name "Team Name" --registry &lt;url&gt;
</Text>
</Box>
<Box marginTop={1}>
<Text dimColor>[r] Refresh</Text>
</Box>
</Box>
);
}
return (
<Box flexDirection="column" padding={1}>
<Text color={colors.primary} bold>Team: {config.teamName}</Text>
<Text color={colors.secondaryDim} dimColor>Registry: {config.registryUrl}</Text>
{error && (
<Box marginTop={1}>
<Text color="red">{symbols.error} {error}</Text>
</Box>
)}
{message && (
<Box marginTop={1}>
<Text color="green">{symbols.success} {message}</Text>
</Box>
)}
<Box marginTop={1} flexDirection="column">
<Text color={colors.secondaryDim} bold>
Shared Skills ({skills.length})
</Text>
{skills.length === 0 ? (
<Text color={colors.secondaryDim} dimColor>
No shared skills. Use `skillkit team share --name &lt;skill&gt;` to share.
</Text>
) : (
<Box flexDirection="column" marginTop={1}>
{visible.map((skill, i) => {
const actualIndex = start + i;
const isSelected = actualIndex === sel;
return (
<Box key={skill.name} flexDirection="column">
<Text>
{isSelected ? symbols.pointer : ' '}{' '}
<Text color={isSelected ? colors.primary : colors.secondaryDim} bold={isSelected}>
{skill.name}
</Text>
<Text dimColor> v{skill.version}</Text>
<Text dimColor> by {skill.author}</Text>
{skill.downloads !== undefined && (
<Text dimColor> | {skill.downloads} downloads</Text>
)}
</Text>
{skill.description && isSelected && (
<Text color={colors.secondaryDim} dimColor> {skill.description}</Text>
)}
</Box>
);
})}
</Box>
)}
</Box>
<Box marginTop={1} borderStyle="single" borderColor={colors.borderDim} paddingX={1}>
<Text dimColor>
[↑↓] Navigate [Enter] Import [s] Sync [r] Refresh
</Text>
</Box>
</Box>
);
}
+2
View File
@@ -11,3 +11,5 @@ export { Workflow } from './Workflow.js';
export { Execute } from './Execute.js';
export { History } from './History.js';
export { Marketplace } from './Marketplace.js';
export { Team } from './Team.js';
export { Plugins } from './Plugins.js';