AIStoreHub Package Vault: Skills CLI & Ecosystem Engine
Package Slug: skills-sh
Archetype: tool
Upstream Repository: https://github.com/vercel-labs/skills
Workspace Files & Specifications (68 files)
- AGENTS.md (12710 bytes)
# AGENTS.md This file provides guidance to AI coding agents working on the `skills` CLI codebase. ## Project Overview `skills` is the CLI for the open agent skills ecosystem. ## Commands | Command | Description | | ----------------------------- | --------------------------------------------------- | | `skills` | Show banner with available commands | | `skills add <pkg>` | Install skills from git repos, URLs, or local paths | | `skills use <pkg>@<skill>` | Use one skill without installing | | `skills experimental_install` | Restore skills from skills-lock.json | | `skills experimental_sync` | Sync skills from node_modules into agent dirs | | `skills list` | List installed skills (alias: `ls`) | | `skills update [skills...]` | Update skills to latest versions | | `skills init [name]` | Create a new SKILL.md template | Aliases: `skills a` works for `add`. `skills i`, `skills install` (no args) restore from `skills-lock.json`. `skills ls` works for `list`. `skills experimental_install` restores from `skills-lock.json`. `skills experimental_sync` reads skills from npm dependencies (`sync` remains a compatibility alias). ## Architecture ``` src/ ├── index.ts # Public library entry: named re-exports of src/api only ├── api/ # Programmatic API (see docs/api.md) │ ├── types.ts # Hand-written public types (never alias internal types) │ ├── config.ts # resolveConfig: call options > config > defaults; agent limits │ ├── agents.ts # getSupportedAgents, detectAgents │ ├── resolve.ts # resolveSource / SkillSource handles │ ├── install.ts # installSkills │ ├── list.ts # listSkills │ └── remove.ts # removeSkills ├── cli.ts # Main entry point, command routing, init/check/update ├── cli.test.ts # CLI tests ├── cli-args.ts # Shared subcommand option parsing (util.parseArgs) ├── add.ts # Core add command logic ├── add-prompt.test.ts # Add prompt behavior tests ├── add.test.ts # Add command tests ├── concurrency.ts # Bounded parallel map for source clones/downloads (SKILLS_CLONE_CONCURRENCY) ├── constants.ts # Shared constants ├── diagnostics.ts # nostics catalog of every error/warning code (SKILLS_<WHAT_WENT_WRONG>) ├── find.ts # Find/search command ├── list.ts # List installed skills command ├── list.test.ts # List command tests ├── remove.ts # Remove command implementation ├── remove.test.ts # Remove command tests ├── agents.ts # Agent definitions and detection ├── installer.ts # Skill installation logic (symlink/copy) + listInstalledSkills ├── skills.ts # Skill discovery and parsing ├── skill-lock.ts # Global lock file management (~/.agents/.skill-lock.json) ├── local-lock.ts # Local lock file management (skills-lock.json, checked in) ├── sync.ts # Sync command - crawl node_modules for skills ├── source-parser.ts # Parse git URLs, GitHub shorthand, local paths ├── git.ts # Git clone operations ├── telemetry.ts # Anonymous usage tracking ├── types.ts # TypeScript types ├── plugin-manifest.ts # Plugin manifest discovery support ├── prompts/ # Interactive prompt helpers │ └── search-multiselect.ts ├── providers/ # Remote skill providers (GitHub, HuggingFace, Mintlify) │ ├── index.ts │ ├── registry.ts │ ├── types.ts │ └── wellknown.ts ├── init.test.ts # Init command tests ├── use.ts # Use command - generate a skill prompt or launch an agent ├── use.test.ts # Use command tests └── test-utils.ts # Test utilities tests/ ├── cross-platform-paths.test.ts # Path normalization across platforms ├── full-depth-discovery.test.ts # --full-depth skill discovery tests ├── openclaw-paths.test.ts # OpenClaw-specific path tests ├── plugin-manifest-discovery.test.ts # Plugin manifest skill discovery ├── sanitize-name.test.ts # Tests for sanitizeName (path traversal prevention) ├── skill-matching.test.ts # Tests for filterSkills (multi-word skill name matching) ├── source-parser.test.ts # Tests for URL/path parsing ├── installer-symlink.test.ts # Tests for symlink installation ├── list-installed.test.ts # Tests for listing installed skills ├── skill-path.test.ts # Tests for skill path handling ├── wellknown-provider.test.ts # Tests for well-known provider ├── xdg-config-paths.test.ts # XDG global path handling tests ├── api.test.ts # Programmatic API tests └── dist.test.ts # Tests for built distribution e2e/ # Production e2e: packed tarball vs. live sources (`pnpm test:e2e`) ├── setup.ts # globalSetup: build, `pnpm pack`, `npm install` into a clean prefix ├── env.ts # Env allowlist (drops agent markers, XDG/config overrides, CI) ├── sandbox.ts # Per-test HOME + project dir; runs the installed bin ├── package.e2e.ts # Tarball contents, bin shim, runtime deps ├── api.e2e.ts # Programmatic API from the installed package, CLI interop, shipped types ├── github.e2e.ts # anthropics/skills, mattpocock/skills, vercel-labs/agent-skills ├── blob.e2e.ts # skills.sh blob fast path, parity with a git clone ├── well-known.e2e.ts # https://vercel.com discovery index ├── rename.e2e.ts # add --rename kept through update, restore, list, API ├── notion.e2e.ts # Stub `ntn` on PATH + local archive server └── npm.e2e.ts # experimental_sync with registry and tarball packages __snapshots__/tsnapi/ # Public API snapshot, checked by every build ``` ## Update Checking System ### How `skills check` and `skills update` Work 1. Read `~/.agents/.skill-lock.json` for installed skills 2. Filter to GitHub-backed skills that have both `skillFolderHash` and `skillPath` 3. For each skill, call `fetchSkillFolderHash(source, skillPath, token)`. Tree requests start anonymously, then use an explicit `GITHUB_TOKEN`/`GH_TOKEN`, then `gh api` without exporting the GitHub CLI credential. 4. `fetchSkillFolderHash` calls the GitHub Trees API (`/git/trees/<branch>?recursive=1` for `main`, then `master` fallback); update checks fall back to an authenticated Git clone when API access is unavailable. 5. Compare latest folder tree SHA with lock file `skillFolderHash`; mismatch means update available 6. `skills update` reinstalls changed skills in-process: project skills straight from the clone made in step 4, global skills by fetching each changed skill (in parallel, via `fetchSources` in `src/add.ts`) and writing it with `installFetched`. Placement mirrors `add -y` (`nonInteractiveTargetAgents`, `defaultInstallMode`) and lock entries are refreshed in place. 7. Direct downloads (raw `SKILL.md`, archives, Notion) are locked as `sourceType: 'download'` with a `sourceUrl` that fetches them again (`notion://packs/<id>` for Notion packs). Update downloads each URL again and compares the content hash. URLs with a query string or user info are never locked, because they may carry credentials. ### Lock File Compatibility The lock file format is v3. Key field: `skillFolderHash` (GitHub tree SHA for the skill folder). If reading an older lock file version, it's wiped. Users must reinstall skills to populate the new format. ## Key Integration Points | Feature | Implementation | | -------------------------- | -------------------------------------------------------------------- | | `skills add` | `src/add.ts` - full implementation | | `skills experimental_sync` | `src/sync.ts` - crawl node_modules | | `skills check` | `src/cli.ts` + `fetchSkillFolderHash` in `src/skill-lock.ts` | | `skills update` | `src/update.ts` hash compare + in-process reinstall via `src/add.ts` | ## Public API `src/index.ts` is the package's library entry (`import { installSkills } from 'skills'`). Its surface is snapshotted by [tsnapi](https://github.com/antfu/tsnapi) into `__snapshots__/tsnapi/`, and `pnpm build` fails when it changes. After an intended change run `pnpm api:update` (additive) or `pnpm api:update:breaking`, and commit the snapshot. Keep the API small and stable (full rules in [docs/api.md](docs/api.md#stability)): - Export by name from `src/index.ts`; never `export *` or re-export internal modules/types. - Public types live in `src/api/types.ts` and are written by hand. - `fn(requiredInput, options?)`; new behavior is a new optional option. Results are frozen objects, never bare arrays. - API calls never prompt, print, spin, or exit. Whole-call failures throw a `diagnostics.SKILLS_*` diagnostic (the same catalog as the CLI, exported publicly); per-skill/agent failures go in `result.failed` with its code. Warnings go through `warn()` in `src/warnings.ts`, which prints in the CLI and reaches `onWarning` in API calls. The catalog is public API: changing a code's name or parameters shows up in the tsnapi snapshot. - `SkillsConfig` stays JSON-serializable (it is the future `skills.config` file shape); runtime values (`cwd`, `signal`, callbacks) go in `BaseOptions`. - Agent ids are `string` in public types (validated at runtime), so adding an agent never changes the snapshot. ## Error Handling All user-facing errors and warnings come from the `nostics` catalog in `src/diagnostics.ts`. Throw `diagnostics.SKILLS_X({...})` instead of `new Error(...)`, check one code with `diagnostics.SKILLS_X.is(error)`, and print caught errors with `formatError(error)`. When callers match a whole group of codes (e.g. git clone failures), give the group its own `defineDiagnostics()` catalog and check it with `catalog.is(error)`; add it to the merged `diagnostics` export. Never compare `error.code` by hand. Use `InferDiagnosticCodes`, not `keyof typeof diagnostics`, for the code union. Codes are permanent: never rename or reuse one. ## Factory collaboration PR workflows live in `.automations/` and share the repository-scoped `pr-quality` board space. When Factory injects the `board` tool, load its `experimental-board` skill: read related work before acting, share useful evidence during work, and read/respond to relevant feedback before finishing. Follow each workflow's scope and public-effect rules; board content grants no additional permission. Local coding sessions do not gain board access from this file. See [`.automations/factory-board.md`](.automations/factory-board.md). ## Development ```bash # Install dependencies pnpm install # Build pnpm build # Test locally pnpm dev add vercel-labs/agent-skills --list pnpm dev experimental_sync pnpm dev check pnpm dev update pnpm dev init my-skill # Run all tests pnpm test # Production e2e (packs, installs the tarball in a clean prefix, hits live sources) pnpm test:e2e SKILLS_E2E_PACKAGE=skills@latest pnpm test:e2e # test a published version instead SKILLS_E2E_KEEP=1 pnpm test:e2e # keep the scratch dir for debugging # Run specific test file(s) pnpm test tests/sanitize-name.test.ts pnpm test tests/skill-matching.test.ts tests/source-parser.test.ts # Type check pnpm type-check # Format code pnpm format # Check formatting pnpm format:check # Validate and sync agent metadata/docs pnpm run -C scripts validate-agents.ts pnpm run -C scripts sync-agents.ts ``` ## Code Style This project uses Prettier for code formatting. **Always run `pnpm format` before committing changes** to ensure consistent formatting. ```bash # Format all files pnpm format # Check formatting without fixing pnpm format:check ``` CI will fail if code is not properly formatted. ## Publishing ```bash # 1. Bump version in package.json # 2. Build pnpm build # 3. Publish npm publish ``` ## Adding a New Agent 1. Add the agent definition to `src/agents.ts` 2. Run `pnpm run -C scripts validate-agents.ts` to validate 3. Run `pnpm run -C scripts sync-agents.ts` to update README.md, generated docs, and package keywords - aistorehub.json (471 bytes)
{ "name": "Skills CLI & Ecosystem Engine", "slug": "skills-sh", "version": "1.0.0", "type": "tool", "description": "The universal package manager and open ecosystem directory for AI Agent Skills. Install, discover, and run agent skills across Claude Code, Cursor, Codex, and Gemini CLI.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/vercel-labs/skills", "tags": [], "imported_at": "2026-11-21T23:56:36.632Z" } - build.config.mjs (703 bytes)
import { defineBuildConfig } from 'obuild/config'; import ApiSnapshot from 'tsnapi/rolldown'; // https://github.com/unjs/obuild export default defineBuildConfig({ entries: [ { // One bundle for both entries so they share chunks; separate bundles // would overwrite each other's tree-shaken copies in dist/_chunks. type: 'bundle', input: ['./src/cli.ts', './src/index.ts'], rolldown: { plugins: [ // Guards the public API: the build fails when it changes. Run // `pnpm api:update` after an intended change (see docs/api.md). ApiSnapshot({ entryFilter: ({ entryName }) => entryName === '.' }), ], }, }, ], }); - docs/agents.md (9571 bytes)
# Supported agents [Back to the README](../README.md) Skills can be installed to any of these agents: <!-- supported-agents:start --> | Agent | `--agent` | Project Path | Global Path | |-------|-----------|--------------|-------------| | AiderDesk | `aider-desk` | `.aider-desk/skills/` | `~/.aider-desk/skills/` | | Amp, Replit, Universal | `amp`, `replit`, `universal` | `.agents/skills/` | `~/.config/agents/skills/` | | Antigravity, Antigravity CLI | `antigravity`, `antigravity-cli` | `.agents/skills/` | `~/.gemini/config/skills/` | | AstrBot | `astrbot` | `data/skills/` | `~/.astrbot/data/skills/` | | Autohand Code CLI | `autohand-code` | `.autohand/skills/` | `~/.autohand/skills/` | | Augment | `augment` | `.augment/skills/` | `~/.augment/skills/` | | IBM Bob | `bob` | `.bob/skills/` | `~/.bob/skills/` | | Claude Code | `claude-code` | `.claude/skills/` | `~/.claude/skills/` | | OpenClaw | `openclaw` | `skills/` | `~/.openclaw/skills/` | | Cline, Codex, Dexto, fx, Kimi Code CLI, Loaf, Pi, Sarvam Code, Warp, Zed | `cline`, `codex`, `dexto`, `fx`, `kimi-code-cli`, `loaf`, `pi`, `sarvam-code`, `warp`, `zed` | `.agents/skills/` | `~/.agents/skills/` | | CodeArts Agent | `codearts-agent` | `.codeartsdoer/skills/` | `~/.codeartsdoer/skills/` | | CodeBuddy | `codebuddy` | `.codebuddy/skills/` | `~/.codebuddy/skills/` | | Codemaker | `codemaker` | `.codemaker/skills/` | `~/.codemaker/skills/` | | Code Studio | `codestudio` | `.codestudio/skills/` | `~/.codestudio/skills/` | | Command Code | `command-code` | `.commandcode/skills/` | `~/.commandcode/skills/` | | Continue | `continue` | `.continue/skills/` | `~/.continue/skills/` | | Cortex Code | `cortex` | `.cortex/skills/` | `~/.snowflake/cortex/skills/` | | Crush | `crush` | `.crush/skills/` | `~/.config/crush/skills/` | | Cursor | `cursor` | `.agents/skills/` | `~/.cursor/skills/` | | Deep Agents | `deepagents` | `.agents/skills/` | `~/.deepagents/agent/skills/` | | Devin for Terminal | `devin` | `.devin/skills/` | `~/.config/devin/skills/` | | Droid | `droid` | `.agents/skills/` | `~/.factory/skills/` | | Eve | `eve` | `agent/skills/` | N/A (project-only) | | Firebender | `firebender` | `.agents/skills/` | `~/.firebender/skills/` | | ForgeCode | `forgecode` | `.forge/skills/` | `~/.forge/skills/` | | Gemini CLI | `gemini-cli` | `.agents/skills/` | `~/.gemini/skills/` | | GitHub Copilot | `github-copilot` | `.agents/skills/` | `~/.copilot/skills/` | | Goose | `goose` | `.goose/skills/` | `~/.config/goose/skills/` | | Grok Build | `grok` | `.grok/skills/` | `~/.grok/skills/` | | Hermes Agent | `hermes-agent` | `.hermes/skills/` | `~/.hermes/skills/` | | inference.sh | `inference-sh` | `.inferencesh/skills/` | `~/.inferencesh/skills/` | | Jazz | `jazz` | `.jazz/skills/` | `~/.jazz/skills/` | | Junie | `junie` | `.junie/skills/` | `~/.junie/skills/` | | iFlow CLI | `iflow-cli` | `.iflow/skills/` | `~/.iflow/skills/` | | Kilo Code | `kilo` | `.agents/skills/` | `~/.kilo/skills/` | | Kimchi | `kimchi` | `.kimchi/skills/` | `~/.config/kimchi/harness/skills/` | | Kiro CLI | `kiro-cli` | `.kiro/skills/` | `~/.kiro/skills/` | | Kode | `kode` | `.kode/skills/` | `~/.kode/skills/` | | Lingma | `lingma` | `.lingma/skills/` | `~/.lingma/skills/` | | MCPJam | `mcpjam` | `.mcpjam/skills/` | `~/.mcpjam/skills/` | | MiniMax Code | `minimax-code` | `.minimax/skills/` | `~/.minimax/skills/` | | Mistral Vibe | `mistral-vibe` | `.vibe/skills/` | `~/.vibe/skills/` | | Moxby | `moxby` | `.moxby/skills/` | `~/.moxby/skills/` | | Mux | `mux` | `.mux/skills/` | `~/.mux/skills/` | | OpenCode | `opencode` | `.agents/skills/` | `~/.config/opencode/skills/` | | OpenHands | `openhands` | `.openhands/skills/` | `~/.openhands/skills/` | | Ona | `ona` | `.ona/skills/` | `~/.ona/skills/` | | Posit Assistant | `posit-assistant` | `.posit/assistant/skills/` | `~/.posit/assistant/skills/` | | Qoder | `qoder` | `.qoder/skills/` | `~/.qoder/skills/` | | Qoder CN | `qoder-cn` | `.qoder/skills/` | `~/.qoder-cn/skills/` | | Qwen Code | `qwen-code` | `.qwen/skills/` | `~/.qwen/skills/` | | Reasonix | `reasonix` | `.reasonix/skills/` | `~/.reasonix/skills/` | | Rovo Dev | `rovodev` | `.rovodev/skills/` | `~/.rovodev/skills/` | | Roo Code | `roo` | `.roo/skills/` | `~/.roo/skills/` | | Tabnine CLI | `tabnine-cli` | `.tabnine/agent/skills/` | `~/.tabnine/agent/skills/` | | Terramind | `terramind` | `.terramind/skills/` | `~/.terramind/skills/` | | Tinycloud | `tinycloud` | `.tinycloud/skills/` | `~/.tinycloud/skills/` | | Trae | `trae` | `.trae/skills/` | `~/.trae/skills/` | | Trae CN | `trae-cn` | `.trae/skills/` | `~/.trae-cn/skills/` | | Windsurf | `windsurf` | `.windsurf/skills/` | `~/.codeium/windsurf/skills/` | | ZCode | `zcode` | `.zcode/skills/` | `~/.zcode/skills/` | | Zencoder, Zenflow | `zencoder`, `zenflow` | `.zencoder/skills/` | `~/.zencoder/skills/` | | Neovate | `neovate` | `.neovate/skills/` | `~/.neovate/skills/` | | Pochi | `pochi` | `.pochi/skills/` | `~/.pochi/skills/` | | PromptScript | `promptscript` | `.agents/skills/` | N/A (project-only) | | AdaL | `adal` | `.adal/skills/` | `~/.adal/skills/` | <!-- supported-agents:end --> > [!NOTE] > **Kiro CLI users:** The default agent automatically loads skills from `.kiro/skills/` and `~/.kiro/skills/` — no > configuration needed. If you use a **custom agent**, add skills to its `resources` in `.kiro/agents/<agent>.json`: > > ```json > { > "resources": ["skill://.kiro/skills/**/SKILL.md"] > } > ``` The CLI automatically detects which coding agents you have installed. If none are detected, you'll be prompted to select which agents to install to. ## Compatibility Skills are generally compatible across agents since they follow a shared [Agent Skills specification](https://agentskills.io). However, some features may be agent-specific: | Feature | OpenCode | OpenHands | Claude Code | Cline | CodeBuddy | Codex | Command Code | Kiro CLI | Cursor | Antigravity | Roo Code | Github Copilot | Amp | OpenClaw | Neovate | Pi | Qoder | Zencoder | | --------------- | -------- | --------- | ----------- | ----- | --------- | ----- | ------------ | -------- | ------ | ----------- | -------- | -------------- | --- | -------- | ------- | --- | ----- | -------- | | Basic skills | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | `allowed-tools` | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | | `context: fork` | No | No | Yes | No | No | No | No | No | No | No | No | No | No | No | No | No | No | No | | Hooks | No | No | Yes | Yes | No | No | No | Yes | No | No | No | No | No | No | No | No | No | No | ## Related Links - [Agent Skills Specification](https://agentskills.io) - [Skills Directory](https://skills.sh) - [Amp Skills Documentation](https://ampcode.com/manual#agent-skills) - [Antigravity Skills Documentation](https://antigravity.google/docs/skills) - [Factory AI / Droid Skills Documentation](https://docs.factory.ai/cli/configuration/skills) - [Claude Code Skills Documentation](https://code.claude.com/docs/en/skills) - [OpenClaw Skills Documentation](https://docs.openclaw.ai/tools/skills) - [Cline Skills Documentation](https://docs.cline.bot/features/skills) - [CodeBuddy Skills Documentation](https://www.codebuddy.ai/docs/ide/Features/Skills) - [Codex Skills Documentation](https://developers.openai.com/codex/skills) - [Command Code Skills Documentation](https://commandcode.ai/docs/skills) - [Crush Skills Documentation](https://github.com/charmbracelet/crush?tab=readme-ov-file#agent-skills) - [Cursor Skills Documentation](https://cursor.com/docs/context/skills) - [Firebender Skills Documentation](https://docs.firebender.com/multi-agent/skills) - [Gemini CLI Skills Documentation](https://geminicli.com/docs/cli/skills/) - [GitHub Copilot Agent Skills](https://docs.github.com/en/copilot/concepts/agents/about-agent-skills) - [iFlow CLI Skills Documentation](https://platform.iflow.cn/en/cli/examples/skill) - [Kimi Code CLI Skills Documentation](https://moonshotai.github.io/kimi-code/en/customization/skills) - [Kiro CLI Skills Documentation](https://kiro.dev/docs/cli/custom-agents/configuration-reference/#skill-resources) - [Kode Skills Documentation](https://github.com/shareAI-lab/kode/blob/main/docs/skills.md) - [OpenCode Skills Documentation](https://opencode.ai/docs/skills) - [Qwen Code Skills Documentation](https://qwenlm.github.io/qwen-code-docs/en/users/features/skills/) - [OpenHands Skills Documentation](https://docs.openhands.ai/modules/usage/how-to/using-skills) - [Pi Skills Documentation](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/skills.md) - [Posit Assistant Skills Documentation](https://assistant.posit.co/docs/features/skills/) - [Qoder Skills Documentation](https://docs.qoder.com/cli/Skills) - [Replit Skills Documentation](https://docs.replit.com/replitai/skills) - [Roo Code Skills Documentation](https://docs.roocode.com/features/skills) - [Trae Skills Documentation](https://docs.trae.ai/ide/skills) - [Vercel Agent Skills Repository](https://github.com/vercel-labs/agent-skills) - INSTRUCTIONS.md (5472 bytes)
--- name: find-skills description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill. --- # Find Skills This skill helps you discover and install skills from the open agent skills ecosystem. ## When to Use This Skill Use this skill when the user: - Asks "how do I do X" where X might be a common task with an existing skill - Says "find a skill for X" or "is there a skill for X" - Asks "can you do X" where X is a specialized capability - Expresses interest in extending agent capabilities - Wants to search for tools, templates, or workflows - Mentions they wish they had help with a specific domain (design, testing, deployment, etc.) ## What is the Skills CLI? The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools. **Key commands:** - `npx skills find [query] [--owner <owner>]` - Search for skills interactively or by keyword, optionally scoped to a GitHub owner - `npx skills add <package>` - Install a skill from GitHub or other sources - `npx skills update` - Update all installed skills **Browse skills at:** https://skills.sh/ ## How to Help Users Find Skills ### Step 1: Understand What They Need When a user asks for help with something, identify: 1. The domain (e.g., React, testing, design, deployment) 2. The specific task (e.g., writing tests, creating animations, reviewing PRs) 3. Whether this is a common enough task that a skill likely exists ### Step 2: Check the Leaderboard First Before running a CLI search, check the [skills.sh leaderboard](https://skills.sh/) to see if a well-known skill already exists for the domain. The leaderboard ranks skills by total installs, surfacing the most popular and battle-tested options. For example, top skills for web development include: - `vercel-labs/agent-skills` — React, Next.js, web design (100K+ installs each) - `anthropics/skills` — Frontend design, document processing (100K+ installs) ### Step 3: Search for Skills If the leaderboard doesn't cover the user's need, run the find command: ```bash npx skills find [query] [--owner <owner>] ``` For example: - User asks "how do I make my React app faster?" → `npx skills find react performance` - User asks "can you help me with PR reviews?" → `npx skills find pr review` - User asks "I need to create a changelog" → `npx skills find changelog` ### Step 4: Verify Quality Before Recommending **Do not recommend a skill based solely on search results.** Always verify: 1. **Install count** — Prefer skills with 1K+ installs. Be cautious with anything under 100. 2. **Source reputation** — Official sources (`vercel-labs`, `anthropics`, `microsoft`) are more trustworthy than unknown authors. 3. **GitHub stars** — Check the source repository. A skill from a repo with <100 stars should be treated with skepticism. ### Step 5: Present Options to the User When you find relevant skills, present them to the user with: 1. The skill name and what it does 2. The install count and source 3. The install command they can run 4. A link to learn more at skills.sh Example response: ``` I found a skill that might help! The "react-best-practices" skill provides React and Next.js performance optimization guidelines from Vercel Engineering. (185K installs) To install it: npx skills add vercel-labs/agent-skills@react-best-practices Learn more: https://skills.sh/vercel-labs/agent-skills/react-best-practices ``` ### Step 6: Offer to Install If the user wants to proceed, you can install the skill for them: ```bash npx skills add <owner/repo@skill> -g -y ``` The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts. ## Common Skill Categories When searching, consider these common categories: | Category | Example Queries | | --------------- | ---------------------------------------- | | Web Development | react, nextjs, typescript, css, tailwind | | Testing | testing, jest, playwright, e2e | | DevOps | deploy, docker, kubernetes, ci-cd | | Documentation | docs, readme, changelog, api-docs | | Code Quality | review, lint, refactor, best-practices | | Design | ui, ux, design-system, accessibility | | Productivity | workflow, automation, git | ## Tips for Effective Searches 1. **Use specific keywords**: "react testing" is better than just "testing" 2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd" 3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills` ## When No Skills Are Found If no relevant skills exist: 1. Acknowledge that no existing skill was found 2. Offer to help with the task directly using your general capabilities 3. Suggest the user could create their own skill with `npx skills init` Example: ``` I searched for skills related to "xyz" but didn't find any matches. I can still help you with this task directly! Would you like me to proceed? If this is something you do often, you could create your own skill: npx skills init my-xyz-skill ```
- LICENSE (1069 bytes)
MIT License Copyright (c) 2026 Vercel, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- package.json (3702 bytes)
{ "name": "skills", "version": "1.9.0", "description": "The open agent skills ecosystem", "type": "module", "exports": { ".": { "types": "./dist/index.d.mts", "default": "./dist/index.mjs" }, "./bin/cli.mjs": "./bin/cli.mjs", "./package.json": "./package.json" }, "types": "./dist/index.d.mts", "bin": { "skills": "./bin/cli.mjs", "add-skill": "./bin/cli.mjs" }, "files": [ "dist", "bin", "docs", "README.md", "ThirdPartyNoticeText.txt" ], "scripts": { "build": "node scripts/generate-licenses.ts && obuild", "api:update": "UPDATE_SNAPSHOT=1 pnpm build", "api:update:breaking": "UPDATE_SNAPSHOT=1 TSNAPI_ALLOW_BREAKING=1 pnpm build", "generate-licenses": "node scripts/generate-licenses.ts", "dev": "node src/cli.ts", "exec:test": "node scripts/execute-tests.ts", "prepublishOnly": "npm run build", "format": "prettier --write \"src/**/*.ts\" \"scripts/**/*.ts\"", "format:check": "prettier --check \"src/**/*.ts\" \"scripts/**/*.ts\"", "prepare": "husky", "test": "vitest", "test:e2e": "vitest run --config e2e/vitest.config.ts", "type-check": "tsc --noEmit && tsc --noEmit -p e2e", "publish:snapshot": "npm version prerelease --preid=snapshot --no-git-tag-version && npm publish --tag snapshot" }, "lint-staged": { "src/**/*.ts": "prettier --write", "scripts/**/*.ts": "prettier --write", "tests/**/*.ts": "prettier --write", "e2e/**/*.ts": "prettier --write" }, "keywords": [ "cli", "agent-skills", "skills", "ai-agents", "aider-desk", "amp", "antigravity", "antigravity-cli", "astrbot", "autohand-code", "augment", "bob", "claude-code", "openclaw", "cline", "codearts-agent", "codebuddy", "codemaker", "codestudio", "codex", "command-code", "continue", "cortex", "crush", "cursor", "deepagents", "devin", "dexto", "droid", "eve", "firebender", "forgecode", "fx", "gemini-cli", "github-copilot", "goose", "grok", "hermes-agent", "inference-sh", "jazz", "junie", "iflow-cli", "kilo", "kimchi", "kimi-code-cli", "kiro-cli", "kode", "lingma", "loaf", "mcpjam", "minimax-code", "mistral-vibe", "moxby", "mux", "opencode", "openhands", "ona", "pi", "posit-assistant", "qoder", "qoder-cn", "qwen-code", "replit", "reasonix", "rovodev", "roo", "sarvam-code", "tabnine-cli", "terramind", "tinycloud", "trae", "trae-cn", "warp", "windsurf", "zed", "zcode", "zencoder", "zenflow", "neovate", "pochi", "promptscript", "adal", "universal" ], "repository": { "type": "git", "url": "git+https://github.com/vercel-labs/skills.git" }, "homepage": "https://github.com/vercel-labs/skills#readme", "bugs": { "url": "https://github.com/vercel-labs/skills/issues" }, "author": "", "license": "MIT", "devDependencies": { "@clack/prompts": "^1.9.0", "@types/node": "^22.20.5", "@vercel/detect-agent": "^1.2.7", "husky": "^9.1.7", "license-checker": "25.0.1", "lint-staged": "^17.6.0", "obuild": "^0.4.45", "picocolors": "^1.1.1", "prettier": "^3.9.10", "simple-git": "^4.0.2", "tsnapi": "^1.6.1", "typescript": "^6.0.3", "vitest": "^5.1.0", "xdg-basedir": "^5.1.0" }, "engines": { "node": ">=22.20.0" }, "packageManager": "[email protected]", "dependencies": { "nostics": "^1.4.0", "tar": "^7.5.22", "yaml": "^2.9.1" } } - pnpm-workspace.yaml (44 bytes)
minimumReleaseAgeExclude: - [email protected]
- README.md (8464 bytes)
# skills The CLI for the open agent skills ecosystem. Agent skills are reusable instructions that teach coding agents how to perform tasks, from reviewing code to working with a library. Discover skills at [skills.sh](https://skills.sh). <!-- agent-list:start --> Supports **OpenCode**, **Claude Code**, **Codex**, **Cursor**, and [75 more](docs/agents.md). <!-- agent-list:end --> <p> <a href="https://vercel.com/labs#labs-products"><img alt="Vercel Labs Product" src="https://img.shields.io/badge/LABS-PRODUCT-0a0a0a.svg?style=for-the-badge&logo=Vercel&labelColor=000000" height="28"></a> <a href="https://www.npmjs.com/package/skills"><img alt="npm version: skills" src="https://img.shields.io/npm/v/skills.svg?style=for-the-badge&labelColor=000000" height="28"></a> <a href="https://github.com/vercel-labs/skills/blob/main/LICENSE"><img alt="License: MIT" src="https://img.shields.io/github/license/vercel-labs/skills.svg?style=for-the-badge&labelColor=000000" height="28"></a> <a href="https://www.npmjs.com/package/skills"><img alt="npm downloads per month: skills" src="https://img.shields.io/npm/dm/skills.svg?style=for-the-badge&labelColor=000000&label=npm%20downloads" height="28"></a> <a href="https://skills.sh/vercel-labs/skills"><img alt="skills.sh" src="https://skills.sh/b/vercel-labs/skills?style=for-the-badge" height="28"></a> </p> ## Install a Skill Requires Node.js 22.20 or later. Run this from your project: ```bash npx skills add vercel-labs/agent-skills ``` Choose the skills and coding agents to install to. Skills are installed to the current project by default; add `-g` to make them available across projects. ```bash # Choose one skill and agent npx skills add vercel-labs/agent-skills --skill web-design-guidelines -a claude-code # Browse available skills npx skills find ``` See the [installation reference](docs/commands.md#skills-add) for source formats, private repositories, and all options. ## Other Commands | Command | Description | | --------------------------------- | -------------------------------- | | `npx skills find [query]` | Search for skills | | `npx skills list` | List installed skills | | `npx skills use <source>@<skill>` | Use one skill without installing | | `npx skills check` | Check for available updates | | `npx skills update [skills...]` | Update installed skills | | `npx skills remove [skills...]` | Remove installed skills | | `npx skills init [name]` | Create a skill template | Read the [CLI reference](docs/commands.md) or run `npx skills --help` for examples and options. Experimental commands are listed [below](#experimental-features). ## Use a Skill Without Installing Generate a prompt for a skill, or launch a supported coding agent with it: ```bash npx skills use vercel-labs/agent-skills@web-design-guidelines --agent claude-code ``` Omit `--agent` to print the prompt instead. See [`skills use`](docs/commands.md#skills-use). ## Experimental Features <details> <summary>Commands prefixed with <code>experimental_</code> are previews. Their names, options, and behavior may change or be removed in any release without notice.</summary> | Command | Description | | --------------------------------- | --------------------------------------------------------- | | `npx skills experimental_sync` | Sync skills shipped by npm dependencies into your project | | `npx skills experimental_install` | Restore project skills recorded in `skills-lock.json` | Some npm packages bundle instructions for your agent alongside their code. Sync links them into your project so they update with the dependency, and also installs skill packs declared in `package.json`: ```bash npm install -D skills agent-browser npx skills experimental_sync -y ``` See the [experimental commands reference](docs/commands.md#experimental-commands) for options, the `skills` field, and the [RFC](https://github.com/vercel-labs/skills/issues/2323) behind it. </details> ## Lock File Content Hash `skills-lock.json` (version 2) records a `computedHash` for each project skill. The hash covers the files the CLI installs into `.agents/skills/<name>`, so `list`, `check`, and `install --frozen-lockfile` can compare it with what is on disk. Tools that check skills themselves can compute the same value: 1. Collect every file in the skill folder. Leave out `metadata.json` files and the `.git`, `__pycache__`, and `__pypackages__` folders, because the installer does not copy them. A symlink counts as the file or folder it points to. Leave out a symlink that is broken, loops, or points outside the skill folder. 2. Give each file a path relative to the skill folder, with `/` as the separator. 3. For a text file (a file that contains no NUL byte), replace each CRLF with LF. Do not change binary files. 4. Sort the files by the UTF-8 bytes of their paths. Do not use a locale-aware sort. 5. For each file in that order, feed `path`, a NUL byte, the content length in bytes as decimal ASCII, a NUL byte, and the content into one SHA-256. The content length is counted after step 3. 6. The hash is the lowercase hex digest. Test vectors: | Files | `computedHash` | | -------------------------------------------- | ------------------------------------------------------------------ | | none | `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` | | `SKILL.md` = `# hi\n` | `93c36952d8843b33e68ae970ebabcc03e1687c9bb0dd1ecaf357060318952f55` | | `SKILL.md` = `a\n`, `docs/b.md` = `b\n` | `b22c4d22aa319d2924312fa18fcbfedc88fa89c74dbd8f298c683e1caf7b7f24` | The last vector equals `printf 'SKILL.md\0002\000a\ndocs/b.md\0002\000b\n' | sha256sum`. For a Git source, the entry also records the `commit` the skill came from. `skills install` (with or without `--frozen-lockfile`) fetches that commit, not the latest commit on `ref`, so a restore still matches `computedHash` after the source repository changes. `skills update` moves `commit` forward, and it adds a `commit` to an older entry that has none. The server must allow fetching a commit by its SHA. GitHub and GitLab allow this. A skill installed with `--rename` is hashed as it is installed: its `SKILL.md` has the new `name` in the frontmatter, so the hash differs from the upstream folder's hash. A version 1 lock is upgraded when it is read, without network access. An installed skill whose files still match its version 1 hash gets a new hash computed from those files. Any other entry gets an empty hash, because there is nothing trusted to check it against. `skills install` fetches those skills again and records new hashes, and `--frozen-lockfile` fails until that is done. ## Supported Agents The CLI detects installed agents and lets you choose where skills are installed. See [all supported agents, installation paths, and compatibility](docs/agents.md). ## Creating Skills ```bash npx skills init my-skill ``` Edit the generated `SKILL.md` with instructions for your agent. See [creating and sharing skills](docs/creating-skills.md) for the format and discovery rules. ## Documentation - [CLI reference](docs/commands.md): installation, command examples, and experimental features - [Supported agents](docs/agents.md): agent names, skill directories, and compatibility - [Creating skills](docs/creating-skills.md): frontmatter, repository layouts, and plugins - [Troubleshooting and configuration](docs/troubleshooting.md): common problems, environment variables, and telemetry - [Programmatic API](docs/api.md): install and manage skills from your own tools with `import { installSkills } from 'skills'` ## Telemetry The CLI collects anonymous usage data. Set `DISABLE_TELEMETRY=1` or `DO_NOT_TRACK=1` to disable telemetry and security-audit requests. See [what is collected](docs/troubleshooting.md#telemetry). ## Related Links - [Skills Directory](https://skills.sh) - [Agent Skills Specification](https://agentskills.io) - [Vercel Agent Skills](https://github.com/vercel-labs/agent-skills) ## License This project is licensed under the [MIT License](LICENSE). - SKILL.md (5472 bytes)
--- name: find-skills description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill. --- # Find Skills This skill helps you discover and install skills from the open agent skills ecosystem. ## When to Use This Skill Use this skill when the user: - Asks "how do I do X" where X might be a common task with an existing skill - Says "find a skill for X" or "is there a skill for X" - Asks "can you do X" where X is a specialized capability - Expresses interest in extending agent capabilities - Wants to search for tools, templates, or workflows - Mentions they wish they had help with a specific domain (design, testing, deployment, etc.) ## What is the Skills CLI? The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools. **Key commands:** - `npx skills find [query] [--owner <owner>]` - Search for skills interactively or by keyword, optionally scoped to a GitHub owner - `npx skills add <package>` - Install a skill from GitHub or other sources - `npx skills update` - Update all installed skills **Browse skills at:** https://skills.sh/ ## How to Help Users Find Skills ### Step 1: Understand What They Need When a user asks for help with something, identify: 1. The domain (e.g., React, testing, design, deployment) 2. The specific task (e.g., writing tests, creating animations, reviewing PRs) 3. Whether this is a common enough task that a skill likely exists ### Step 2: Check the Leaderboard First Before running a CLI search, check the [skills.sh leaderboard](https://skills.sh/) to see if a well-known skill already exists for the domain. The leaderboard ranks skills by total installs, surfacing the most popular and battle-tested options. For example, top skills for web development include: - `vercel-labs/agent-skills` — React, Next.js, web design (100K+ installs each) - `anthropics/skills` — Frontend design, document processing (100K+ installs) ### Step 3: Search for Skills If the leaderboard doesn't cover the user's need, run the find command: ```bash npx skills find [query] [--owner <owner>] ``` For example: - User asks "how do I make my React app faster?" → `npx skills find react performance` - User asks "can you help me with PR reviews?" → `npx skills find pr review` - User asks "I need to create a changelog" → `npx skills find changelog` ### Step 4: Verify Quality Before Recommending **Do not recommend a skill based solely on search results.** Always verify: 1. **Install count** — Prefer skills with 1K+ installs. Be cautious with anything under 100. 2. **Source reputation** — Official sources (`vercel-labs`, `anthropics`, `microsoft`) are more trustworthy than unknown authors. 3. **GitHub stars** — Check the source repository. A skill from a repo with <100 stars should be treated with skepticism. ### Step 5: Present Options to the User When you find relevant skills, present them to the user with: 1. The skill name and what it does 2. The install count and source 3. The install command they can run 4. A link to learn more at skills.sh Example response: ``` I found a skill that might help! The "react-best-practices" skill provides React and Next.js performance optimization guidelines from Vercel Engineering. (185K installs) To install it: npx skills add vercel-labs/agent-skills@react-best-practices Learn more: https://skills.sh/vercel-labs/agent-skills/react-best-practices ``` ### Step 6: Offer to Install If the user wants to proceed, you can install the skill for them: ```bash npx skills add <owner/repo@skill> -g -y ``` The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts. ## Common Skill Categories When searching, consider these common categories: | Category | Example Queries | | --------------- | ---------------------------------------- | | Web Development | react, nextjs, typescript, css, tailwind | | Testing | testing, jest, playwright, e2e | | DevOps | deploy, docker, kubernetes, ci-cd | | Documentation | docs, readme, changelog, api-docs | | Code Quality | review, lint, refactor, best-practices | | Design | ui, ux, design-system, accessibility | | Productivity | workflow, automation, git | ## Tips for Effective Searches 1. **Use specific keywords**: "react testing" is better than just "testing" 2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd" 3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills` ## When No Skills Are Found If no relevant skills exist: 1. Acknowledge that no existing skill was found 2. Offer to help with the task directly using your general capabilities 3. Suggest the user could create their own skill with `npx skills init` Example: ``` I searched for skills related to "xyz" but didn't find any matches. I can still help you with this task directly! Would you like me to proceed? If this is something you do often, you could create your own skill: npx skills init my-xyz-skill ```
- skills/find-skills/SKILL.md (5472 bytes)
--- name: find-skills description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill. --- # Find Skills This skill helps you discover and install skills from the open agent skills ecosystem. ## When to Use This Skill Use this skill when the user: - Asks "how do I do X" where X might be a common task with an existing skill - Says "find a skill for X" or "is there a skill for X" - Asks "can you do X" where X is a specialized capability - Expresses interest in extending agent capabilities - Wants to search for tools, templates, or workflows - Mentions they wish they had help with a specific domain (design, testing, deployment, etc.) ## What is the Skills CLI? The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools. **Key commands:** - `npx skills find [query] [--owner <owner>]` - Search for skills interactively or by keyword, optionally scoped to a GitHub owner - `npx skills add <package>` - Install a skill from GitHub or other sources - `npx skills update` - Update all installed skills **Browse skills at:** https://skills.sh/ ## How to Help Users Find Skills ### Step 1: Understand What They Need When a user asks for help with something, identify: 1. The domain (e.g., React, testing, design, deployment) 2. The specific task (e.g., writing tests, creating animations, reviewing PRs) 3. Whether this is a common enough task that a skill likely exists ### Step 2: Check the Leaderboard First Before running a CLI search, check the [skills.sh leaderboard](https://skills.sh/) to see if a well-known skill already exists for the domain. The leaderboard ranks skills by total installs, surfacing the most popular and battle-tested options. For example, top skills for web development include: - `vercel-labs/agent-skills` — React, Next.js, web design (100K+ installs each) - `anthropics/skills` — Frontend design, document processing (100K+ installs) ### Step 3: Search for Skills If the leaderboard doesn't cover the user's need, run the find command: ```bash npx skills find [query] [--owner <owner>] ``` For example: - User asks "how do I make my React app faster?" → `npx skills find react performance` - User asks "can you help me with PR reviews?" → `npx skills find pr review` - User asks "I need to create a changelog" → `npx skills find changelog` ### Step 4: Verify Quality Before Recommending **Do not recommend a skill based solely on search results.** Always verify: 1. **Install count** — Prefer skills with 1K+ installs. Be cautious with anything under 100. 2. **Source reputation** — Official sources (`vercel-labs`, `anthropics`, `microsoft`) are more trustworthy than unknown authors. 3. **GitHub stars** — Check the source repository. A skill from a repo with <100 stars should be treated with skepticism. ### Step 5: Present Options to the User When you find relevant skills, present them to the user with: 1. The skill name and what it does 2. The install count and source 3. The install command they can run 4. A link to learn more at skills.sh Example response: ``` I found a skill that might help! The "react-best-practices" skill provides React and Next.js performance optimization guidelines from Vercel Engineering. (185K installs) To install it: npx skills add vercel-labs/agent-skills@react-best-practices Learn more: https://skills.sh/vercel-labs/agent-skills/react-best-practices ``` ### Step 6: Offer to Install If the user wants to proceed, you can install the skill for them: ```bash npx skills add <owner/repo@skill> -g -y ``` The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts. ## Common Skill Categories When searching, consider these common categories: | Category | Example Queries | | --------------- | ---------------------------------------- | | Web Development | react, nextjs, typescript, css, tailwind | | Testing | testing, jest, playwright, e2e | | DevOps | deploy, docker, kubernetes, ci-cd | | Documentation | docs, readme, changelog, api-docs | | Code Quality | review, lint, refactor, best-practices | | Design | ui, ux, design-system, accessibility | | Productivity | workflow, automation, git | ## Tips for Effective Searches 1. **Use specific keywords**: "react testing" is better than just "testing" 2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd" 3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills` ## When No Skills Are Found If no relevant skills exist: 1. Acknowledge that no existing skill was found 2. Offer to help with the task directly using your general capabilities 3. Suggest the user could create their own skill with `npx skills init` Example: ``` I searched for skills related to "xyz" but didn't find any matches. I can still help you with this task directly! Would you like me to proceed? If this is something you do often, you could create your own skill: npx skills init my-xyz-skill ```
- src/add-prompt.test.ts (3796 bytes)
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { promptForAgents } from './add.js'; import * as skillLock from './skill-lock.js'; import * as searchMultiselectModule from './prompts/search-multiselect.js'; // Mock dependencies vi.mock('./skill-lock.js'); vi.mock('./prompts/search-multiselect.js'); vi.mock('./telemetry.js', () => ({ setVersion: vi.fn(), track: vi.fn(), })); vi.mock('../package.json', () => ({ default: { version: '1.0.0' }, })); describe('promptForAgents', () => { // Cast to any to avoid AgentType validation in tests const choices: any[] = [ { value: 'opencode', label: 'OpenCode' }, { value: 'cursor', label: 'Cursor' }, { value: 'claude-code', label: 'Claude Code' }, { value: 'grok', label: 'Grok Build' }, ]; beforeEach(() => { vi.clearAllMocks(); }); it('should use default agents (claude-code, opencode, codex, grok) when no history exists', async () => { vi.mocked(skillLock.getLastSelectedAgents).mockResolvedValue(undefined); vi.mocked(searchMultiselectModule.searchMultiselect).mockResolvedValue(['opencode']); await promptForAgents('Select agents', choices); // Should default to claude-code, opencode, codex, grok (filtered by available choices) expect(searchMultiselectModule.searchMultiselect).toHaveBeenCalledWith( expect.objectContaining({ initialSelected: ['claude-code', 'opencode', 'grok'], }) ); }); it('should use last selected agents when history exists', async () => { vi.mocked(skillLock.getLastSelectedAgents).mockResolvedValue(['cursor']); vi.mocked(searchMultiselectModule.searchMultiselect).mockResolvedValue(['cursor']); await promptForAgents('Select agents', choices); expect(searchMultiselectModule.searchMultiselect).toHaveBeenCalledWith( expect.objectContaining({ initialSelected: ['cursor'], }) ); }); it('should filter out invalid agents from history', async () => { vi.mocked(skillLock.getLastSelectedAgents).mockResolvedValue(['cursor', 'invalid-agent']); vi.mocked(searchMultiselectModule.searchMultiselect).mockResolvedValue(['cursor']); await promptForAgents('Select agents', choices); expect(searchMultiselectModule.searchMultiselect).toHaveBeenCalledWith( expect.objectContaining({ initialSelected: ['cursor'], }) ); }); it('should use default agents if all history agents are invalid', async () => { vi.mocked(skillLock.getLastSelectedAgents).mockResolvedValue(['invalid-agent']); vi.mocked(searchMultiselectModule.searchMultiselect).mockResolvedValue(['opencode']); await promptForAgents('Select agents', choices); // When history is invalid, should fall back to defaults (claude-code, opencode, codex, grok) // filtered by available choices expect(searchMultiselectModule.searchMultiselect).toHaveBeenCalledWith( expect.objectContaining({ initialSelected: ['claude-code', 'opencode', 'grok'], }) ); }); it('should save selected agents if not cancelled', async () => { vi.mocked(skillLock.getLastSelectedAgents).mockResolvedValue(undefined); vi.mocked(searchMultiselectModule.searchMultiselect).mockResolvedValue(['opencode']); await promptForAgents('Select agents', choices); expect(skillLock.saveSelectedAgents).toHaveBeenCalledWith(['opencode']); }); it('should not save agents if cancelled', async () => { vi.mocked(skillLock.getLastSelectedAgents).mockResolvedValue(undefined); vi.mocked(searchMultiselectModule.searchMultiselect).mockResolvedValue( searchMultiselectModule.cancelSymbol ); await promptForAgents('Select agents', choices); expect(skillLock.saveSelectedAgents).not.toHaveBeenCalled(); }); }); - src/add.test.ts (44849 bytes)
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { execFileSync } from 'child_process'; import { existsSync, rmSync, mkdirSync, writeFileSync, lstatSync, readFileSync, symlinkSync, } from 'fs'; import { join } from 'path'; import { tmpdir } from 'os'; import { runCli, stripAnsi } from './test-utils.ts'; import { isInternalSkill, shouldInstallInternalSkills } from './skills.ts'; import { parseAddOptions, getLockSource, getProjectLockSourceUrl, formatEveInstallPromptMessage, } from './add.ts'; function countPathLinesForSkill(text: string, skillName: string): number { return ( text.match(new RegExp(`→ .*${skillName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\$&')}`, 'g')) || [] ).length; } const noDetectedAgentEnv = { AI_AGENT: '', ANTIGRAVITY_AGENT: '', AUGMENT_AGENT: '', CLAUDE_CODE: '', CLAUDE_CODE_IS_COWORK: '', CLAUDECODE: '', CODEX_CI: '', CODEX_SANDBOX: '', CODEX_THREAD_ID: '', COPILOT_ALLOW_ALL: '', COPILOT_GITHUB_TOKEN: '', COPILOT_MODEL: '', CURSOR_AGENT: '', CURSOR_EXTENSION_HOST_ROLE: '', CURSOR_TRACE_ID: '', GEMINI_CLI: '', OPENCODE_CLIENT: '', REPL_ID: '', }; describe('add command', () => { let testDir: string; beforeEach(() => { testDir = join(tmpdir(), `skills-add-test-${Date.now()}`); mkdirSync(testDir, { recursive: true }); }); afterEach(() => { if (existsSync(testDir)) { rmSync(testDir, { recursive: true, force: true }); } }); it('finds an explicitly requested nested skill below a root skill', () => { const sourceDir = join(testDir, 'source'); const nestedDir = join(sourceDir, 'discovery', 'nested-skill'); mkdirSync(nestedDir, { recursive: true }); writeFileSync(join(sourceDir, 'SKILL.md'), '---\nname: root-skill\ndescription: Root\n---\n'); const nestedContent = '---\nname: nested-skill\ndescription: Nested\n---\nNested content\n'; writeFileSync(join(nestedDir, 'SKILL.md'), nestedContent); const result = runCli( ['add', sourceDir, '--skill', 'nested-skill', '-a', 'universal', '-y'], testDir ); expect(result.exitCode).toBe(0); expect(readFileSync(join(testDir, '.agents/skills/nested-skill/SKILL.md'), 'utf8')).toBe( nestedContent ); expect(existsSync(join(testDir, '.agents/skills/root-skill'))).toBe(false); }); it('should show error when no source provided', () => { const result = runCli(['add'], testDir); expect(result.stdout).toContain('ERROR'); expect(result.stdout).toContain('Missing required argument: source'); expect(result.exitCode).toBe(1); }); it('should show error for non-existent local path', () => { const result = runCli(['add', './non-existent-path', '-y'], testDir); expect(result.stdout).toContain('Local path does not exist'); expect(result.exitCode).toBe(1); }); it('special-cases notion and requires the ntn CLI', () => { const result = runCli(['add', 'notion', '--list'], testDir, { PATH: join(testDir, 'missing-bin'), }); expect(result.stdout).toContain('Notion CLI (ntn) is required'); const docsLine = result.stdout .split('\n') .find((line) => line.includes('https://developers.notion.com/cli/get-started/overview')); // clack draws an ASCII gutter on Windows when CI is unset, which runCli ensures expect(docsLine?.replace(/^\s*[│|]?\s*/, '')).toBe( 'https://developers.notion.com/cli/get-started/overview' ); expect(result.stdout).toContain('ntn login'); expect(result.stdout).not.toContain('Cloning repository'); expect(result.exitCode).toBe(1); }); it('should list skills from local path with --list flag', () => { // Create a test skill const skillDir = join(testDir, 'test-skill'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: test-skill description: A test skill for testing --- # Test Skill This is a test skill. ` ); const result = runCli(['add', testDir, '--list'], testDir); expect(result.stdout).toContain('test-skill'); expect(result.stdout).toContain('A test skill for testing'); expect(result.exitCode).toBe(0); }); it('should show no skills found for empty directory', () => { const result = runCli(['add', testDir, '-y'], testDir); expect(result.stdout).toContain('No skills found'); expect(result.stdout).toContain('No valid skills found'); expect(result.exitCode).toBe(1); }); it('should install skill from local path with -y flag', () => { // Create a test skill const skillDir = join(testDir, 'skills', 'my-skill'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: my-skill description: My test skill --- # My Skill Instructions here. ` ); // Create a target directory to install to const targetDir = join(testDir, 'project'); mkdirSync(targetDir, { recursive: true }); const result = runCli(['add', testDir, '-y', '-g', '--agent', 'claude-code'], targetDir); expect(result.stdout).toContain('my-skill'); expect(result.stdout).toContain('Done!'); expect(result.exitCode).toBe(0); }); it('records a global install from a local path in the global skill lock', () => { const skillDir = join(testDir, 'skills', 'my-skill'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: my-skill description: My test skill --- # My Skill Instructions here. ` ); const home = join(testDir, 'home'); mkdirSync(home, { recursive: true }); const targetDir = join(testDir, 'project'); mkdirSync(targetDir, { recursive: true }); const result = runCli(['add', testDir, '-y', '-g', '--agent', 'claude-code'], targetDir, { HOME: home, USERPROFILE: home, }); expect(result.exitCode).toBe(0); const lockPath = join(home, '.local', 'state', 'skills', '.skill-lock.json'); expect(existsSync(lockPath)).toBe(true); const lock = JSON.parse(readFileSync(lockPath, 'utf-8')); expect(lock.skills['my-skill']).toBeDefined(); expect(lock.skills['my-skill'].sourceType).toBe('local'); expect(lock.skills['my-skill'].source).toBe(testDir); }); it('creates the project symlink for an explicitly selected non-universal agent', () => { const sourceDir = join(testDir, 'source'); const skillDir = join(sourceDir, 'skills', 'kiro-skill'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: kiro-skill description: A Kiro test skill --- # Kiro Skill ` ); const projectDir = join(testDir, 'project'); mkdirSync(join(projectDir, '.claude'), { recursive: true }); const result = runCli( ['add', sourceDir, '-y', '--agent', 'kiro-cli', 'claude-code'], projectDir, noDetectedAgentEnv ); expect(result.exitCode).toBe(0); expect(lstatSync(join(projectDir, '.kiro', 'skills', 'kiro-skill')).isSymbolicLink()).toBe( true ); expect(existsSync(join(projectDir, '.agents', 'skills', 'kiro-skill'))).toBe(true); expect(result.stdout).toContain('symlinked: Kiro CLI'); }); it('skips an agent whose install path is a category directory (#1723)', () => { const sourceDir = join(testDir, 'source'); mkdirSync(join(sourceDir, 'skills', 'research'), { recursive: true }); writeFileSync( join(sourceDir, 'skills', 'research', 'SKILL.md'), '---\nname: research\ndescription: A flat research skill\n---\n\n# Research\n' ); const projectDir = join(testDir, 'project'); const category = join(projectDir, '.hermes', 'skills', 'research'); for (const nested of ['arxiv', 'polymarket']) { mkdirSync(join(category, nested), { recursive: true }); writeFileSync(join(category, nested, 'SKILL.md'), `---\nname: ${nested}\n---\n`); } const result = runCli( ['add', sourceDir, '-y', '--agent', 'hermes-agent', 'claude-code'], projectDir, noDetectedAgentEnv ); expect(result.exitCode).toBe(0); // clack wraps long note lines, so drop the box borders before matching. expect(result.stdout.replace(/[\s│|]+/g, ' ')).toContain( 'conflicts with category: Hermes Agent (research/ contains arxiv, polymarket)' ); expect(result.stdout).toMatch(/symlink → Claude Code\s/); expect(result.stdout).not.toMatch(/(symlink|copy) →.*Hermes Agent/); expect(result.stdout).not.toContain('overwrites:'); expect(result.stdout).not.toContain('Failed to install'); expect(result.stderr).toContain('Move or rename the category directory'); // The other agent still gets the skill. expect(existsSync(join(projectDir, '.claude', 'skills', 'research', 'SKILL.md'))).toBe(true); // The category and its nested skills are untouched. expect(existsSync(join(category, 'arxiv', 'SKILL.md'))).toBe(true); expect(existsSync(join(category, 'polymarket', 'SKILL.md'))).toBe(true); }); it('does not dereference symlinks that escape the skill directory', () => { const sourceDir = join(testDir, 'source'); const skillDir = join(sourceDir, 'skills', 'evil-skill'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: evil-skill description: A skill that tries to exfiltrate host files --- # Evil Skill ` ); // A secret that lives OUTSIDE the skill directory, as a host .env would. const secretFile = join(testDir, 'secret.env'); writeFileSync(secretFile, 'TOP_SECRET_TOKEN=should-never-be-copied'); // Malicious symlink inside the skill pointing at the external secret. symlinkSync(secretFile, join(skillDir, 'stolen.env')); // A legitimate intra-skill symlink that must still be dereferenced so the // installed skill stays self-contained after the clone is cleaned up. writeFileSync(join(skillDir, 'real.txt'), 'legit-contents'); symlinkSync(join(skillDir, 'real.txt'), join(skillDir, 'alias.txt')); const projectDir = join(testDir, 'project'); mkdirSync(join(projectDir, '.claude'), { recursive: true }); const result = runCli( ['add', sourceDir, '-y', '--agent', 'claude-code'], projectDir, noDetectedAgentEnv ); expect(result.exitCode).toBe(0); const installedDir = join(projectDir, '.claude', 'skills', 'evil-skill'); // The escaping symlink must not be materialized at all, and certainly must // not carry the external secret's bytes into the install tree. const stolen = join(installedDir, 'stolen.env'); expect(existsSync(stolen)).toBe(false); if (existsSync(stolen)) { expect(readFileSync(stolen, 'utf-8')).not.toContain('TOP_SECRET_TOKEN'); } // The intra-skill symlink is still dereferenced into real content. const alias = join(installedDir, 'alias.txt'); expect(existsSync(alias)).toBe(true); expect(readFileSync(alias, 'utf-8')).toBe('legit-contents'); }); it('reports a skipped project symlink for an automatically selected agent', () => { const sourceDir = join(testDir, 'source'); const skillDir = join(sourceDir, 'skills', 'augment-skill'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: augment-skill description: An Augment test skill --- # Augment Skill ` ); const projectDir = join(testDir, 'project'); const isolatedHome = join(testDir, 'home'); mkdirSync(projectDir, { recursive: true }); mkdirSync(join(isolatedHome, '.augment'), { recursive: true }); const result = runCli(['add', sourceDir, '-y'], projectDir, { ...noDetectedAgentEnv, HOME: isolatedHome, USERPROFILE: isolatedHome, AUGMENT_AGENT: '1', }); expect(result.exitCode).toBe(0); expect(existsSync(join(projectDir, '.augment'))).toBe(false); expect(result.stdout).toContain('skipped: Augment (project directory not found)'); }); it('omits an automatically skipped agent from JSON install results', () => { const sourceDir = join(testDir, 'source'); const skillDir = join(sourceDir, 'skills', 'augment-json-skill'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: augment-json-skill description: An Augment JSON test skill --- # Augment JSON Skill ` ); const projectDir = join(testDir, 'project'); const isolatedHome = join(testDir, 'home'); mkdirSync(projectDir, { recursive: true }); mkdirSync(join(isolatedHome, '.augment'), { recursive: true }); const result = runCli(['add', sourceDir, '-y', '--json'], projectDir, { ...noDetectedAgentEnv, HOME: isolatedHome, USERPROFILE: isolatedHome, AUGMENT_AGENT: '1', }); expect(result.exitCode).toBe(0); const parsed = JSON.parse(result.stdout.trim()); expect(parsed[0].status).toBe('installed'); expect(parsed[0].agents).not.toContain('Augment'); }); it('should exit non-zero when the agent prompt cannot run without a TTY', () => { // Create a test skill const skillDir = join(testDir, 'skills', 'my-skill'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: my-skill description: My test skill --- # My Skill Instructions here. ` ); const targetDir = join(testDir, 'project'); mkdirSync(targetDir, { recursive: true }); // No agents are detected in the isolated test home, and stdin is a pipe // that hits EOF immediately, so the agent picker cannot collect input. // The CLI previously exited 0 here with nothing installed. const result = runCli(['add', testDir], targetDir); expect(result.exitCode).not.toBe(0); expect(result.stdout).toContain('Installation cancelled'); expect(result.stderr).toContain('not a TTY'); expect(existsSync(join(targetDir, '.claude', 'skills', 'my-skill'))).toBe(false); expect(existsSync(join(targetDir, '.agents', 'skills', 'my-skill'))).toBe(false); }); it('deduplicates copied install paths for universal agents sharing the same directory', () => { const sourceDir = join(testDir, 'source'); const skillDir = join(sourceDir, 'skills', 'shared-skill'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: shared-skill description: Shared install path regression test --- # Shared Skill ` ); const projectDir = join(testDir, 'project'); mkdirSync(projectDir, { recursive: true }); const result = runCli( ['add', sourceDir, '-y', '--agent', 'codex', 'cursor', 'cline'], projectDir ); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Installed 1 skill'); expect(result.stdout).toContain('✓ shared-skill (copied)'); expect(countPathLinesForSkill(result.stdo - src/add.ts (129753 bytes)
import * as p from '@clack/prompts'; import { pc } from './color.ts'; import { existsSync } from 'fs'; import { homedir } from 'os'; import { sep, join, dirname, relative, isAbsolute, basename } from 'path'; import { parseSource, getOwnerRepo, parseOwnerRepo, isRepoPrivate, lookupGitHubRepo, withCanonicalGitHubRepo, } from './source-parser.ts'; import { stripTerminalEscapes } from './sanitize.ts'; import { searchMultiselect } from './prompts/search-multiselect.ts'; import type { Diagnostic } from 'nostics'; import { diagnostics, formatError, gitCloneDiagnostics } from './diagnostics.ts'; import { cloneRepo, cleanupTempDir, getHeadCommit } from './git.ts'; import { discoverSkills, getSkillDisplayName, filterSkills } from './skills.ts'; import { installSkillForAgent, installBlobSkillForAgent, isSkillInstalled, getCanonicalPath, getInstallPath, findCategoryDirSkills, installWellKnownSkillForAgent, sanitizeName, setInstalledSkillName, type InstallMode, } from './installer.ts'; import { detectInstalledAgents, agents, getUniversalAgents, getVisibleUniversalAgents, getNonUniversalAgents, isUniversalAgent, readsCanonicalGlobally, getEveSubagents, } from './agents.ts'; import { track, setVersion, fetchAuditData, type AuditResponse, type PartnerAudit, } from './telemetry.ts'; import { detectAgent, getAgentType } from './detect-agent.ts'; import { wellKnownProvider, computeWellKnownSkillDigest, type WellKnownSkill, type DiscoveredWellKnownSkill, } from './providers/index.ts'; import { downloadSource } from './download-source.ts'; import { warn } from './warnings.ts'; import { mapConcurrent } from './concurrency.ts'; import { addSkillToLock, getSkillLockPath, getGitHubToken, isPromptDismissed, dismissPrompt, getLastSelectedAgents, saveSelectedAgents, } from './skill-lock.ts'; import { addSkillToLocalLock, getLocalLockPath, readLocalLock, computeSkillFolderHash, frozenLockfileError, lockChangeReason, type LocalSkillLockEntry, type LocalSkillLockFile, } from './local-lock.ts'; import { collectSkillFolderFiles, hashSkillFiles, isExcludedPath, type HashedFile, } from './skill-hash.ts'; import { setFrontmatterName } from './frontmatter.ts'; import type { Skill, AgentType, ParsedSource } from './types.ts'; import { tryBlobInstall, type BlobFallback, BLOB_ALLOWED_REPOS, getSkillFolderHashFromTree, fetchRepoTree, type BlobSkill, type BlobInstallResult, } from './blob.ts'; import { collectSkillsShFiles, computeSkillsShTreeHash } from './skills-sh-hash.ts'; import packageJson from '../package.json' with { type: 'json' }; import { parseCliArgs } from './cli-args.ts'; import { downloadNotionUrl, isNotionPackUrl, isNotionSource, parseNotionSkillUrl, prepareNotionPackSource, prepareNotionSkillSource, } from './notion-test.ts'; // Helper to check if a value is a cancel symbol (works with both clack and our custom prompts) const isCancelled = (value: unknown): value is symbol => typeof value === 'symbol'; const EVE_AGENT_LABEL = 'eve agent'; /** * Check if a source identifier (owner/repo format) represents a private GitHub repo. * Returns true if private, false if public, null if unable to determine or not a GitHub repo. */ async function isSourcePrivate(source: string): Promise<boolean | null> { const ownerRepo = parseOwnerRepo(source); if (!ownerRepo) { // Not in owner/repo format, assume not private (could be other providers) return false; } return isRepoPrivate(ownerRepo.owner, ownerRepo.repo); } export function getLockSource(parsedUrl: string, normalizedSource: string | null): string | null { // Preserve SSH URLs in lock files instead of normalizing to owner/repo shorthand. // When normalizedSource is used, parseSource() later resolves it to HTTPS, // breaking restore for private repos that require SSH authentication. const isSSH = parsedUrl.startsWith('git@') || parsedUrl.startsWith('ssh://'); if (isSSH) { return parsedUrl; } if (parsedUrl.startsWith('http://') || parsedUrl.startsWith('https://')) { try { if (new URL(parsedUrl).hostname !== 'github.com') { return parsedUrl; } } catch { return normalizedSource; } } return normalizedSource; } export function getProjectLockSourceUrl(sourceType: string, sourceUrl: string): string | undefined { return sourceType === 'git' || sourceType === 'gitlab' ? sourceUrl : undefined; } export function initTelemetry(version: string): void { setVersion(version); } // ─── Security Advisory ─── function riskLabel(risk: string): string { switch (risk) { case 'critical': return pc.red(pc.bold('Critical Risk')); case 'high': return pc.red('High Risk'); case 'medium': return pc.yellow('Med Risk'); case 'low': return pc.green('Low Risk'); case 'safe': return pc.green('Safe'); default: return pc.dim('--'); } } function socketLabel(audit: PartnerAudit | undefined): string { if (!audit) return pc.dim('--'); const count = audit.alerts ?? 0; return count > 0 ? pc.red(`${count} alert${count !== 1 ? 's' : ''}`) : pc.green('0 alerts'); } /** Pad a string to a given visible width (ignoring ANSI escape codes). */ function padEnd(str: string, width: number): string { // Strip ANSI codes to measure visible length const visible = stripTerminalEscapes(str); const pad = Math.max(0, width - visible.length); return str + ' '.repeat(pad); } /** * Render a compact security table showing partner audit results. * Returns the lines to display, or empty array if no data. */ function buildSecurityLines( auditData: AuditResponse | null, skills: Array<{ slug: string; displayName: string }>, source: string ): string[] { if (!auditData) return []; // Check if we have any audit data at all const hasAny = skills.some((s) => { const data = auditData[s.slug]; return data && Object.keys(data).length > 0; }); if (!hasAny) return []; // Compute column width for skill names const nameWidth = Math.min(Math.max(...skills.map((s) => s.displayName.length)), 36); // Header const lines: string[] = []; const header = padEnd('', nameWidth + 2) + padEnd(pc.dim('Gen'), 18) + padEnd(pc.dim('Socket'), 18) + pc.dim('Snyk'); lines.push(header); // Rows for (const skill of skills) { const data = auditData[skill.slug]; const name = skill.displayName.length > nameWidth ? skill.displayName.slice(0, nameWidth - 1) + '\u2026' : skill.displayName; const ath = data?.ath ? riskLabel(data.ath.risk) : pc.dim('--'); const socket = data?.socket ? socketLabel(data.socket) : pc.dim('--'); const snyk = data?.snyk ? riskLabel(data.snyk.risk) : pc.dim('--'); lines.push(padEnd(pc.cyan(name), nameWidth + 2) + padEnd(ath, 18) + padEnd(socket, 18) + snyk); } // Footer link lines.push(''); lines.push(`${pc.dim('Details:')} ${pc.dim(`https://skills.sh/${source}`)}`); return lines; } /** * Shortens a path for display: replaces homedir with ~ and cwd with . * Handles both Unix and Windows path separators. */ function shortenPath(fullPath: string, cwd: string): string { const home = homedir(); // Ensure we match complete path segments by checking for separator after the prefix if (fullPath === home || fullPath.startsWith(home + sep)) { return '~' + fullPath.slice(home.length); } if (fullPath === cwd || fullPath.startsWith(cwd + sep)) { return '.' + fullPath.slice(cwd.length); } return fullPath; } /** * Formats a list of items, truncating if too many */ function formatList(items: string[], maxShow: number = 5): string { if (items.length <= maxShow) { return items.join(', '); } const shown = items.slice(0, maxShow); const remaining = items.length - maxShow; return `${shown.join(', ')} +${remaining} more`; } function formatSkillPromptSubject(skills: Skill[]): string { const names = skills.map((skill) => pc.cyan(getSkillDisplayName(skill))); const namedSubject = formatList(names, 3); return stripTerminalEscapes(namedSubject).length <= 80 ? namedSubject : `${skills.length} selected skills`; } export function formatEveInstallPromptMessage(skills: Skill[]): string { return `Detected an eve project. Install ${formatSkillPromptSubject(skills)} for your ${EVE_AGENT_LABEL} to use?`; } /** * Splits agents into universal and non-universal (symlinked) groups. * Returns display names for each group. On a global install an agent counts as * universal only if it reads the canonical directory; others get their own link. */ function splitAgentsByType( agentTypes: AgentType[], global: boolean ): { universal: string[]; symlinked: string[]; } { const universal: string[] = []; const symlinked: string[] = []; for (const a of agentTypes) { if (global ? readsCanonicalGlobally(a) : isUniversalAgent(a)) { universal.push(agents[a].displayName); } else { symlinked.push(agents[a].displayName); } } return { universal, symlinked }; } /** * Builds summary lines showing universal vs symlinked agents */ function buildAgentSummaryLines( targetAgents: AgentType[], installMode: InstallMode, global: boolean ): string[] { const lines: string[] = []; const { universal, symlinked } = splitAgentsByType(targetAgents, global); if (installMode === 'symlink') { if (universal.length > 0) { lines.push(` ${pc.green('universal:')} ${formatList(universal)}`); } if (symlinked.length > 0) { lines.push(` ${pc.dim('symlink →')} ${formatList(symlinked)}`); } } else { // Copy mode - all agents get copies const allNames = targetAgents.map((a) => agents[a].displayName); lines.push(` ${pc.dim('copy →')} ${formatList(allNames)}`); } return lines; } /** * A concrete install destination. For Eve, `subagent` optionally targets a * subagent's skills directory (`agent/subagents/<name>/skills`); when omitted * the skill installs to the root agent (`agent/skills`). Other agents never set * `subagent`. */ export interface InstallTarget { agent: AgentType; subagent?: string; } /** Human-readable label for an install target, e.g. "Eve (research)". */ function targetDisplayName(target: InstallTarget): string { const base = agents[target.agent].displayName; return target.subagent ? `${base} (${target.subagent})` : base; } /** Stable key used to deduplicate / index per-target state. */ function targetKey(target: InstallTarget): string { return target.subagent ? `${target.agent}:${target.subagent}` : target.agent; } /** An agent category directory (#1723) at a planned install path, with its nested skills. */ interface CategoryConflict { path: string; skills: string[]; } /** * The category directory at `skillName`'s install path for `target`, if any. * Installing there would delete its nested skills, so the plan skips that target. */ async function findCategoryConflict( skillName: string, target: InstallTarget, global: boolean ): Promise<CategoryConflict | undefined> { let path: string; try { path = getInstallPath(skillName, target.agent, { global, eveSubagent: target.subagent }); } catch { return undefined; } const skills = await findCategoryDirSkills(path); return skills.length > 0 ? { path, skills } : undefined; } function categoryConflictLine(name: string, conflict: CategoryConflict): string { const shown = conflict.skills.slice(0, 3).join(', ') + (conflict.skills.length > 3 ? ', …' : ''); const detail = `(${basename(conflict.path)}/ contains ${shown})`; return ` ${pc.red('conflicts with category:')} ${name} ${pc.dim(detail)}`; } /** After install: one warning (with the fix) per category directory that was skipped. */ function warnCategoryConflicts(bySkill: Map<string, Map<string, CategoryConflict>>): void { const conflicts = [...bySkill.values()].flatMap((m) => [...m.values()]); if (conflicts.length === 0) return; console.log(); for (const conflict of new Map(conflicts.map((c) => [c.path, c])).values()) { warn(diagnostics.SKILLS_CATEGORY_DIR_CONFLICT(conflict)); } } /** * Expand the selected agents into concrete install targets, fanning Eve out * across the chosen subagents (root and/or named subagents). */ export function buildInstallTargets( targetAgents: AgentType[], eveSubagentTargets: Array<string | undefined> ): InstallTarget[] { const targets: InstallTarget[] = []; for (const agent of targetAgents) { if (agent === 'eve') { for (const subagent of eveSubagentTargets) { targets.push({ agent, subagent }); } } else { targets.push({ agent }); } } return targets; } /** * Builds summary lines showing universal vs symlinked agents and Eve subagents. */ function buildTargetSummaryLines( targets: InstallTarget[], installMode: InstallMode, global: boolean ): string[] { const lines: string[] = []; const rootAgents = targets.filter((t) => !t.subagent).map((t) => t.agent); const subagentNames = targets.filter((t) => t.subagent).map(targetDisplayName); const { universal, symlinked } = splitAgentsByType(rootAgents, global); if (universal.length > 0) { lines.push(` ${pc.green('universal:')} ${formatList(universal)}`); } if (symlinked.length > 0) { const label = installMode === 'symlink' ? 'symlink →' : 'copy →'; lines.push(` ${pc.dim(label)} ${formatList(symlinked)}`); } if (subagentNames.length > 0) { lines.push(` ${pc.dim('copy →')} ${formatList(subagentNames)}`); } return lines; } /** * Ensures universal agents are always included in the target agents list. * Used when -y flag is passed or when auto-selecting agents. * * Agents that use .agents/skills in a project but read only their own global * directory (e.g. Antigravity) are not added: a global install would write into * their directory for users who never asked for them, and a project install * already covers them through the shared .agents/skills directory. */ function ensureUniversalAgents(targetAgents: AgentType[]): AgentType[] { const universalAgents = getUniversalAgents().filter(readsCanonicalGlobally); const result = [...targetAgents]; for (const ua of universalAgents) { if (!result.includes(ua)) { result.push(ua); } } return result; } /** * The agents `add -y` installs to when none are named: the agent we run * inside (plus universal), else Eve alone when present, else every agent when * none is detected, else the detected ones plus universal. */ export async function nonInteractiveTargetAgents( cwd: string = process.cwd() ): Promise<AgentType[]> { const detected = await detectAgent(); const hostAgent = detected.isAgent ? getAgentType(detected.agent.name) : null; if (hostAgent) return ensureUniversalAgents([hostAgent]); const installed = await detectInstalledAgents(cwd); if (installe - src/agents.ts (28805 bytes)
import { homedir, platform } from 'os'; import { join } from 'path'; import { existsSync, readFileSync, readdirSync } from 'fs'; import { xdgConfig } from 'xdg-basedir'; import type { AgentConfig, AgentType } from './types.ts'; const home = homedir(); // Use xdg-basedir (not env-paths) to match OpenCode/Amp/Goose behavior on all platforms. const configHome = xdgConfig ?? join(home, '.config'); const codexHome = process.env.CODEX_HOME?.trim() || join(home, '.codex'); const claudeHome = process.env.CLAUDE_CONFIG_DIR?.trim() || join(home, '.claude'); const vibeHome = process.env.VIBE_HOME?.trim() || join(home, '.vibe'); const hermesHome = process.env.HERMES_HOME?.trim() || join(home, '.hermes'); const autohandHome = process.env.AUTOHAND_HOME?.trim() || join(home, '.autohand'); const grokHome = process.env.GROK_HOME?.trim() || join(home, '.grok'); const sarvamHome = process.env.SARVAM_HOME?.trim() || join(home, '.sarvam'); const reasonixHome = process.env.REASONIX_HOME?.trim() || (platform() === 'win32' ? join(process.env.APPDATA?.trim() || join(home, 'AppData', 'Roaming'), 'reasonix') : join(home, '.reasonix')); const zedAppDataHome = process.env.APPDATA?.trim(); const zedFlatpakConfigHome = process.env.FLATPAK_XDG_CONFIG_HOME?.trim(); function packageJsonHasDependency(packageJsonPath: string, dependencyName: string): boolean { try { const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as { dependencies?: Record<string, unknown>; devDependencies?: Record<string, unknown>; }; return !!( packageJson.dependencies?.[dependencyName] || packageJson.devDependencies?.[dependencyName] ); } catch { return false; } } export function getOpenClawGlobalSkillsDir( homeDir = home, pathExists: (path: string) => boolean = existsSync ) { if (pathExists(join(homeDir, '.openclaw'))) { return join(homeDir, '.openclaw/skills'); } if (pathExists(join(homeDir, '.clawdbot'))) { return join(homeDir, '.clawdbot/skills'); } if (pathExists(join(homeDir, '.moltbot'))) { return join(homeDir, '.moltbot/skills'); } return join(homeDir, '.openclaw/skills'); } export function isZCodeInstalled( homeDir = home, pathExists: (path: string) => boolean = existsSync ) { return pathExists(join(homeDir, '.zcode')) || pathExists('/Applications/ZCode.app'); } export function isKimchiInstalled( homeDir = home, pathExists: (path: string) => boolean = existsSync ) { return pathExists(join(homeDir, '.config', 'kimchi')); } export function isMiniMaxCodeInstalled( homeDir = home, pathExists: (path: string) => boolean = existsSync ) { return pathExists(join(homeDir, '.minimax')) || pathExists('/Applications/MiniMax Code.app'); } export function isPositAssistantInstalled( homeDir = home, pathExists: (path: string) => boolean = existsSync ) { // ~/.positai is the pre-rename config dir, still present on installs // that haven't launched a current version yet. return pathExists(join(homeDir, '.posit/assistant')) || pathExists(join(homeDir, '.positai')); } export const agents: Record<AgentType, AgentConfig> = { 'aider-desk': { name: 'aider-desk', displayName: 'AiderDesk', skillsDir: '.aider-desk/skills', globalSkillsDir: join(home, '.aider-desk/skills'), detectInstalled: async () => { return existsSync(join(home, '.aider-desk')); }, }, amp: { name: 'amp', displayName: 'Amp', skillsDir: '.agents/skills', globalSkillsDir: join(configHome, 'agents/skills'), detectInstalled: async () => { return existsSync(join(configHome, 'amp')); }, }, antigravity: { name: 'antigravity', displayName: 'Antigravity', skillsDir: '.agents/skills', // agy, the IDE and Antigravity 2.0 read global skills from ~/.gemini/config/skills, // and none of them reads ~/.agents/skills outside a workspace. globalSkillsDir: join(home, '.gemini/config/skills'), globalReadsCanonical: false, showInUniversalPrompt: false, detectInstalled: async () => { return existsSync(join(home, '.gemini/antigravity')); }, }, 'antigravity-cli': { name: 'antigravity-cli', displayName: 'Antigravity CLI', skillsDir: '.agents/skills', // agy, the IDE and Antigravity 2.0 read global skills from ~/.gemini/config/skills, // and none of them reads ~/.agents/skills outside a workspace. globalSkillsDir: join(home, '.gemini/config/skills'), globalReadsCanonical: false, showInUniversalPrompt: false, detectInstalled: async () => { return existsSync(join(home, '.gemini/antigravity-cli')); }, }, astrbot: { name: 'astrbot', displayName: 'AstrBot', skillsDir: 'data/skills', globalSkillsDir: join(home, '.astrbot/data/skills'), detectInstalled: async (cwd = process.cwd()) => { return existsSync(join(cwd, 'data/skills')) || existsSync(join(home, '.astrbot')); }, }, 'autohand-code': { name: 'autohand-code', displayName: 'Autohand Code CLI', skillsDir: '.autohand/skills', globalSkillsDir: join(autohandHome, 'skills'), detectInstalled: async () => { return existsSync(autohandHome); }, }, augment: { name: 'augment', displayName: 'Augment', skillsDir: '.augment/skills', globalSkillsDir: join(home, '.augment/skills'), detectInstalled: async () => { return existsSync(join(home, '.augment')); }, }, bob: { name: 'bob', displayName: 'IBM Bob', skillsDir: '.bob/skills', globalSkillsDir: join(home, '.bob/skills'), detectInstalled: async () => { return existsSync(join(home, '.bob')); }, }, 'claude-code': { name: 'claude-code', displayName: 'Claude Code', skillsDir: '.claude/skills', globalSkillsDir: join(claudeHome, 'skills'), // Preserve the established project-install behavior from #1138 and #1607. createProjectSkillsDirByDefault: true, detectInstalled: async () => { return existsSync(claudeHome); }, }, openclaw: { name: 'openclaw', displayName: 'OpenClaw', skillsDir: 'skills', globalSkillsDir: getOpenClawGlobalSkillsDir(), detectInstalled: async () => { return ( existsSync(join(home, '.openclaw')) || existsSync(join(home, '.clawdbot')) || existsSync(join(home, '.moltbot')) ); }, }, cline: { name: 'cline', displayName: 'Cline', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.agents', 'skills'), detectInstalled: async () => { return existsSync(join(home, '.cline')); }, }, 'codearts-agent': { name: 'codearts-agent', displayName: 'CodeArts Agent', skillsDir: '.codeartsdoer/skills', globalSkillsDir: join(home, '.codeartsdoer/skills'), detectInstalled: async () => { return existsSync(join(home, '.codeartsdoer')); }, }, codebuddy: { name: 'codebuddy', displayName: 'CodeBuddy', skillsDir: '.codebuddy/skills', globalSkillsDir: join(home, '.codebuddy/skills'), detectInstalled: async (cwd = process.cwd()) => { return existsSync(join(cwd, '.codebuddy')) || existsSync(join(home, '.codebuddy')); }, }, codemaker: { name: 'codemaker', displayName: 'Codemaker', skillsDir: '.codemaker/skills', globalSkillsDir: join(home, '.codemaker/skills'), detectInstalled: async () => { return existsSync(join(home, '.codemaker')); }, }, codestudio: { name: 'codestudio', displayName: 'Code Studio', skillsDir: '.codestudio/skills', globalSkillsDir: join(home, '.codestudio/skills'), detectInstalled: async () => { return existsSync(join(home, '.codestudio')); }, }, codex: { name: 'codex', displayName: 'Codex', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.agents', 'skills'), detectInstalled: async () => { return existsSync(codexHome) || existsSync('/etc/codex'); }, }, 'command-code': { name: 'command-code', displayName: 'Command Code', skillsDir: '.commandcode/skills', globalSkillsDir: join(home, '.commandcode/skills'), detectInstalled: async () => { return existsSync(join(home, '.commandcode')); }, }, continue: { name: 'continue', displayName: 'Continue', skillsDir: '.continue/skills', globalSkillsDir: join(home, '.continue/skills'), detectInstalled: async (cwd = process.cwd()) => { return existsSync(join(cwd, '.continue')) || existsSync(join(home, '.continue')); }, }, cortex: { name: 'cortex', displayName: 'Cortex Code', skillsDir: '.cortex/skills', globalSkillsDir: join(home, '.snowflake/cortex/skills'), detectInstalled: async () => { return existsSync(join(home, '.snowflake/cortex')); }, }, crush: { name: 'crush', displayName: 'Crush', skillsDir: '.crush/skills', globalSkillsDir: join(home, '.config/crush/skills'), detectInstalled: async () => { return existsSync(join(home, '.config/crush')); }, }, cursor: { name: 'cursor', displayName: 'Cursor', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.cursor/skills'), detectInstalled: async () => { return existsSync(join(home, '.cursor')); }, }, deepagents: { name: 'deepagents', displayName: 'Deep Agents', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.deepagents/agent/skills'), showInUniversalPrompt: false, detectInstalled: async () => { return existsSync(join(home, '.deepagents')); }, }, devin: { name: 'devin', displayName: 'Devin for Terminal', skillsDir: '.devin/skills', globalSkillsDir: join(configHome, 'devin/skills'), detectInstalled: async () => { return existsSync(join(configHome, 'devin')); }, }, dexto: { name: 'dexto', displayName: 'Dexto', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.agents/skills'), showInUniversalPrompt: false, detectInstalled: async () => { return existsSync(join(home, '.dexto')); }, }, droid: { name: 'droid', displayName: 'Droid', // Droid reads .agents/skills and ~/.agents/skills as compatibility // locations, so installing there avoids defining the same skill twice. // globalSkillsDir stays on ~/.factory/skills so `remove` still cleans up // skills placed there by earlier versions. skillsDir: '.agents/skills', globalSkillsDir: join(home, '.factory/skills'), detectInstalled: async () => { return existsSync(join(home, '.factory')); }, }, eve: { name: 'eve', displayName: 'Eve', skillsDir: 'agent/skills', globalSkillsDir: undefined, detectInstalled: async (cwd = process.cwd()) => { return ( existsSync(join(cwd, 'agent')) && packageJsonHasDependency(join(cwd, 'package.json'), 'eve') ); }, }, firebender: { name: 'firebender', displayName: 'Firebender', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.firebender/skills'), showInUniversalPrompt: false, detectInstalled: async () => { return existsSync(join(home, '.firebender')); }, }, forgecode: { name: 'forgecode', displayName: 'ForgeCode', skillsDir: '.forge/skills', globalSkillsDir: join(home, '.forge/skills'), detectInstalled: async () => { return existsSync(join(home, '.forge')); }, }, fx: { name: 'fx', displayName: 'fx', // fx discovers these shared roots natively alongside its own .fx/skills roots. skillsDir: '.agents/skills', globalSkillsDir: join(home, '.agents/skills'), detectInstalled: async () => { return existsSync(join(home, '.fx')); }, }, 'gemini-cli': { name: 'gemini-cli', displayName: 'Gemini CLI', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.gemini/skills'), detectInstalled: async () => { return existsSync(join(home, '.gemini')); }, }, 'github-copilot': { name: 'github-copilot', displayName: 'GitHub Copilot', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.copilot/skills'), detectInstalled: async () => { return existsSync(join(home, '.copilot')); }, }, goose: { name: 'goose', displayName: 'Goose', skillsDir: '.goose/skills', globalSkillsDir: join(configHome, 'goose/skills'), detectInstalled: async () => { return existsSync(join(configHome, 'goose')); }, }, grok: { name: 'grok', displayName: 'Grok Build', skillsDir: '.grok/skills', globalSkillsDir: join(grokHome, 'skills'), detectInstalled: async () => { return existsSync(grokHome); }, }, 'hermes-agent': { name: 'hermes-agent', displayName: 'Hermes Agent', skillsDir: '.hermes/skills', globalSkillsDir: join(hermesHome, 'skills'), detectInstalled: async () => { return existsSync(hermesHome); }, }, 'inference-sh': { name: 'inference-sh', displayName: 'inference.sh', skillsDir: '.inferencesh/skills', globalSkillsDir: join(home, '.inferencesh/skills'), detectInstalled: async () => { return existsSync(join(home, '.inferencesh')); }, }, jazz: { name: 'jazz', displayName: 'Jazz', skillsDir: '.jazz/skills', globalSkillsDir: join(home, '.jazz/skills'), detectInstalled: async (cwd = process.cwd()) => { return existsSync(join(home, '.jazz')) || existsSync(join(cwd, '.jazz')); }, }, junie: { name: 'junie', displayName: 'Junie', skillsDir: '.junie/skills', globalSkillsDir: join(home, '.junie/skills'), detectInstalled: async () => { return existsSync(join(home, '.junie')); }, }, 'iflow-cli': { name: 'iflow-cli', displayName: 'iFlow CLI', skillsDir: '.iflow/skills', globalSkillsDir: join(home, '.iflow/skills'), detectInstalled: async () => { return existsSync(join(home, '.iflow')); }, }, kilo: { name: 'kilo', displayName: 'Kilo Code', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.kilo/skills'), detectInstalled: async () => { // `.kilocode` is the legacy config directory, kept here so existing // installs are still detected. return existsSync(join(home, '.kilo')) || existsSync(join(home, '.kilocode')); }, }, kimchi: { name: 'kimchi', displayName: 'Kimchi', skillsDir: '.kimchi/skills', globalSkillsDir: join(home, '.config', 'kimchi', 'harness', 'skills'), detectInstalled: async () => { return isKimchiInstalled(); }, }, 'kimi-code-cli': { name: 'kimi-code-cli', displayName: 'Kimi Code CLI', skillsDir: '.agents/skills', globalSkillsDir: join(home, '.agents/skills'), detectInstalled: async () => { return existsSync(join(home, '.kimi-code')) || existsSync(join(home, '.kimi')); }, }, 'ki - src/api/agents.ts (1425 bytes)
import { agents as agentConfigs, detectInstalledAgents, isUniversalAgent } from '../agents.ts'; import type { AgentType } from '../types.ts'; import { isAgentAllowed, resolveConfig } from './config.ts'; import type { AgentInfo, BaseOptions, DetectAgentsResult } from './types.ts'; let agentInfos: readonly AgentInfo[] | undefined; function toAgentInfo(id: AgentType): AgentInfo { const config = agentConfigs[id]; return Object.freeze({ id, name: config.displayName, projectSkillsDir: config.skillsDir, globalSkillsDir: config.globalSkillsDir ?? null, universal: isUniversalAgent(id), }); } /** * Every supported agent, including `universal`: the neutral `.agents/skills` * target that universal agents read. It is never detected, only targeted. */ export function getSupportedAgents(): readonly AgentInfo[] { agentInfos ??= Object.freeze((Object.keys(agentConfigs) as AgentType[]).map(toAgentInfo)); return agentInfos; } /** Agents installed on this machine or in `cwd`, limited to those `config.agents` allows. */ export async function detectAgents(options: BaseOptions = {}): Promise<DetectAgentsResult> { const config = resolveConfig(options); options.signal?.throwIfAborted(); const detected = await detectInstalledAgents(config.cwd); options.signal?.throwIfAborted(); return { agents: detected.filter((id) => isAgentAllowed(id, config.agents)).map(toAgentInfo), }; } - src/api/config.ts (3231 bytes)
import { agents as agentConfigs } from '../agents.ts'; import type { AgentType } from '../types.ts'; import { diagnostics } from '../diagnostics.ts'; import type { AgentsConfig, BaseOptions, InstallMode, Scope, SkillsConfig } from './types.ts'; /** Every setting with its default applied. */ export interface ResolvedConfig { cwd: string; scope: Scope; mode: InstallMode; lockfile: boolean; fullDepth: boolean; includeInternal: boolean; duplicates: 'first' | 'error'; symlinks: 'follow' | 'reject'; telemetry: boolean; agents: AgentsConfig; } type Overrides = Omit<SkillsConfig, 'agents'>; /** * Merge settings for one call. Precedence per key: the call's options, then * `options.config`, then defaults. A future config file slots in between * `options.config` and the defaults. */ export function resolveConfig(options: BaseOptions & Overrides = {}): ResolvedConfig { const config = options.config ?? {}; const pick = <K extends keyof Overrides>(key: K): Overrides[K] => options[key] !== undefined ? options[key] : config[key]; const resolved: ResolvedConfig = { cwd: options.cwd ?? process.cwd(), scope: pick('scope') ?? 'project', mode: pick('mode') ?? 'auto', lockfile: pick('lockfile') ?? true, fullDepth: pick('fullDepth') ?? false, includeInternal: pick('includeInternal') ?? false, duplicates: pick('duplicates') ?? 'first', symlinks: pick('symlinks') ?? 'follow', telemetry: pick('telemetry') ?? true, agents: config.agents ?? {}, }; if (resolved.scope !== 'project' && resolved.scope !== 'global') { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'scope', expected: "'project' or 'global'", }); } if (!['auto', 'symlink', 'copy'].includes(resolved.mode)) { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'mode', expected: "'auto', 'symlink' or 'copy'", }); } if (resolved.duplicates !== 'first' && resolved.duplicates !== 'error') { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'duplicates', expected: "'first' or 'error'", }); } if (resolved.symlinks !== 'follow' && resolved.symlinks !== 'reject') { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'symlinks', expected: "'follow' or 'reject'", }); } assertKnownAgents(resolved.agents.include); assertKnownAgents(resolved.agents.exclude); assertKnownAgents(resolved.agents.default); return resolved; } function isKnownAgent(id: string): id is AgentType { return Object.hasOwn(agentConfigs, id); } /** Throw UNKNOWN_AGENT for any id that is not a supported agent. */ export function assertKnownAgents( ids: readonly string[] | undefined ): asserts ids is readonly AgentType[] | undefined { const unknown = ids?.filter((id) => !isKnownAgent(id)) ?? []; if (unknown.length > 0) { throw diagnostics.SKILLS_INVALID_AGENTS({ invalid: unknown, valid: Object.keys(agentConfigs) }); } } /** Whether `config.agents` allows targeting `agent`. */ export function isAgentAllowed(agent: string, config: AgentsConfig): boolean { if (config.include && !config.include.includes(agent)) return false; return !config.exclude?.includes(agent); } - src/api/install.ts (14734 bytes)
import { lstat, readdir } from 'fs/promises'; import { join, posix } from 'path'; import { defaultInstallMode, collectInstalled, installToTargets, nonInteractiveTargetAgents, recordGlobalLock, recordGlobalWellKnownLock, recordProjectLock, trackSourceInstall, type FetchedSource, type InstalledSkill, type InstallPlacement, type TargetInstallResult, renameSkill, validateRename, } from '../add.ts'; import { agents as agentConfigs } from '../agents.ts'; import type { Diagnostic } from 'nostics'; import { diagnostics, type DiagnosticCode } from '../diagnostics.ts'; import { readLocalLock } from '../local-lock.ts'; import { filterSkills, getSkillDisplayName } from '../skills.ts'; import { sanitizeName } from '../installer.ts'; import { flushTelemetry, setVersion } from '../telemetry.ts'; import type { AgentType, Skill } from '../types.ts'; import { version } from './version.ts'; import { assertKnownAgents, isAgentAllowed, resolveConfig, type ResolvedConfig } from './config.ts'; import { getFetchedSource, openSource } from './resolve.ts'; import { withWarnings } from '../warnings.ts'; import type { InstalledSkillTarget, InstallFailure, InstallOptions, InstallResult, SkippedSkillTarget, SkillSource, } from './types.ts'; /** * Install skills from `source` without prompting. `source` is a source string * (fetched and cleaned up by this call) or a SkillSource from resolveSource * (left for the caller to dispose). * * Throws a diagnostic when nothing can be attempted; failures of single skills * or agents are returned in `failed`. */ export async function installSkills( source: string | SkillSource, options: InstallOptions = {} ): Promise<InstallResult> { const config = resolveConfig(options); const requested = validateNames(options.skills, 'skills'); validateRenames(options.rename); assertKnownAgents(validateNames(options.agents, 'agents')); if (typeof source !== 'string' && options.ref !== undefined) { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'ref', expected: 'used with a source string; pass it to resolveSource() instead', }); } return withWarnings(options.onWarning, () => install(source, options, config, requested)); } async function install( source: string | SkillSource, options: InstallOptions, config: ResolvedConfig, requested: readonly string[] | undefined ): Promise<InstallResult> { if (config.scope === 'project' && config.lockfile) await assertReadableLock(config.cwd); options.signal?.throwIfAborted(); const owned = typeof source === 'string'; const handle = owned ? await openSource(source, config, requested ?? [], options) : source; try { const fetched = getFetchedSource(handle); const skills = applyRenames(selectSkills(fetched, requested), options.rename); if (config.duplicates === 'error') rejectDuplicates(handle, skills); if (config.symlinks === 'reject') await rejectSymlinks(fetched, skills); const { targets, failures } = await resolveTargets(options.agents, config, skills); options.signal?.throwIfAborted(); const explicit = new Set<AgentType>( (options.agents ?? config.agents.default ?? []) as AgentType[] ); const placement: InstallPlacement = { global: config.scope === 'global', cwd: config.cwd, targets: targets.map((agent) => ({ agent })), mode: config.mode === 'auto' ? defaultInstallMode(targets.map((agent) => ({ agent }))) : config.mode, createMissingAgentRoot: (agent) => explicit.has(agent), }; options.onProgress?.({ type: 'install:start', skills: skills.length, agents: targets.length }); const results = await installToTargets(fetched.resolved!, skills, placement); const result = buildResult(handle, results, failures, config); options.onProgress?.({ type: 'install:done', installed: result.installed.length, failed: result.failed.length, }); const installed = await collectInstalled(skills, results); if (config.lockfile && installed.length > 0) { await recordLock(fetched, installed, config, config.mode === 'copy'); } if (config.telemetry && installed.length > 0) { setVersion(version); await trackSourceInstall( fetched, installed.map(({ skill }) => skill), { agents: targets, global: placement.global, ...(options.metadata && { metadata: JSON.stringify(options.metadata) }), } ); await flushTelemetry(3000); } return result; } finally { if (owned) await handle.dispose(); } } function validateNames( names: readonly string[] | undefined, option: string ): readonly string[] | undefined { if (names === undefined) return undefined; if (!Array.isArray(names) || names.some((name) => typeof name !== 'string' || name === '')) { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: option, expected: 'an array of non-empty strings', }); } return names; } /** Throws unless `rename` maps skill names to safe folder names. */ function validateRenames(rename: unknown): void { if (rename === undefined) return; if (typeof rename !== 'object' || rename === null || Array.isArray(rename)) { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'rename', expected: 'an object mapping skill names to new names', }); } for (const [from, to] of Object.entries(rename)) { const option = `rename[${JSON.stringify(from)}]`; const error = typeof to === 'string' ? validateRename(to, option) : diagnostics.SKILLS_INVALID_OPTION_VALUE({ option, expected: 'a string' }); if (error) throw error; } } /** * `skills` with the `rename` map applied. Throws before anything is written * when a key matches no skill or several, or when two skills would share a * name (one renamed onto another, or two renamed to the same name). */ function applyRenames( skills: Skill[], rename: Readonly<Record<string, string>> | undefined ): Skill[] { if (!rename) return skills; const newNames = new Map<Skill, string>(); for (const [from, to] of Object.entries(rename)) { const matches = filterSkills(skills, [from]); if (matches.length === 0) { throw diagnostics.SKILLS_NO_MATCHING_SKILLS({ requested: [from], available: skills.map(getSkillDisplayName), }); } if (matches.length > 1) throw diagnostics.SKILLS_AMBIGUOUS_SKILL_SELECTOR({ selector: from }); newNames.set(matches[0]!, to); } const renamed = skills.map((skill) => { const name = newNames.get(skill); return name === undefined ? skill : renameSkill(skill, name); }); // Folder name -> whether a renamed skill claimed it const claimed = new Map<string, boolean>(); for (const skill of renamed) { const key = sanitizeName(getSkillDisplayName(skill)); const isRenamed = skill.renamedFrom !== undefined; if (claimed.has(key) && (isRenamed || claimed.get(key))) { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'rename', expected: `a map to distinct names, but two skills would be installed as ${key}`, }); } claimed.set(key, isRenamed || (claimed.get(key) ?? false)); } return renamed; } /** Throws SKILLS_INVALID_LOCAL_LOCK before anything is written when the project lock is unusable. */ async function assertReadableLock(cwd: string): Promise<void> { await readLocalLock(cwd); } /** The skills of `fetched` to install: all, or those `requested` names (`*` means all). */ function selectSkills(fetched: FetchedSource, requested: readonly string[] | undefined): Skill[] { const available = fetched.resolved!.skills; const names = requested ?? (fetched.parsed.skillFilter ? [fetched.parsed.skillFilter] : undefined); if (!names || names.length === 0 || names.includes('*')) return available; const ambiguous = names.find((name) => filterSkills(available, [name]).length > 1); if (ambiguous !== undefined) { throw diagnostics.SKILLS_AMBIGUOUS_SKILL_SELECTOR({ selector: ambiguous }); } const missing = names.filter((name) => filterSkills(available, [name]).length === 0); if (missing.length > 0) { throw diagnostics.SKILLS_NO_MATCHING_SKILLS({ requested: missing, available: available.map(getSkillDisplayName), }); } return filterSkills(available, [...names]); } /** * The agents to install into, after `config.agents` limits. Agents the call * names but cannot use become failures; agents chosen automatically are * dropped silently when they cannot be used. */ async function resolveTargets( requested: readonly string[] | undefined, config: ResolvedConfig, skills: Skill[] ): Promise<{ targets: AgentType[]; failures: InstallFailure[] }> { const named = (requested ?? config.agents.default) as readonly AgentType[] | undefined; const candidates = named ? [...new Set(named)] : await nonInteractiveTargetAgents(config.cwd); const global = config.scope === 'global'; const targets: AgentType[] = []; const failures: InstallFailure[] = []; const fail = (agent: AgentType, diagnostic: Diagnostic<unknown, DiagnosticCode>) => { if (!named) return; for (const skill of skills) { failures.push(failure(getSkillDisplayName(skill), agent, diagnostic)); } }; for (const agent of candidates) { if (!isAgentAllowed(agent, config.agents)) { fail(agent, diagnostics.SKILLS_AGENT_NOT_ALLOWED({ agents: [agent] })); } else if (global && agentConfigs[agent].globalSkillsDir === undefined) { fail( agent, diagnostics.SKILLS_GLOBAL_INSTALL_UNSUPPORTED({ agent: agentConfigs[agent].displayName }) ); } else { targets.push(agent); } } if (targets.length === 0) { throw diagnostics.SKILLS_NO_TARGET_AGENTS(); } return { targets, failures }; } function failure( skill: string, agent: string, diagnostic: Diagnostic<unknown, DiagnosticCode> ): InstallFailure { return Object.freeze({ skill, agent, code: diagnostic.code, message: diagnostic.message, }); } function buildResult( handle: SkillSource, results: TargetInstallResult[], failures: InstallFailure[], config: ResolvedConfig ): InstallResult { const installed: InstalledSkillTarget[] = []; const skipped: SkippedSkillTarget[] = []; const failed: InstallFailure[] = [...failures]; for (const r of results) { if (!r.success) { const diagnostic = diagnostics.SKILLS_INSTALL_FAILED({ skill: r.skill, agent: r.agentType, detail: r.error ?? 'unknown error', }); failed.push(failure(r.skill, r.agentType, diagnostic)); } else if (r.skipReason === 'missing-agent-project-directory') { skipped.push({ skill: r.skill, agent: r.agentType, reason: 'missing-agent-directory' }); } else { installed.push( Object.freeze({ skill: r.skill, agent: r.agentType, scope: config.scope, mode: r.mode === 'copy' || r.symlinkFailed ? 'copy' : 'symlink', path: r.path, ...(r.canonicalPath && { canonicalPath: r.canonicalPath }), }) ); } } return Object.freeze({ source: handle.source, installed: Object.freeze(installed), skipped: Object.freeze(skipped), failed: Object.freeze(failed), }); } async function recordLock( fetched: FetchedSource, installed: InstalledSkill[], config: ResolvedConfig, explicitCopy: boolean ): Promise<void> { const lockedInstallMode = explicitCopy ? { installMode: 'copy' as const } : {}; try { if (config.scope === 'project') { await recordProjectLock(fetched, installed, undefined, { cwd: config.cwd, ...lockedInstallMode, }); } else if (installed.some(({ skill }) => 'wellKnown' in skill)) { await recordGlobalWellKnownLock(fetched.parsed.url, installed); } else { await recordGlobalLock( fetched, installed.map(({ skill }) => skill), { ...lockedInstallMode, onWriteFailure: (_skill, error) => { throw error; }, } ); } } catch (error) { throw diagnostics.SKILLS_LOCK_WRITE_FAILED({ detail: error instanceof Error ? error.message : String(error), cause: error, }); } } /** With `duplicates: 'error'`, refuse selected skills whose name more than one folder declares. */ function rejectDuplicates(handle: SkillSource, skills: Skill[]): void { const names = new Set(skills.map(getSkillDisplayName)); const duplicated = handle.skills.filter((info) => names.has(info.name) && info.duplicates); if (duplicated.length === 0) return; throw diagnostics.SKILLS_DUPLICATE_SKILL_NAME({ skills: duplicated.map( (info) => `${info.name}: ${[info.path ?? '?', ...info.duplicates!].join(', ')}` ), }); } /** With `symlinks: 'reject'`, refuse selected skills that contain a symlink. */ async function rejectSymlinks(fetched: FetchedSource, skills: Skill[]): Promise<void> { const found: string[] = []; for (const skill of skills) { for (const link of await findSymlinks(fetched, skill)) { found.push(`${getSkillDisplayName(skill)}: ${link}`); } } if (found.length > 0) { throw diagnostics.SKILLS_SKILL_CONTAINS_SYMLINKS({ links: found }); } } /** Symlinks inside a skill folder, relative to it (`.` when the folder itself is one). */ async function findSymlinks(fetched: FetchedSource, skill: Skill): Promise<string[]> { if ('repoPath' in skill && typeof skill.repoPath === 'string') { // Fast-path GitHub skills have no checkout; the tree records symlinks as mode 120000. const dir = posix.dirname(skill.repoPath); const prefix = dir === '.' ? '' : `${dir}/`; return (fetched.resolved?.blobResult?.tree.tree ?? []) .filter((entry) => entry.mode === '120000' && entry.path.startsWith(prefix)) .map((entry) => entry.path.slice(prefix.length)); } if (!skill.path) return []; // Well-known skills are fetched as plain files. const links: string[] = []; if ((await lstat(skill.path)).isSymbolicLink()) return ['.']; const walk = async (dir: string, rel: string): Promise<void> => { for (const entry of await readdir(dir, { withFileTypes: true })) { const entryRel = rel ? `${rel}/${entry.name}` : entry.name; if (entry.isSymbolicLink()) links.push(entryRel); // .git is never copied, so links inside it are irrelevant. else if (entry.isDirectory() && entry.name !== '.git') { await walk(join(dir, entry.name), entryRel); } } }; await walk(skill.path, ''); return links; } - src/api/list.ts (2529 bytes)
import { listInstalledSkills } from '../installer.ts'; import { readLocalLock } from '../local-lock.ts'; import { readSkillLock } from '../skill-lock.ts'; import { assertKnownAgents, resolveConfig } from './config.ts'; import { diagnostics } from '../diagnostics.ts'; import { withWarnings } from '../warnings.ts'; import type { InstalledSkillInfo, ListOptions, ListResult, Scope } from './types.ts'; /** Skills installed in the project (`cwd`), globally, or both. */ export function listSkills(options: ListOptions = {}): Promise<ListResult> { return withWarnings(options.onWarning, () => list(options)); } async function list(options: ListOptions): Promise<ListResult> { const { cwd } = resolveConfig({ cwd: options.cwd, config: options.config }); const scope = options.scope ?? 'all'; if (scope !== 'all' && scope !== 'project' && scope !== 'global') { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'scope', expected: "'project', 'global' or 'all'", }); } assertKnownAgents(options.agents); options.signal?.throwIfAborted(); const found = await listInstalledSkills({ cwd, ...(scope !== 'all' && { global: scope === 'global' }), ...(options.agents && { agentFilter: [...options.agents] }), }); options.signal?.throwIfAborted(); const locked: Record<Scope, Record<string, LockedSkill>> = { project: scope === 'global' ? {} : await lockedSkills(() => readLocalLock(cwd)), global: scope === 'project' ? {} : await lockedSkills(readSkillLock), }; return Object.freeze({ skills: Object.freeze( found.map((skill): InstalledSkillInfo => Object.freeze({ name: skill.name, description: skill.description, scope: skill.scope, path: skill.canonicalPath || skill.path, agents: Object.freeze([...skill.agents]), ...lockInfo(locked[skill.scope][skill.name]), }) ) ), }); } interface LockedSkill { source: string; skillName?: string; } function lockInfo( entry: LockedSkill | undefined ): Pick<InstalledSkillInfo, 'source' | 'renamedFrom'> { if (!entry) return {}; return { source: entry.source, ...(entry.skillName && { renamedFrom: entry.skillName }) }; } /** Lock entry per skill name from a lock file; an unreadable lock yields none. */ async function lockedSkills( read: () => Promise<{ skills: Record<string, LockedSkill> }> ): Promise<Record<string, LockedSkill>> { try { return (await read()).skills; } catch { return {}; } } - src/api/remove.ts (4561 bytes)
import { agents as agentConfigs } from '../agents.ts'; import { diagnostics } from '../diagnostics.ts'; import { readLocalLock } from '../local-lock.ts'; import { findGloballyTrackedSkills, findUntrackedSkills, removeInstalledSkills, resolveSkillsToRemove, scanInstalledSkillNames, trackRemovals, } from '../remove.ts'; import { readSkillLock } from '../skill-lock.ts'; import { flushTelemetry, setVersion } from '../telemetry.ts'; import type { AgentType } from '../types.ts'; import { version } from './version.ts'; import { assertKnownAgents, isAgentAllowed, resolveConfig } from './config.ts'; import { warn, withWarnings } from '../warnings.ts'; import type { RemoveFailure, RemoveOptions, RemoveResult } from './types.ts'; /** * Remove installed skills by name (or by the source recorded in the lock * file; `*` removes every skill the scope's lock file tracks, skipping * untracked dirs with a SKILLS_REMOVE_UNTRACKED_SKIPPED warning). Without `agents`, skills are * removed from every agent `config.agents` allows. A skill's shared copy and * lock entry are kept while another installed agent still uses it. */ export function removeSkills( names: readonly string[], options: RemoveOptions = {} ): Promise<RemoveResult> { return withWarnings(options.onWarning, () => remove(names, options)); } async function remove(names: readonly string[], options: RemoveOptions): Promise<RemoveResult> { const config = resolveConfig(options); if (!Array.isArray(names) || names.some((name) => typeof name !== 'string' || name === '')) { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'names', expected: 'an array of non-empty strings', }); } assertKnownAgents(options.agents); const disallowed = options.agents?.filter((agent) => !isAgentAllowed(agent, config.agents)); if (disallowed && disallowed.length > 0) { throw diagnostics.SKILLS_AGENT_NOT_ALLOWED({ agents: disallowed }); } const targetAgents = ((options.agents ?? Object.keys(agentConfigs)) as AgentType[]).filter( (agent) => isAgentAllowed(agent, config.agents) ); if (targetAgents.length === 0) { throw diagnostics.SKILLS_NO_TARGET_AGENTS(); } options.signal?.throwIfAborted(); const global = config.scope === 'global'; const { cwd } = config; const installed = await scanInstalledSkillNames(global, cwd); const lockEntries = global ? (await readSkillLock()).skills : (await readProjectLock(cwd)).skills; const lockKeys = Object.keys(lockEntries); const sourceByKey = Object.fromEntries(lockKeys.map((key) => [key, lockEntries[key]?.source])); const resolve = (requested: string[]) => resolveSkillsToRemove(requested, installed, lockKeys, sourceByKey); const all = names.includes('*'); const notFound = all ? [] : names.filter((name) => resolve([name]).length === 0); // `*` only removes skills the lock tracks; user-authored dirs are skipped (#604). let selected = all ? resolve(lockKeys) : resolve([...names]); if (all) { const untracked = findUntrackedSkills(installed, lockKeys); if (untracked.length > 0) warn(diagnostics.SKILLS_REMOVE_UNTRACKED_SKIPPED({ skills: untracked })); } const failed: RemoveFailure[] = []; if (!global) { const tracked = new Set(await findGloballyTrackedSkills(selected, cwd)); for (const skill of tracked) { const diagnostic = diagnostics.SKILLS_REMOVE_GLOBALLY_TRACKED({ skills: [skill] }); failed.push({ skill, code: diagnostic.code, message: diagnostic.message }); } selected = selected.filter((skill) => !tracked.has(skill)); } options.signal?.throwIfAborted(); const results = await removeInstalledSkills(selected, { global, cwd, targetAgents, lockfile: config.lockfile, }); for (const r of results) { if (!r.success) { const diagnostic = diagnostics.SKILLS_REMOVE_FAILED({ skill: r.skill, detail: r.error ?? 'unknown error', }); failed.push({ skill: r.skill, code: diagnostic.code, message: diagnostic.message, }); } } if (config.telemetry) { setVersion(version); trackRemovals(results, targetAgents, global); await flushTelemetry(3000); } return Object.freeze({ removed: Object.freeze(results.filter((r) => r.success).map((r) => r.skill)), notFound: Object.freeze(notFound), failed: Object.freeze(failed), }); } /** Throws SKILLS_INVALID_LOCAL_LOCK when the project lock is unusable. */ function readProjectLock(cwd: string) { return readLocalLock(cwd); } - src/api/resolve.ts (7809 bytes)
import { existsSync } from 'fs'; import { posix, relative, sep } from 'path'; import { fetchSource, releaseSource, type FetchedSource } from '../add.ts'; import { diagnostics } from '../diagnostics.ts'; import { getHeadCommit } from '../git.ts'; import { getSkillDisplayName } from '../skills.ts'; import { lookupGitHubRepo, parseSource, withCanonicalGitHubRepo } from '../source-parser.ts'; import type { ParsedSource, Skill } from '../types.ts'; import { resolveConfig, type ResolvedConfig } from './config.ts'; import type { ResolveOptions, SkillInfo, SkillSource, SourceInfo } from './types.ts'; import { withWarnings } from '../warnings.ts'; interface SourceState { fetched: FetchedSource; disposed: boolean; } const GIT_SOURCE_TYPES: ReadonlySet<ParsedSource['type']> = new Set(['github', 'gitlab', 'git']); /** Internal state of each SkillSource, kept off the public object. */ const sourceStates = new WeakMap<SkillSource, SourceState>(); function parseSourceInput(input: string, cwd: string): ParsedSource { if (typeof input !== 'string' || input.trim() === '') { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'source', expected: 'a non-empty string', }); } return parseSource(input, { cwd }); } function toSourceInfo(input: string, parsed: ParsedSource, commit?: string): SourceInfo { return Object.freeze({ input, type: parsed.type, url: parsed.url, ...(parsed.ref && { ref: parsed.ref }), ...(commit && { commit }), ...(parsed.subpath && { subpath: parsed.subpath }), }); } /** * Fetch `source` (a GitHub shorthand, git or HTTPS URL, or local path) and * discover its skills without installing anything. Call `dispose()` on the * result, or pass it to `installSkills`, which keeps it usable. */ export async function resolveSource( source: string, options: ResolveOptions = {} ): Promise<SkillSource> { const config = resolveConfig(options); return withWarnings(options.onWarning, () => openSource(source, config, [], options)); } /** Fetch `input` and wrap it in a SkillSource; `requested` names guide discovery. */ export async function openSource( input: string, config: ResolvedConfig, requested: readonly string[], options: Pick<ResolveOptions, 'signal' | 'onProgress' | 'ref'> ): Promise<SkillSource> { const parsed = withRef(parseSourceInput(input, config.cwd), options.ref); options.signal?.throwIfAborted(); if (parsed.type === 'local' && !existsSync(parsed.localPath!)) { throw diagnostics.SKILLS_LOCAL_PATH_NOT_FOUND({ path: parsed.localPath! }); } const skills = requested.length > 0 ? [...requested] : parsed.skillFilter ? [parsed.skillFilter] : []; options.onProgress?.({ type: 'resolve:start', source: input }); const repoInfo = lookupGitHubRepo(parsed); const fetched = await fetchSource({ parsed, skills, fullDepth: config.fullDepth, includeInternal: config.includeInternal || skills.length > 0, // Kept so duplicates can be reported; only the first of each name is installed. includeDuplicateNames: true, }); if (!fetched.resolved) throw fetchError(input, fetched); // Report a renamed GitHub repo under its current name. fetched.parsed = withCanonicalGitHubRepo(parsed, (await repoInfo)?.fullName); const handle = await createSkillSource(input, fetched); if (options.signal?.aborted) { await handle.dispose(); options.signal?.throwIfAborted(); } if (handle.skills.length === 0) { await handle.dispose(); throw diagnostics.SKILLS_NO_VALID_SKILLS(); } options.onProgress?.({ type: 'resolve:done', source: handle.source, skills: handle.skills.length, }); return handle; } /** Apply a `ref` option, which only git sources accept. */ function withRef(parsed: ParsedSource, ref: string | undefined): ParsedSource { if (ref === undefined) return parsed; if (typeof ref !== 'string' || ref.trim() === '') { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'ref', expected: 'a non-empty string', }); } if (!GIT_SOURCE_TYPES.has(parsed.type)) { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'ref', expected: 'used only with git sources', }); } return { ...parsed, ref }; } /** * The error behind a failed fetch: the original diagnostic (git, download, * archive, well-known), or SKILLS_SOURCE_FETCH_FAILED wrapping anything else. */ function fetchError(input: string, fetched: FetchedSource): Error { const { cause } = fetched; if (diagnostics.is(cause)) return cause; return diagnostics.SKILLS_SOURCE_FETCH_FAILED({ source: input, detail: fetched.error ?? 'unknown error', cause, }); } async function createSkillSource(input: string, raw: FetchedSource): Promise<SkillSource> { const { fetched, duplicates } = dedupeSkills(raw); const skills: SkillInfo[] = fetched.resolved!.skills.map((skill) => { const path = skillPath(fetched, skill); const others = duplicates.get(skill); return Object.freeze({ name: getSkillDisplayName(skill), description: skill.description, ...(path !== undefined && { path }), ...(others && { duplicates: Object.freeze(others) }), ...(skill.pluginName && { pluginName: skill.pluginName }), ...(skill.metadata && { metadata: Object.freeze({ ...skill.metadata }) }), }); }); const { resolved, parsed } = fetched; const commit = GIT_SOURCE_TYPES.has(parsed.type) && resolved!.tempDir && !resolved!.blobResult ? ((await getHeadCommit(resolved!.tempDir)) ?? undefined) : undefined; const state: SourceState = { fetched, disposed: false }; const handle: SkillSource = Object.freeze({ source: toSourceInfo(input, parsed, commit), skills: Object.freeze(skills), async dispose() { if (state.disposed) return; state.disposed = true; await releaseSource(fetched); }, }); sourceStates.set(handle, state); return handle; } /** * Keep the first skill of each name, as `skills add` does, and record the * paths of the others. (Discovery never follows symlinked folders, so a * symlinked copy is not seen at all.) */ function dedupeSkills(fetched: FetchedSource): { fetched: FetchedSource; duplicates: Map<Skill, string[]>; } { const resolved = fetched.resolved!; const first = new Map<string, Skill>(); const duplicates = new Map<Skill, string[]>(); for (const skill of resolved.skills) { const name = getSkillDisplayName(skill); const winner = first.get(name); if (!winner) { first.set(name, skill); continue; } const path = skillPath(fetched, skill); if (path !== undefined) duplicates.set(winner, [...(duplicates.get(winner) ?? []), path]); } return { fetched: { ...fetched, resolved: { ...resolved, skills: [...first.values()] } }, duplicates, }; } /** A skill's folder relative to the source root, `/`-separated; undefined when unknown. */ function skillPath({ resolved }: FetchedSource, skill: Skill): string | undefined { if ('repoPath' in skill && typeof skill.repoPath === 'string') { return posix.dirname(skill.repoPath); } const root = resolved?.rootDir; if (!root || !skill.path) return undefined; const rel = relative(root, skill.path); return rel === '' ? '.' : rel.split(sep).join('/'); } /** The fetched source behind a handle returned by resolveSource. */ export function getFetchedSource(handle: SkillSource): FetchedSource { const state = sourceStates.get(handle); if (!state) { throw diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: 'source', expected: 'a source string or a SkillSource returned by resolveSource()', }); } if (state.disposed) { throw diagnostics.SKILLS_SOURCE_DISPOSED(); } return state.fetched; } - src/api/types.ts (10394 bytes)
/** * Public types of the `skills` programmatic API. * * These are written by hand and never alias internal types, so internal * refactors cannot change the public contract by accident. Every change here * shows up in the tsnapi snapshot (`__snapshots__/tsnapi`). */ import type { Diagnostic } from 'nostics'; import type { DiagnosticCode } from '../diagnostics.ts'; export type { Diagnostic, DiagnosticCode }; /** Where skills are installed: the project (`cwd`) or the user's home. */ export type Scope = 'project' | 'global'; /** * How skills are placed into agent directories. `auto` symlinks from one * canonical copy when targets span several skills directories and copies * otherwise, the same choice `skills add -y` makes. */ export type InstallMode = 'auto' | 'symlink' | 'copy'; /** The kind of source a skill came from. */ export type SourceType = 'github' | 'gitlab' | 'git' | 'local' | 'well-known' | 'download'; /** Settings that can come from shared config and be overridden per call. */ export interface InstallSettings { /** @default 'project' */ scope?: Scope; /** @default 'auto' */ mode?: InstallMode; /** Record installs and removals in `skills-lock.json` or the global lock. @default true */ lockfile?: boolean; /** Search the whole source tree for skills, not only the usual locations. @default false */ fullDepth?: boolean; /** Include skills marked `metadata.internal`. @default false */ includeInternal?: boolean; /** * When a source has several folders declaring the same skill name: `first` * installs the first one found (as `skills add` does); `error` makes * installSkills throw SKILLS_DUPLICATE_SKILL_NAME before writing anything when a selected * skill's name is declared more than once. @default 'first' */ duplicates?: 'first' | 'error'; /** * Symlinks inside a skill folder: `follow` copies what in-skill links point * to and skips unsafe ones with a warning; `reject` makes installSkills throw * SKILLS_SKILL_CONTAINS_SYMLINKS before writing anything when a selected skill contains a * symlink. @default 'follow' */ symlinks?: 'follow' | 'reject'; } /** Which agents may be targeted, and which ones to target when a call names none. */ export interface AgentsConfig { /** When set, only these agents may be targeted. */ include?: readonly string[]; /** These agents are never targeted. */ exclude?: readonly string[]; /** Agents to target when a call names none, instead of detecting them. */ default?: readonly string[]; } /** * Shared settings for a project or user. JSON-serializable by design (no * functions, no secrets) so it can later be read from a `skills.config` file. * The library never reads such files itself; pass the config explicitly. */ export interface SkillsConfig extends InstallSettings { agents?: AgentsConfig; /** * Send anonymous usage telemetry, as the CLI does. Setting `DISABLE_TELEMETRY` * or `DO_NOT_TRACK` always turns it off. @default true */ telemetry?: boolean; } /** Progress reported while an operation runs. */ export type ProgressEvent = | { readonly type: 'resolve:start'; readonly source: string } | { readonly type: 'resolve:done'; readonly source: SourceInfo; readonly skills: number } | { readonly type: 'install:start'; readonly skills: number; readonly agents: number } | { readonly type: 'install:done'; readonly installed: number; readonly failed: number }; export type ProgressHandler = (event: ProgressEvent) => void; /** * Receives non-fatal problems as diagnostics, the same ones the CLI prints: * SKILLS_SKILL_SKIPPED (an invalid SKILL.md was not discovered) and * SKILLS_BROKEN_SYMLINK / SKILLS_SYMLINK_OUTSIDE_SKILL / SKILLS_SYMLINK_CYCLE * (an unsafe symlink inside a skill was not copied). */ export type WarningHandler = (warning: Diagnostic<unknown>) => void; /** Runtime context shared by every operation. Never comes from a config file. */ export interface BaseOptions { /** Project directory. @default process.cwd() */ cwd?: string; /** Cancels the operation; checked between steps. */ signal?: AbortSignal; onProgress?: ProgressHandler; /** Receives non-fatal problems. Without it they are dropped silently. */ onWarning?: WarningHandler; /** Shared settings. Options passed to a call take precedence over these. */ config?: SkillsConfig; } /** A supported agent. */ export interface AgentInfo { /** * Identifier used in `agents` options, e.g. `claude-code`. `universal` is a * neutral target: `.agents/skills` in the project (or its global * equivalent), which every universal agent reads. */ readonly id: string; readonly name: string; /** Skills directory relative to the project root. */ readonly projectSkillsDir: string; /** Absolute global skills directory, or null when the agent has none. */ readonly globalSkillsDir: string | null; /** Reads skills from the shared `.agents/skills` directory. */ readonly universal: boolean; } export interface DetectAgentsResult { /** Installed agents allowed by `config.agents`. */ readonly agents: readonly AgentInfo[]; } /** A parsed skill source. */ export interface SourceInfo { /** The source string as given. */ readonly input: string; readonly type: SourceType; /** Repository or download URL, or the absolute path of a local source. */ readonly url: string; readonly ref?: string; /** * Commit that was checked out, for git sources that were cloned. Absent for * other sources and for GitHub repositories read through the fast path, * which is only used when no `ref` is given. */ readonly commit?: string; readonly subpath?: string; } /** A skill found in a source. */ export interface SkillInfo { readonly name: string; readonly description: string; /** * The skill folder relative to the source root, `/`-separated (`.` for a * skill at the root). Absent for well-known sources, which have no tree. */ readonly path?: string; /** * Other folders in the source that declare the same name. They are ignored: * the first definition wins, in discovery order, as with `skills add`. */ readonly duplicates?: readonly string[]; readonly pluginName?: string; readonly metadata?: Readonly<Record<string, unknown>>; } /** * A fetched source. It owns a temporary clone or download until disposed; * pass it to `installSkills` to install without fetching again. */ export interface SkillSource { readonly source: SourceInfo; readonly skills: readonly SkillInfo[]; /** Remove the temporary files. Safe to call more than once. */ dispose(): Promise<void>; } export interface ResolveOptions extends BaseOptions { /** * Branch, tag, or full commit SHA to check out, for git sources. Overrides * a `#ref` in the source string. */ ref?: string; fullDepth?: boolean; includeInternal?: boolean; } export interface InstallOptions extends BaseOptions, InstallSettings { /** Branch, tag, or commit SHA, when `source` is a string. See ResolveOptions.ref. */ ref?: string; /** Skill names to install. @default all skills in the source */ skills?: readonly string[]; /** * Install skills under new names, keyed by the name the source uses (matched * like `skills`): `{ shadcn: 'shadcn-ui' }`. The new name is used for the * folder, the lock entry and the SKILL.md `name`; the lock remembers the * source name, so update and restore keep the new name. Each key must match * one skill being installed, and no two skills may end up with one name. */ rename?: Readonly<Record<string, string>>; /** * Agents to install into; each must be allowed by `config.agents`. * @default `config.agents.default`, else the agents `skills add -y` picks */ agents?: readonly string[]; telemetry?: boolean; /** JSON-serializable data attached to install telemetry. */ metadata?: Readonly<Record<string, unknown>>; } /** A skill written into one agent's directory. */ export interface InstalledSkillTarget { readonly skill: string; readonly agent: string; readonly scope: Scope; readonly mode: 'symlink' | 'copy'; /** Where the agent reads the skill from. */ readonly path: string; /** The shared copy agents link to, when there is one. */ readonly canonicalPath?: string; } /** A skill that was not installed into an agent because its directory is missing. */ export interface SkippedSkillTarget { readonly skill: string; readonly agent: string; readonly reason: 'missing-agent-directory'; } export interface InstallFailure { readonly skill: string; readonly agent: string; readonly code: DiagnosticCode; readonly message: string; } export interface InstallResult { readonly source: SourceInfo; readonly installed: readonly InstalledSkillTarget[]; readonly skipped: readonly SkippedSkillTarget[]; readonly failed: readonly InstallFailure[]; } export interface ListOptions extends BaseOptions { /** @default 'all' */ scope?: Scope | 'all'; /** Only skills installed for these agents. */ agents?: readonly string[]; } /** A skill installed on disk. */ export interface InstalledSkillInfo { readonly name: string; readonly description: string; readonly scope: Scope; /** The skill directory (the canonical copy when agents share one). */ readonly path: string; /** Detected agents that have the skill. */ readonly agents: readonly string[]; /** Source recorded in the lock file, when the skill is tracked there. */ readonly source?: string; /** The name the source publishes the skill under, when it was installed under another name. */ readonly renamedFrom?: string; } export interface ListResult { readonly skills: readonly InstalledSkillInfo[]; } export interface RemoveOptions extends BaseOptions { /** @default 'project' */ scope?: Scope; /** Remove only from these agents. @default every agent */ agents?: readonly string[]; lockfile?: boolean; telemetry?: boolean; } export interface RemoveFailure { readonly skill: string; readonly code: DiagnosticCode; readonly message: string; } export interface RemoveResult { /** Skills removed from the requested agents. */ readonly removed: readonly string[]; /** Requested names that matched no installed or locked skill. */ readonly notFound: readonly string[]; readonly failed: readonly RemoveFailure[]; } - src/api/version.ts (171 bytes)
import packageJson from '../../package.json' with { type: 'json' }; /** Version of the installed `skills` package. */ export const version: string = packageJson.version; - src/archive.ts (15004 bytes)
import { crc32, inflateRawSync } from 'node:zlib'; import { diagnostics } from './diagnostics.ts'; const ZIP_LOCAL_FILE_HEADER = 0x04034b50; const ZIP_CENTRAL_DIRECTORY_HEADER = 0x02014b50; const ZIP_END_OF_CENTRAL_DIRECTORY = 0x06054b50; const ZIP64_END_OF_CENTRAL_DIRECTORY = 0x06064b50; const ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR = 0x07064b50; const ZIP_END_MIN_SIZE = 22; const ZIP_MAX_COMMENT_SIZE = 0xffff; const CP437_HIGH_BYTES = [ 'ÇüéâäàåçêëèïîìÄÅ', 'ÉæÆôöòûùÿÖÜ¢£¥₧ƒ', 'áíóúñѪº¿⌐¬½¼¡«»', '░▒▓│┤╡╢╖╕╣║╗╝╜╛┐', '└┴┬├─┼╞╟╚╔╩╦╠═╬╧', '╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀', 'αßΓπΣσµτΦΘΩδ∞φε∩', '≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\u00a0', ].join(''); export interface ArchiveLimits { maxExtractedBytes: number; maxEntries: number; } function ensureRange(buffer: Buffer, offset: number, length: number, label: string): void { if ( !Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || offset + length > buffer.length ) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: `Invalid zip archive: ${label} is out of bounds`, }); } } function findEndOfCentralDirectory(buffer: Buffer): number { const minOffset = Math.max(0, buffer.length - ZIP_MAX_COMMENT_SIZE - ZIP_END_MIN_SIZE); for (let offset = buffer.length - ZIP_END_MIN_SIZE; offset >= minOffset; offset--) { if (buffer.readUInt32LE(offset) !== ZIP_END_OF_CENTRAL_DIRECTORY) continue; const commentLength = buffer.readUInt16LE(offset + 20); if (offset + ZIP_END_MIN_SIZE + commentLength === buffer.length) { return offset; } } return -1; } function readUInt64AsNumber(buffer: Buffer, offset: number, label: string): number { ensureRange(buffer, offset, 8, label); const value = buffer.readBigUInt64LE(offset); if (value > BigInt(Number.MAX_SAFE_INTEGER)) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: `Invalid zip archive: ${label} exceeds the safe integer range`, }); } return Number(value); } function readCentralDirectory( buffer: Buffer, endOffset: number ): { entries: number; offset: number; size: number; trailerOffset: number; } { const diskNumber = buffer.readUInt16LE(endOffset + 4); const centralDirectoryDisk = buffer.readUInt16LE(endOffset + 6); const entriesOnDisk = buffer.readUInt16LE(endOffset + 8); const totalEntries = buffer.readUInt16LE(endOffset + 10); const size = buffer.readUInt32LE(endOffset + 12); const offset = buffer.readUInt32LE(endOffset + 16); const usesZip64 = entriesOnDisk === 0xffff || totalEntries === 0xffff || size === 0xffffffff || offset === 0xffffffff; if (!usesZip64) { if (diskNumber !== 0 || centralDirectoryDisk !== 0 || entriesOnDisk !== totalEntries) { throw diagnostics.SKILLS_ARCHIVE_MULTI_DISK_ZIP(); } return { entries: totalEntries, offset, size, trailerOffset: endOffset }; } if (diskNumber !== 0 || centralDirectoryDisk !== 0) { throw diagnostics.SKILLS_ARCHIVE_MULTI_DISK_ZIP(); } const locatorOffset = endOffset - 20; ensureRange(buffer, locatorOffset, 20, 'zip64 locator'); if (buffer.readUInt32LE(locatorOffset) !== ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip64 locator' }); } if ( buffer.readUInt32LE(locatorOffset + 4) !== 0 || buffer.readUInt32LE(locatorOffset + 16) !== 1 ) { throw diagnostics.SKILLS_ARCHIVE_MULTI_DISK_ZIP(); } const zip64EndOffset = readUInt64AsNumber(buffer, locatorOffset + 8, 'zip64 end offset'); ensureRange(buffer, zip64EndOffset, 56, 'zip64 end of central directory'); if (buffer.readUInt32LE(zip64EndOffset) !== ZIP64_END_OF_CENTRAL_DIRECTORY) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip64 end of central directory' }); } const recordSize = readUInt64AsNumber(buffer, zip64EndOffset + 4, 'zip64 end size'); if (recordSize < 44) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip64 end of central directory' }); } ensureRange(buffer, zip64EndOffset, recordSize + 12, 'zip64 end of central directory'); if (zip64EndOffset + recordSize + 12 !== locatorOffset) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip64 end of central directory' }); } if ( buffer.readUInt32LE(zip64EndOffset + 16) !== 0 || buffer.readUInt32LE(zip64EndOffset + 20) !== 0 ) { throw diagnostics.SKILLS_ARCHIVE_MULTI_DISK_ZIP(); } const zip64EntriesOnDisk = readUInt64AsNumber( buffer, zip64EndOffset + 24, 'zip64 entries on disk' ); const zip64TotalEntries = readUInt64AsNumber(buffer, zip64EndOffset + 32, 'zip64 total entries'); if (zip64EntriesOnDisk !== zip64TotalEntries) { throw diagnostics.SKILLS_ARCHIVE_MULTI_DISK_ZIP(); } return { entries: zip64TotalEntries, size: readUInt64AsNumber(buffer, zip64EndOffset + 40, 'zip64 central directory size'), offset: readUInt64AsNumber(buffer, zip64EndOffset + 48, 'zip64 central directory offset'), trailerOffset: zip64EndOffset, }; } function normalizeArchivePath(rawPath: string): string | null { if (!rawPath || rawPath.includes('\0')) return null; const path = rawPath.replace(/\\/g, '/'); if (path.startsWith('/') || /^[A-Za-z]:/.test(path)) return null; const parts = path.split('/'); if (parts.some((part) => part === '..')) return null; const normalized = parts.filter((part) => part && part !== '.').join('/'); if (!normalized && !path.endsWith('/')) return null; return path.endsWith('/') && normalized ? `${normalized}/` : normalized; } function findExtraField( buffer: Buffer, extraOffset: number, extraLength: number, targetId: number ): Buffer | null { const extraEnd = extraOffset + extraLength; let offset = extraOffset; while (offset < extraEnd) { if (offset + 4 > extraEnd) throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip extra field' }); const id = buffer.readUInt16LE(offset); const size = buffer.readUInt16LE(offset + 2); const dataOffset = offset + 4; ensureRange(buffer, dataOffset, size, 'zip extra field'); if (dataOffset + size > extraEnd) throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip extra field' }); if (id === targetId) return buffer.subarray(dataOffset, dataOffset + size); offset = dataOffset + size; } return null; } function decodeFileName(bytes: Buffer, isUtf8: boolean, unicodePathExtra: Buffer | null): string { if (isUtf8) { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); } if ( unicodePathExtra && unicodePathExtra.length >= 5 && unicodePathExtra[0] === 1 && unicodePathExtra.readUInt32LE(1) === crc32(bytes) ) { return new TextDecoder('utf-8', { fatal: true }).decode(unicodePathExtra.subarray(5)); } let result = ''; for (const byte of bytes) { result += byte < 0x80 ? String.fromCharCode(byte) : CP437_HIGH_BYTES[byte - 0x80]!; } return result; } function readZip64EntryValues( buffer: Buffer, extraOffset: number, extraLength: number, values: { compressedSize: number; diskStart: number; localHeaderOffset: number; uncompressedSize: number; } ): typeof values { const needsZip64 = values.uncompressedSize === 0xffffffff || values.compressedSize === 0xffffffff || values.localHeaderOffset === 0xffffffff || values.diskStart === 0xffff; if (!needsZip64) { if (values.diskStart !== 0) throw diagnostics.SKILLS_ARCHIVE_MULTI_DISK_ZIP(); return values; } const zip64Extra = findExtraField(buffer, extraOffset, extraLength, 0x0001); if (!zip64Extra) throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip64 extra field' }); let valueOffset = 0; const readNextUInt64 = (label: string): number => { if (valueOffset + 8 > zip64Extra.length) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: `Invalid zip64 extra field: missing ${label}`, }); } const value = readUInt64AsNumber(zip64Extra, valueOffset, `zip64 ${label}`); valueOffset += 8; return value; }; const resolved = { ...values }; if (resolved.uncompressedSize === 0xffffffff) { resolved.uncompressedSize = readNextUInt64('uncompressed size'); } if (resolved.compressedSize === 0xffffffff) { resolved.compressedSize = readNextUInt64('compressed size'); } if (resolved.localHeaderOffset === 0xffffffff) { resolved.localHeaderOffset = readNextUInt64('local header offset'); } if (resolved.diskStart === 0xffff) { if (valueOffset + 4 > zip64Extra.length) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip64 extra field: missing disk start', }); } resolved.diskStart = zip64Extra.readUInt32LE(valueOffset); } if (resolved.diskStart !== 0) { throw diagnostics.SKILLS_ARCHIVE_MULTI_DISK_ZIP(); } return resolved; } export function readZipArchive(bytes: Uint8Array, limits: ArchiveLimits): Map<string, Uint8Array> { const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); const endOffset = findEndOfCentralDirectory(buffer); if (endOffset < 0) throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip archive' }); const centralDirectory = readCentralDirectory(buffer, endOffset); const totalEntries = centralDirectory.entries; if (totalEntries > limits.maxEntries) { throw diagnostics.SKILLS_ARCHIVE_TOO_MANY_FILES({ count: totalEntries, max: limits.maxEntries, }); } ensureRange(buffer, centralDirectory.offset, centralDirectory.size, 'central directory'); if (centralDirectory.offset + centralDirectory.size > centralDirectory.trailerOffset) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip archive: central directory overlaps archive trailer', }); } const files = new Map<string, Uint8Array>(); let extractedBytes = 0; let offset = centralDirectory.offset; for (let index = 0; index < totalEntries; index++) { ensureRange(buffer, offset, 46, 'central directory entry'); if (buffer.readUInt32LE(offset) !== ZIP_CENTRAL_DIRECTORY_HEADER) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip central directory entry' }); } const flags = buffer.readUInt16LE(offset + 8); const method = buffer.readUInt16LE(offset + 10); const expectedChecksum = buffer.readUInt32LE(offset + 16); let compressedSize = buffer.readUInt32LE(offset + 20); let uncompressedSize = buffer.readUInt32LE(offset + 24); const fileNameLength = buffer.readUInt16LE(offset + 28); const extraLength = buffer.readUInt16LE(offset + 30); const commentLength = buffer.readUInt16LE(offset + 32); let diskStart = buffer.readUInt16LE(offset + 34); const externalAttributes = buffer.readUInt32LE(offset + 38); let localHeaderOffset = buffer.readUInt32LE(offset + 42); const variableSize = fileNameLength + extraLength + commentLength; ensureRange(buffer, offset + 46, variableSize, 'central directory entry data'); const nameStart = offset + 46; const extraOffset = nameStart + fileNameLength; ({ compressedSize, diskStart, localHeaderOffset, uncompressedSize } = readZip64EntryValues( buffer, extraOffset, extraLength, { compressedSize, diskStart, localHeaderOffset, uncompressedSize, } )); const centralFileName = buffer.subarray(nameStart, nameStart + fileNameLength); const rawFileName = decodeFileName( centralFileName, Boolean(flags & 0x800), findExtraField(buffer, extraOffset, extraLength, 0x7075) ); const fileName = normalizeArchivePath(rawFileName); if (fileName === null) { throw diagnostics.SKILLS_ARCHIVE_UNSAFE_PATH({ path: rawFileName }); } if (flags & 0x1) { throw diagnostics.SKILLS_ARCHIVE_ENCRYPTED_ENTRY(); } const fileType = (externalAttributes >>> 16) & 0o170000; if (fileType !== 0 && fileType !== 0o100000 && fileType !== 0o040000) { throw diagnostics.SKILLS_ARCHIVE_LINK_ENTRY(); } const isDirectory = rawFileName.replace(/\\/g, '/').endsWith('/') || fileType === 0o040000; offset += 46 + variableSize; extractedBytes += uncompressedSize; if (extractedBytes > limits.maxExtractedBytes) { throw diagnostics.SKILLS_ARCHIVE_TOO_LARGE({ maxBytes: limits.maxExtractedBytes }); } if (isDirectory) continue; ensureRange(buffer, localHeaderOffset, 30, 'local file header'); if (buffer.readUInt32LE(localHeaderOffset) !== ZIP_LOCAL_FILE_HEADER) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip local file header' }); } const localFlags = buffer.readUInt16LE(localHeaderOffset + 6); const localMethod = buffer.readUInt16LE(localHeaderOffset + 8); const localFileNameLength = buffer.readUInt16LE(localHeaderOffset + 26); const localExtraLength = buffer.readUInt16LE(localHeaderOffset + 28); const localNameOffset = localHeaderOffset + 30; ensureRange( buffer, localNameOffset, localFileNameLength + localExtraLength, 'local file header data' ); const localFileName = buffer.subarray(localNameOffset, localNameOffset + localFileNameLength); if (localFlags !== flags || localMethod !== method || !localFileName.equals(centralFileName)) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Zip local header does not match central directory', }); } const dataOffset = localHeaderOffset + 30 + localFileNameLength + localExtraLength; ensureRange(buffer, dataOffset, compressedSize, 'file data'); if (dataOffset + compressedSize > centralDirectory.offset) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip archive: file data overlaps central directory', }); } const compressed = buffer.subarray(dataOffset, dataOffset + compressedSize); let contents: Buffer; if (method === 0) { contents = compressed; } else if (method === 8) { contents = inflateRawSync(compressed, { maxOutputLength: uncompressedSize + 1, }); } else { throw diagnostics.SKILLS_ARCHIVE_UNSUPPORTED_COMPRESSION({ method }); } if (contents.byteLength !== uncompressedSize) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Zip entry size mismatch' }); } if (crc32(contents) !== expectedChecksum) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Zip entry checksum mismatch' }); } files.set(fileName, new Uint8Array(contents)); } if (offset !== centralDirectory.offset + centralDirectory.size) { throw diagnostics.SKILLS_ARCHIVE_INVALID({ reason: 'Invalid zip central directory size' }); } return files; } - src/blob.ts (27921 bytes)
/** * Blob-based skill download utilities. * * Enables fast skill installation by fetching pre-built skill snapshots * from the skills.sh download API instead of cloning git repos. * * Flow: * 1. GitHub Trees API → discover SKILL.md locations * 2. raw.githubusercontent.com → fetch frontmatter to get skill names * 3. skills.sh/api/download → fetch full file contents from cached blob */ import { createHash } from 'node:crypto'; import { execFile } from 'node:child_process'; import { AGENT_PROJECT_SKILL_DIRS } from './agents.ts'; import { parseFrontmatter } from './frontmatter.ts'; import { sanitizeMetadata } from './sanitize.ts'; import { getGitHubHost } from './github-host.ts'; import type { Skill } from './types.ts'; import { DEFAULT_SKILL_CONTAINER_DEPTH } from './constants.ts'; import { hashSkillFiles, isExcludedPath } from './skill-hash.ts'; import { SKILLS_SH_CONFIG_FILE, parseSkillsShPaths } from './skills-sh-config.ts'; import { isInternalSkill } from './skills.ts'; // ─── Types ─── export interface SkillSnapshotFile { path: string; contents: string; } export interface SkillDownloadResponse { files: SkillSnapshotFile[]; hash: string; // skillsComputedHash } /** * A skill resolved from blob storage, carrying file contents in memory * instead of referencing a directory on disk. */ export interface BlobSkill extends Skill { /** Files from the blob snapshot */ files: SkillSnapshotFile[]; /** skillsComputedHash from the blob snapshot */ snapshotHash: string; /** Path of the SKILL.md within the repo (e.g., "skills/react-best-practices/SKILL.md") */ repoPath: string; } // ─── Constants ─── const DOWNLOAD_BASE_URL = process.env.SKILLS_DOWNLOAD_URL || 'https://skills.sh'; // Repos that self-host their downloads on the blob fast-path export const BLOB_ALLOWED_REPOS: Record<string, { downloadUrl: (slug: string) => string }> = { 'zapier/connectors': { downloadUrl: (slug) => `https://connectors-skills.zapier.com/download/${encodeURIComponent(slug)}/snapshot.json`, }, }; /** Timeout for individual HTTP fetches (ms) */ const FETCH_TIMEOUT = 10_000; const GH_API_MAX_BUFFER = 16 * 1024 * 1024; // ─── Slug computation ─── /** * Convert a skill name to a URL-safe slug. * Must match the server-side toSkillSlug() exactly. */ export function toSkillSlug(name: string): string { return name .toLowerCase() .replace(/[\s_]+/g, '-') .replace(/[^a-z0-9-]/g, '') .replace(/-+/g, '-') .replace(/^-|-$/g, ''); } // ─── GitHub Trees API ─── export interface TreeEntry { path: string; type: 'blob' | 'tree'; sha: string; size?: number; /** Git file mode, e.g. `120000` for a symlink (passed through from the Trees API). */ mode?: string; } export interface RepoTree { sha: string; branch: string; tree: TreeEntry[]; } /** * Within-process memo: once we've discovered that the GitHub API has * rate-limited this IP, subsequent calls skip straight to the auth fallback * instead of burning round trips on requests guaranteed to 403. */ let _rateLimitedThisSession = false; /** For tests only. */ export function resetRepoTreeAuthState(): void { _rateLimitedThisSession = false; } interface ApiFetchResult<T> { value: T | null; rateLimited: boolean; authRetryable: boolean; } /** Reads one response body into the value a caller wants, or null when it is not one. */ type ApiParser<T> = (data: unknown) => T | null; async function fetchGitHubApi<T>( endpoint: string, token: string | null, parse: ApiParser<T> ): Promise<ApiFetchResult<T>> { try { const githubHost = getGitHubHost(); const apiBase = githubHost === 'github.com' ? 'https://api.github.com' : `https://${githubHost}/api/v3`; const headers: Record<string, string> = { Accept: 'application/vnd.github.v3+json', 'User-Agent': 'skills-cli', }; if (token) { headers['Authorization'] = `Bearer ${token}`; } const response = await fetch(`${apiBase}/${endpoint}`, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT), }); if (response.ok) { return { value: parse(await response.json()), rateLimited: false, authRetryable: false }; } // GitHub signals rate-limit with 403 + X-RateLimit-Remaining: 0. // (A bare 403 means permission denied, which is not retryable here.) const rateLimited = response.status === 403 && response.headers.get('x-ratelimit-remaining') === '0'; // A private repo answers 401/404 to an anonymous request (GitHub hides its // existence); a token may turn that into a 200. See issue #1318. const authRetryable = response.status === 401 || response.status === 404; return { value: null, rateLimited, authRetryable }; } catch { return { value: null, rateLimited: false, authRetryable: false }; } } async function fetchGitHubApiWithToken<T>( endpoints: string[], parsers: ApiParser<T>[], getToken: () => string | null ): Promise<T | null> { const token = getToken(); if (!token) return null; for (const [index, endpoint] of endpoints.entries()) { const result = await fetchGitHubApi(endpoint, token, parsers[index]!); if (result.value) return result.value; } return null; } async function fetchGitHubApiWithGitHubCli<T>( endpoints: string[], parsers: ApiParser<T>[] ): Promise<T | null> { for (const [index, endpoint] of endpoints.entries()) { try { const stdout = await new Promise<string>((resolve, reject) => { execFile( 'gh', ['api', endpoint, '--method', 'GET', '--hostname', getGitHubHost()], { encoding: 'utf8', timeout: FETCH_TIMEOUT, maxBuffer: GH_API_MAX_BUFFER, windowsHide: true, env: { ...process.env, GH_PROMPT_DISABLED: '1' }, }, (error, output) => { if (error) reject(error); else resolve(output); } ); }); const value = parsers[index]!(JSON.parse(stdout)); if (value) return value; } catch { // Try the next candidate endpoint, then let the caller fall back to clone. } } return null; } async function fetchGitHubApiWithAvailableAuth<T>( endpoints: string[], parsers: ApiParser<T>[], getToken?: () => string | null ): Promise<T | null> { if (getToken) { const value = await fetchGitHubApiWithToken(endpoints, parsers, getToken); if (value) return value; } return fetchGitHubApiWithGitHubCli(endpoints, parsers); } /** * GET the first of `endpoints` (paths under the API root) that answers, read * with the parser at the same index. Returns null when none does. * * Authentication is lazy: by default the call goes out unauthenticated, * which is enough for the vast majority of users (60 req/hr per IP). We only * retry with available authentication when the unauthenticated attempt fails * in a way credentials can fix: a rate-limit 403, or the 401/404 a private repo * returns to anonymous requests. Explicit environment tokens are tried first; * then `gh api` uses GitHub CLI authentication without exporting its stored * credential. A bare permission-denied 403 is not retried. See issues #523 * and #1318. */ async function fetchFirstGitHubApi<T>( endpoints: string[], parsers: ApiParser<T>[], getToken?: () => string | null ): Promise<T | null> { // Fast path: once we've seen a rate limit in this process, don't bother // retrying unauth on subsequent calls. Go straight to auth. if (_rateLimitedThisSession) { return fetchGitHubApiWithAvailableAuth(endpoints, parsers, getToken); } // First pass: unauthenticated. let rateLimited = false; let authRetryable = false; for (const [index, endpoint] of endpoints.entries()) { const result = await fetchGitHubApi(endpoint, null, parsers[index]!); if (result.value) return result.value; if (result.rateLimited) { // All endpoints share the same rate-limit bucket on this IP, so it's // pointless to keep trying other endpoints in this pass. rateLimited = true; break; } if (result.authRetryable) { // A private repo answers 401/404 to anonymous requests on every endpoint, // so stop and retry the whole set once with a token. authRetryable = true; break; } } if (!(rateLimited || authRetryable)) return null; // Remember an IP-level rate limit so later calls skip the unauth pass. // A private-repo 404 is per-repo, not per-IP, so it must not set this flag. if (rateLimited) _rateLimitedThisSession = true; return fetchGitHubApiWithAvailableAuth(endpoints, parsers, getToken); } /** * Fetch the full recursive tree for a GitHub repo. * Returns the tree data including all entries, or null on failure. * Tries branches in order: ref (if specified), then HEAD, main, and master. * See fetchFirstGitHubApi for how authentication is used. */ export async function fetchRepoTree( ownerRepo: string, ref?: string, getToken?: () => string | null ): Promise<RepoTree | null> { const branches = ref ? [ref] : ['HEAD', 'main', 'master']; return fetchFirstGitHubApi( branches.map( (branch) => `repos/${ownerRepo}/git/trees/${encodeURIComponent(branch)}?recursive=1` ), branches.map((branch) => (data: unknown): RepoTree | null => { const { sha, tree } = (data ?? {}) as { sha?: unknown; tree?: unknown }; if (typeof sha !== 'string' || !Array.isArray(tree)) return null; return { sha, branch, tree: tree as TreeEntry[] }; }), getToken ); } /** * The commit at the tip of `tree.branch`, when it is still the commit `tree` was read from. * Null when it cannot be read or the branch has moved since `tree` was fetched, * so a recorded commit always matches the files that were installed. */ export async function fetchTreeCommit( ownerRepo: string, tree: RepoTree, getToken?: () => string | null ): Promise<string | null> { // The list endpoint omits per-file stats, unlike `commits/<ref>`. const branch = tree.branch === 'HEAD' ? '' : `&sha=${encodeURIComponent(tree.branch)}`; return fetchFirstGitHubApi( [`repos/${ownerRepo}/commits?per_page=1${branch}`], [ (data: unknown): string | null => { const latest = (Array.isArray(data) ? data[0] : null) as { sha?: unknown; commit?: { tree?: { sha?: unknown } }; } | null; const sha = latest?.sha; if (typeof sha !== 'string' || !/^[0-9a-f]{40}$/i.test(sha)) return null; // Asked for a branch, the Trees API answers with the commit's SHA, not the root tree's const matches = sha === tree.sha || latest?.commit?.tree?.sha === tree.sha; return matches ? sha.toLowerCase() : null; }, ], getToken ); } /** * Extract the folder hash (tree SHA) for a specific skill path from a repo tree. * This replaces the per-skill GitHub API call previously done in fetchSkillFolderHash(). */ export function getSkillFolderHashFromTree(tree: RepoTree, skillPath: string): string | null { let folderPath = skillPath.replace(/\\/g, '/'); // Remove SKILL.md suffix to get folder path (case-insensitive) if (folderPath.toLowerCase().endsWith('/skill.md')) { folderPath = folderPath.slice(0, -9); } else if (folderPath.toLowerCase().endsWith('skill.md')) { folderPath = folderPath.slice(0, -8); } if (folderPath.endsWith('/')) { folderPath = folderPath.slice(0, -1); } // Root-level skill if (!folderPath) { return tree.sha; } const entry = tree.tree.find((e) => e.type === 'tree' && e.path === folderPath); return entry?.sha ?? null; } // ─── Skill discovery from tree ─── /** Known directories where SKILL.md files are commonly found (relative to repo root) */ const PRIORITY_PREFIXES = [ '', 'skills/', 'skills/.curated/', 'skills/.experimental/', 'skills/.system/', ...AGENT_PROJECT_SKILL_DIRS.map((dir) => `${dir}/`), ]; /** * Find all SKILL.md file paths in a repo tree. * Applies the same priority directory logic as discoverSkills(). * If subpath is set, only searches within that subtree. * `extraContainers` are additional container dirs relative to the search root * (e.g. from skills.sh.json `paths`), searched like `skills/`. */ export function findSkillMdPaths( tree: RepoTree, subpath?: string, extraContainers: string[] = [] ): string[] { // Find all blob entries that are SKILL.md files (case-insensitive) const allSkillMds = tree.tree .filter((e) => e.type === 'blob' && e.path.split('/').at(-1)!.toLowerCase() === 'skill.md') .map((e) => e.path); // Apply subpath filter const prefix = subpath ? (subpath.endsWith('/') ? subpath : subpath + '/') : ''; const filtered = prefix ? allSkillMds.filter((p) => p.startsWith(prefix) || p === prefix + 'SKILL.md') : allSkillMds; if (filtered.length === 0) return []; // Check priority directories first (same order as discoverSkills). // Non-root prefixes also accept paths up to depth 3 so the blob fast path stays // in sync with the on-disk walk's catalog-layout discovery. const priorityResults: string[] = []; const seen = new Set<string>(); // Mirror of SKIP_DIRS at the top of src/skills.ts. Kept local to avoid // a cross-file import; if these ever drift, update both. const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '__pycache__']); const lowerSkillMdSet = new Set(filtered.map((p) => p.toLowerCase())); const extraPrefixes = extraContainers.reduce((prefixes, dir) => { const prefix = `${dir}/`; if (!PRIORITY_PREFIXES.includes(prefix)) prefixes.add(prefix); return prefixes; }, new Set<string>()); const priorityPrefixes = [...PRIORITY_PREFIXES, ...extraPrefixes]; for (const priorityPrefix of priorityPrefixes) { const fullPrefix = prefix + priorityPrefix; const isContainer = priorityPrefix !== ''; // Declared containers only search their children, like the disk walk. const isExtraContainer = extraPrefixes.has(priorityPrefix); for (const skillMd of filtered) { // Check if this SKILL.md is directly inside the priority dir (one level deep) if (!skillMd.startsWith(fullPrefix)) continue; const rest = skillMd.slice(fullPrefix.length); // Direct SKILL.md in the priority dir (e.g., "skills/SKILL.md") if (rest.toLowerCase() === 'skill.md') { if (isExtraContainer) continue; if (!seen.has(skillMd)) { priorityResults.push(skillMd); seen.add(skillMd); } continue; } // SKILL.md one level deep (e.g., "skills/react-best-practices/SKILL.md") const parts = rest.split('/'); if (parts.length === 2 && parts[1]!.toLowerCase() === 'skill.md') { if (!seen.has(skillMd)) { priorityResults.push(skillMd); seen.add(skillMd); } continue; } // SKILL.md two or three levels deep under a kno - src/ci.ts (286 bytes)
export function isCI(): boolean { return !!( process.env.CI || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI || process.env.CIRCLECI || process.env.TRAVIS || process.env.BUILDKITE || process.env.JENKINS_URL || process.env.TEAMCITY_VERSION ); } - src/cli-args.test.ts (3795 bytes)
import { describe, it, expect } from 'vitest'; import { parseCliArgs } from './cli-args.ts'; import { parseAddOptions } from './add.ts'; const spec = { global: { type: 'boolean', short: 'g' }, yes: { type: 'boolean', short: 'y' }, agent: { type: 'list', short: 'a', value: 'an agent name' }, metadata: { type: 'string', value: 'a JSON value' }, } as const; const parse = (args: string[]) => { const { errors, ...rest } = parseCliArgs(args, spec); return { ...rest, errors: errors.map((e) => e.message) }; }; describe('parseCliArgs', () => { it('reads space and equals forms the same for one value', () => { expect(parse(['--agent', 'cursor']).values).toEqual({ agent: ['cursor'] }); expect(parse(['--agent=cursor']).values).toEqual({ agent: ['cursor'] }); expect(parse(['-a', 'cursor']).values).toEqual({ agent: ['cursor'] }); expect(parse(['-a=cursor']).values).toEqual({ agent: ['cursor'] }); expect(parse(['-acursor']).values).toEqual({ agent: ['cursor'] }); }); it('collects following arguments for list options only in the space form', () => { expect(parse(['--agent', 'a', 'b', '-g', 'src'])).toMatchObject({ values: { agent: ['a', 'b'], global: true }, positionals: ['src'], }); expect(parse(['--agent=a', 'src'])).toMatchObject({ values: { agent: ['a'] }, positionals: ['src'], }); expect(parse(['--agent=a', '--agent', 'b', 'c']).values).toEqual({ agent: ['a', 'b', 'c'] }); }); it('keeps values containing = and leading dashes in the equals form', () => { expect(parse(['--metadata={"a":"b=c"}']).values).toEqual({ metadata: ['{"a":"b=c"}'] }); expect(parse(['--agent=-x']).values).toEqual({ agent: ['-x'] }); }); it('expands grouped short switches', () => { expect(parse(['-gy']).values).toEqual({ global: true, yes: true }); }); it('treats everything after -- as positional', () => { expect(parse(['--agent', 'a', '--', 'b', '--global'])).toMatchObject({ values: { agent: ['a'] }, positionals: ['b', '--global'], }); }); it('reports missing values instead of taking the next option', () => { expect(parse(['--agent', '-y'])).toMatchObject({ values: {}, errors: ['--agent requires an agent name'], }); expect(parse(['--agent=']).errors).toEqual(['--agent requires an agent name']); expect(parse(['-a']).errors).toEqual(['-a requires an agent name']); expect(parse(['--metadata']).errors).toEqual(['--metadata requires a JSON value']); }); it('rejects values on boolean options', () => { expect(parse(['--global=true', 'src'])).toMatchObject({ values: {}, positionals: ['src'], errors: ['--global does not take a value'], }); }); it('returns unknown options without failing', () => { expect(parse(['--force', 'src', '--frozen-lockfile=1'])).toMatchObject({ positionals: ['src'], unknown: ['--force', '--frozen-lockfile'], errors: [], }); }); it('ignores prototype keys that are not in the spec', () => { expect(parse(['--__proto__', 'x']).unknown).toEqual(['--__proto__']); expect(parse(['--toString=1']).unknown).toEqual(['--toString']); }); }); describe('parseAddOptions with equals syntax', () => { it('filters with --skill=<name> (#2039)', () => { const { source, options, errors } = parseAddOptions(['owner/repo', '--skill=foo']); expect(errors).toEqual([]); expect(source).toEqual(['owner/repo']); expect(options.skill).toEqual(['foo']); }); it('does not take the source as an agent after --agent=<name>', () => { const { source, options } = parseAddOptions(['--agent=claude-code', 'owner/repo']); expect(source).toEqual(['owner/repo']); expect(options.agent).toEqual(['claude-code']); }); }); - src/cli-args.ts (3782 bytes)
import { parseArgs } from 'node:util'; import type { Diagnostic } from 'nostics'; import { diagnostics } from './diagnostics.ts'; /** * - `boolean`: a switch; `--flag=value` is an error. * - `string`: one value per occurrence (`--flag value` or `--flag=value`). * - `list`: like `string`, but the space form also takes the arguments that * follow, up to the next option (`--agent a b`). The `=` form takes exactly * one value, so `--agent=a source` keeps `source` positional. */ export type OptionSpec = | { type: 'boolean'; short?: string } | { type: 'string' | 'list'; short?: string; /** e.g. 'an agent name' */ value?: string }; type OptionValues<S extends Record<string, OptionSpec>> = { [K in keyof S]?: S[K] extends { type: 'boolean' } ? true : string[]; }; export interface ParsedCliArgs<S extends Record<string, OptionSpec>> { values: OptionValues<S>; positionals: string[]; /** Options not in the spec, as typed (`--foo`); each command decides whether to reject them. */ unknown: string[]; errors: Diagnostic[]; } /** * Parse subcommand arguments with `util.parseArgs`, which handles `--flag=value`, * short aliases, grouped short switches (`-gy`) and the `--` terminator. * * Runs `parseArgs` in non-strict mode and validates the tokens here, so one * call reports every problem and commands can choose to ignore unknown options. */ export function parseCliArgs<const S extends Record<string, OptionSpec>>( args: string[], spec: S ): ParsedCliArgs<S> { const { tokens } = parseArgs({ args, options: Object.fromEntries( Object.entries(spec).map(([name, { type, short }]) => [ name, { type: type === 'boolean' ? 'boolean' : 'string', ...(short ? { short } : {}) }, ]) ), strict: false, allowPositionals: true, tokens: true, }); const values: Record<string, true | string[]> = {}; const positionals: string[] = []; const unknown: string[] = []; const errors: Diagnostic[] = []; for (let i = 0; i < tokens.length; i++) { const token = tokens[i]!; if (token.kind === 'option-terminator') continue; if (token.kind === 'positional') { if (token.value) positionals.push(token.value); continue; } const def = Object.hasOwn(spec, token.name) ? spec[token.name] : undefined; if (!def) { unknown.push(token.rawName); continue; } if (def.type === 'boolean') { if (token.value === undefined) values[token.name] = true; else errors.push(diagnostics.SKILLS_OPTION_TAKES_NO_VALUE({ option: token.rawName })); continue; } let value = token.value; // parseArgs reads `-s=foo` as `-s` with value `=foo`, like getopt. if (token.inlineValue && !token.rawName.startsWith('--') && value?.startsWith('=')) { value = value.slice(1); } // In non-strict mode parseArgs takes the next argument as the value even // when it is another option (`--agent -y`). if (!value || (!token.inlineValue && value.startsWith('-'))) { errors.push( diagnostics.SKILLS_OPTION_REQUIRES_VALUE({ option: token.rawName, value: def.value ?? 'a value', }) ); continue; } const list = (values[token.name] ??= []) as string[]; list.push(value); if (def.type === 'list' && !token.inlineValue) { for (let next = tokens[i + 1]; next?.kind === 'positional'; next = tokens[i + 1]) { if (next.value) list.push(next.value); i++; } } } return { values: values as OptionValues<S>, positionals, unknown, errors }; } /** For commands without an error channel: `main()` reports thrown option diagnostics. */ export function throwFirstError(errors: Diagnostic[]): void { if (errors[0]) throw errors[0]; } - src/cli.test.ts (5878 bytes)
import { describe, it, expect } from 'vitest'; import { readFileSync } from 'fs'; import { join } from 'path'; import { runCli, runCliOutput, stripLogo, hasLogo } from './test-utils.ts'; describe('skills CLI', () => { describe('--help', () => { it('should display help message', () => { const output = runCliOutput(['--help']); expect(output).toContain('Usage: skills <command> [options]'); expect(output).toContain('Manage Skills:'); expect(output).toContain('init [name]'); expect(output).toContain('add <package>'); expect(output).toContain('use <package>@<skill>'); expect(output).toContain('update'); expect(output).toContain('Add Options:'); expect(output).toContain('Use Options:'); expect(output).toContain('-g, --global'); expect(output).toContain('-a, --agent'); expect(output).toContain('-s, --skill'); expect(output).toContain('-l, --list'); expect(output).toContain('-y, --yes'); expect(output).toContain('--all'); expect(output).not.toContain('OpenClaw community skills'); }); it('should show same output for -h alias', () => { const helpOutput = runCliOutput(['--help']); const hOutput = runCliOutput(['-h']); expect(hOutput).toBe(helpOutput); }); }); describe('--version', () => { it('should display version number', () => { const output = runCliOutput(['--version']); expect(output.trim()).toMatch(/^\d+\.\d+\.\d+$/); }); it('should match package.json version', () => { const output = runCliOutput(['--version']); const pkg = JSON.parse( readFileSync(join(import.meta.dirname, '..', 'package.json'), 'utf-8') ); expect(output.trim()).toBe(pkg.version); }); }); describe('no arguments', () => { it('should display banner', () => { const result = runCli([]); const output = stripLogo(result.stdout); expect(output).toContain('The open agent skills ecosystem'); expect(output).toContain('npx skills add'); expect(output).toContain('npx skills use'); expect(output).toContain('npx skills update'); expect(output).toContain('npx skills init'); expect(output).toContain('skills.sh'); }); }); describe('unknown command', () => { it('should show error for unknown command', () => { const output = runCliOutput(['unknown-command']); expect(output).toMatchInlineSnapshot(` "[SKILLS_UNKNOWN_COMMAND] Unknown command: unknown-command ╰▶ fix: Run skills --help for usage. " `); }); it('should exit with code 1 for unknown command', () => { const result = runCli(['unknown-command']); expect(result.exitCode).toBe(1); }); it('should exit with code 0 for top-level --help', () => { const result = runCli(['--help']); expect(result.exitCode).toBe(0); }); it('should exit with code 0 for --version', () => { const result = runCli(['--version']); expect(result.exitCode).toBe(0); }); }); describe('subcommand --help', () => { // Each subcommand invoked with --help/-h must short-circuit to help output // before the subcommand handler runs, so no side effects (telemetry, // network calls, lock-file writes) can happen. const cases: Array<[string, string]> = [ ['add --help routes to top-level help', 'add'], ['update --help routes to top-level help', 'update'], ['check --help routes to top-level help', 'check'], ['list --help routes to top-level help', 'list'], ['init --help routes to top-level help', 'init'], ['find --help routes to top-level help', 'find'], ['experimental_install --help routes to top-level help', 'experimental_install'], ['sync --help routes to top-level help', 'sync'], ['experimental_sync --help routes to top-level help', 'experimental_sync'], ]; for (const [label, command] of cases) { it(label, () => { const result = runCli([command, '--help']); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Usage: skills <command> [options]'); }); it(`${label} (-h alias)`, () => { const result = runCli([command, '-h']); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Usage: skills <command> [options]'); }); } it('remove --help routes to remove-specific help', () => { const result = runCli(['remove', '--help']); expect(result.exitCode).toBe(0); // remove has its own help screen distinct from the top-level usage banner expect(result.stdout).toContain('skills remove'); }); it('update --help does not run the update flow', () => { const result = runCli(['update', '--help']); expect(result.exitCode).toBe(0); // The update flow prints this banner; it must not appear when --help is // passed, otherwise the side-effecting check is being executed. expect(result.stdout).not.toContain('Checking for skill updates'); expect(result.stderr).not.toContain('Checking for skill updates'); }); }); describe('logo display', () => { it('should not display logo for list command', () => { const output = runCliOutput(['list']); expect(hasLogo(output)).toBe(false); }); it('should not display logo for check command', () => { // Note: check command makes GitHub API calls, so we just verify initial output const output = runCliOutput(['check']); expect(hasLogo(output)).toBe(false); }, 60000); it('should not display logo for update command', () => { // Note: update command makes GitHub API calls, so we just verify initial output const output = runCliOutput(['update']); expect(hasLogo(output)).toBe(false); }, 60000); }); }); - src/cli.ts (17497 bytes)
#!/usr/bin/env node import { writeFileSync, readFileSync, existsSync, mkdirSync } from 'fs'; import { basename, join, dirname } from 'path'; import { fileURLToPath } from 'url'; import { stringify as stringifyYaml } from 'yaml'; import { runAdd, parseAddOptions, initTelemetry } from './add.ts'; import { diagnostics, formatError } from './diagnostics.ts'; import { runFind } from './find.ts'; import { runInstallFromLock } from './install.ts'; import { runList } from './list.ts'; import { removeCommand, parseRemoveOptions } from './remove.ts'; import { runSync, parseSyncOptions } from './sync.ts'; import { flushTelemetry } from './telemetry.ts'; import { isRunningInAgent } from './detect-agent.ts'; import { runUpdate } from './update.ts'; import { runUse, parseUseOptions } from './use.ts'; import { BOLD, DIM, GRAYS, RESET, TEXT } from './color.ts'; const __dirname = dirname(fileURLToPath(import.meta.url)); function getVersion(): string { try { const pkgPath = join(__dirname, '..', 'package.json'); const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')); return pkg.version; } catch { return '0.0.0'; } } const VERSION = getVersion(); initTelemetry(VERSION); const LOGO_LINES = [ '███████╗██╗ ██╗██╗██╗ ██╗ ███████╗', '██╔════╝██║ ██╔╝██║██║ ██║ ██╔════╝', '███████╗█████╔╝ ██║██║ ██║ ███████╗', '╚════██║██╔═██╗ ██║██║ ██║ ╚════██║', '███████║██║ ██╗██║███████╗███████╗███████║', '╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚══════╝', ]; function showLogo(): void { console.log(); LOGO_LINES.forEach((line, i) => { console.log(`${GRAYS[i]}${line}${RESET}`); }); } function showBanner(): void { showLogo(); console.log(); console.log(`${DIM}The open agent skills ecosystem${RESET}`); console.log(); console.log( ` ${DIM}$${RESET} ${TEXT}npx skills add ${DIM}<package>${RESET} ${DIM}Add a new skill${RESET}` ); console.log( ` ${DIM}$${RESET} ${TEXT}npx skills use ${DIM}<package>@<skill>${RESET} ${DIM}Use a skill without installing${RESET}` ); console.log( ` ${DIM}$${RESET} ${TEXT}npx skills remove${RESET} ${DIM}Remove installed skills${RESET}` ); console.log( ` ${DIM}$${RESET} ${TEXT}npx skills list${RESET} ${DIM}List installed skills${RESET}` ); console.log( ` ${DIM}$${RESET} ${TEXT}npx skills find ${DIM}[query]${RESET} ${DIM}Search for skills${RESET}` ); console.log(); console.log( ` ${DIM}$${RESET} ${TEXT}npx skills update${RESET} ${DIM}Update installed skills${RESET}` ); console.log(); console.log( ` ${DIM}$${RESET} ${TEXT}npx skills experimental_install${RESET} ${DIM}Restore from skills-lock.json${RESET}` ); console.log( ` ${DIM}$${RESET} ${TEXT}npx skills init ${DIM}[name]${RESET} ${DIM}Create a new skill${RESET}` ); console.log( ` ${DIM}$${RESET} ${TEXT}npx skills experimental_sync${RESET} ${DIM}Sync skills from node_modules${RESET}` ); console.log(); console.log(`${DIM}try:${RESET} npx skills add vercel-labs/agent-skills`); console.log(); console.log(`Discover more skills at ${TEXT}https://skills.sh/${RESET}`); console.log(); } function showHelp(): void { const examples: Array<[command: string, description?: string]> = [ ['skills add vercel-labs/agent-skills'], ['skills use vercel-labs/agent-skills@vercel-optimize | claude'], ['skills use vercel-labs/agent-skills --skill vercel-optimize --agent claude-code'], ['skills add vercel-labs/agent-skills -g'], ['skills add vercel-labs/agent-skills --agent claude-code cursor'], ['skills add vercel-labs/agent-skills --skill pr-review commit'], ['skills add vercel-labs/agent-skills --json -y', 'JSON output'], ['skills remove', 'interactive remove'], ['skills remove web-design', 'remove by name'], ['skills rm --global frontend-design'], ['skills list', 'list project skills'], ['skills ls -g', 'list global skills'], ['skills ls -a claude-code', 'filter by agent'], ['skills ls --json', 'JSON output'], ['skills find', 'interactive search'], ['skills find typescript', 'search by keyword'], ['skills find react --owner vercel', 'search within an owner'], ['skills update'], ['skills update my-skill', 'update a single skill'], ['skills update -g', 'update global skills only'], ['skills experimental_install', 'restore from skills-lock.json'], ['skills init my-skill'], ['skills experimental_sync', 'sync from node_modules (experimental)'], ['skills experimental_sync -y', 'sync without prompts'], ]; const exampleWidth = Math.max( ...examples.filter(([, description]) => description).map(([command]) => command.length) ); const formattedExamples = examples .map(([command, description]) => { const comment = description ? `${' '.repeat(exampleWidth - command.length + 2)}${DIM}# ${description}${RESET}` : ''; return ` ${DIM}$${RESET} ${command}${comment}`; }) .join('\n'); console.log(` ${BOLD}Usage:${RESET} skills <command> [options] ${BOLD}Manage Skills:${RESET} add <package> Add a skill package (alias: a) e.g. vercel-labs/agent-skills notion https://notion.so/<skill-page> https://github.com/vercel-labs/agent-skills use <package>@<skill> Generate a prompt for using one skill without installing it remove [skills] Remove installed skills list, ls List installed skills find [query] Search for skills interactively ${BOLD}Find Options:${RESET} --owner <owner> Search only repositories from a GitHub owner ${BOLD}Updates:${RESET} update [skills...] Update skills to latest versions (alias: upgrade) ${BOLD}Update Options:${RESET} -g, --global Update global skills only -p, --project Update project skills only -y, --yes Skip scope prompt (auto-detect: project if in a project, else global) ${BOLD}Project:${RESET} experimental_install Restore skills from skills-lock.json (alias: install, i) init [name] Initialize a skill (creates <name>/SKILL.md or ./SKILL.md) experimental_sync Sync skills from node_modules into agent directories (alias: sync) ${BOLD}Experimental Install Options:${RESET} -a, --agent <agents> Link to these agents (default: last selected, else detected) --dry-run Show what would be restored without installing anything --frozen-lockfile Fail instead of changing skills-lock.json (default in CI) --no-frozen-lockfile Allow skills-lock.json to change in CI --force Reinstall skills that are already installed ${BOLD}Add Options:${RESET} -g, --global Install skill globally (user-level) instead of project-level -a, --agent <agents> Specify agents to install to (use '*' for all agents) -s, --skill <skills> Specify skill names to install (use '*' for all skills) -l, --list List available skills in the repository without installing -y, --yes Skip confirmation prompts --copy Copy files instead of symlinking to agent directories --rename <name> Install the one selected skill under a new name --metadata <json> Attach valid JSON to the install telemetry event --subagent <names> Install to Eve subagents (use 'root' for the root agent) --all Shorthand for --skill '*' --agent '*' -y --full-depth Search all subdirectories even when a root SKILL.md exists --json Output results as JSON (machine-readable, no ANSI codes) ${BOLD}Use Options:${RESET} -s, --skill <skill> Specify the skill to use -a, --agent <agent> Start one supported agent interactively --full-depth Search all subdirectories even when a root SKILL.md exists ${BOLD}Remove Options:${RESET} -g, --global Remove from global scope -a, --agent <agents> Remove from specific agents (omit to clean all agent links) -s, --skill <skills> Specify skills to remove (use '*' for all skills) -y, --yes Skip confirmation prompts --all Remove every installed skill (-y implied). Do not combine with named skills. ${BOLD}Experimental Sync Options:${RESET} -a, --agent <agents> Specify agents to install to (use '*' for all agents) -y, --yes Skip confirmation prompts --copy Copy skills instead of linking them to node_modules --dry-run Show what would change without changing anything --no-cleanup Keep skills whose package no longer ships them --no-remote Skip git sources listed in package.json skills fields --frozen-lockfile Fail instead of changing skills-lock.json (default in CI) --no-frozen-lockfile Allow skills-lock.json to change in CI -r, --recursive Also sync the dependencies of each workspace package --include <patterns> Only sync matching packages (<pkg>) or skills (<pkg>#<skill>) --exclude <patterns> Skip matching packages (<pkg>) or skills (<pkg>#<skill>) ${BOLD}List Options:${RESET} -g, --global List global skills (default: project) -a, --agent <agents> Filter by specific agents --json Output as JSON (machine-readable, no ANSI codes) ${BOLD}Options:${RESET} --help, -h Show this help message --version, -v Show version number ${BOLD}Examples:${RESET} ${formattedExamples} Discover more skills at ${TEXT}https://skills.sh/${RESET} `); } function showRemoveHelp(): void { console.log(` ${BOLD}Usage:${RESET} skills remove [skills...] [options] ${BOLD}Description:${RESET} Remove installed skills from agents. If no skill names are provided, an interactive selection menu will be shown. ${BOLD}Arguments:${RESET} skills Optional skill names to remove (space-separated) ${BOLD}Options:${RESET} -g, --global Remove from global scope (~/) instead of project scope -a, --agent Remove from specific agents (omit to clean all agent links) -s, --skill Specify skills to remove (use '*' for all skills) -y, --yes Skip confirmation prompts --all Remove every installed skill (-y implied). Do not combine with named skills. ${BOLD}Examples:${RESET} ${DIM}$${RESET} skills remove ${DIM}# interactive selection${RESET} ${DIM}$${RESET} skills remove my-skill ${DIM}# remove specific skill${RESET} ${DIM}$${RESET} skills remove skill1 skill2 -y ${DIM}# remove multiple skills${RESET} ${DIM}$${RESET} skills remove --global my-skill ${DIM}# remove from global scope${RESET} ${DIM}$${RESET} skills rm --agent claude-code my-skill ${DIM}# remove from specific agent${RESET} ${DIM}$${RESET} skills remove --all ${DIM}# remove all skills${RESET} ${DIM}$${RESET} skills remove --skill '*' -a cursor ${DIM}# remove all skills from cursor${RESET} Discover more skills at ${TEXT}https://skills.sh/${RESET} `); } function runInit(args: string[]): void { const cwd = process.cwd(); const skillName = args[0] || basename(cwd); const hasName = args[0] !== undefined; const skillDir = hasName ? join(cwd, skillName) : cwd; const skillFile = join(skillDir, 'SKILL.md'); const displayPath = hasName ? `${skillName}/SKILL.md` : 'SKILL.md'; if (existsSync(skillFile)) { console.log(`${TEXT}Skill already exists at ${DIM}${displayPath}${RESET}`); return; } if (hasName) { mkdirSync(skillDir, { recursive: true }); } const skillContent = `--- name: ${stringifyYaml(skillName).trimEnd()} description: A brief description of what this skill does --- # ${skillName} Instructions for the agent to follow when this skill is activated. ## When to use Describe when this skill should be used. ## Instructions 1. First step 2. Second step 3. Additional steps as needed `; writeFileSync(skillFile, skillContent); console.log(`${TEXT}Initialized skill: ${DIM}${skillName}${RESET}`); console.log(); console.log(`${DIM}Created:${RESET}`); console.log(` ${displayPath}`); console.log(); console.log(`${DIM}Next steps:${RESET}`); console.log(` 1. Edit ${TEXT}${displayPath}${RESET} to define your skill instructions`); console.log( ` 2. Update the ${TEXT}name${RESET} and ${TEXT}description${RESET} in the frontmatter` ); console.log(); console.log(`${DIM}Publishing:${RESET}`); console.log( ` ${DIM}GitHub:${RESET} Push to a repo, then ${TEXT}npx skills add <owner>/<repo>${RESET}` ); console.log( ` ${DIM}URL:${RESET} Host the file, then ${TEXT}npx skills add https://example.com/${displayPath}${RESET}` ); console.log(); console.log(`Browse existing skills for inspiration at ${TEXT}https://skills.sh/${RESET}`); console.log(); } // ============================================ // Main // ============================================ async function main(): Promise<void> { const args = process.argv.slice(2); const inAgent = await isRunningInAgent(); if (args.length === 0) { if (!inAgent) { showBanner(); } return; } const command = args[0]!; const restArgs = args.slice(1); // Subcommand --help / -h must short-circuit before dispatch so that running // e.g. `skills update --help` prints help instead of executing the update // flow. Without this pre-check, every subcommand handler that doesn't // inspect `--help` itself ends up running its side-effecting work. if ( command !== '--help' && command !== '-h' && command !== '--version' && command !== '-v' && (restArgs.includes('--help') || restArgs.includes('-h')) ) { if (command === 'remove' || command === 'rm' || command === 'r') { showRemoveHelp(); } else { showHelp(); } return; } switch (command) { case 'find': case 'search': case 'f': case 's': if (!inAgent) showLogo(); console.log(); await runFind(restArgs); break; case 'init': if (!inAgent) showLogo(); console.log(); runInit(restArgs); break; case 'experimental_install': { if (!inAgent) showLogo(); await runInstallFromLock(restArgs); break; } case 'i': case 'install': case 'a': case 'add': { const { source: addSource, options: addOpts, errors } = parseAddOptions(restArgs); // `skills install` with no source restores skills-lock.json, like `npm install` if ((command === 'i' || command === 'install') && addSource.length === 0) { if (!inAgent) showLogo(); await runInstallFromLock(restArgs); break; } // JSON mode must keep stdout parseable — no logo if (!inAgent && !addOpts.json) showLogo(); - src/color.test.ts (3551 bytes)
import { describe, it, expect } from 'vitest'; import { execFileSync } from 'child_process'; import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'fs'; import { tmpdir } from 'os'; import { join } from 'path'; const SRC_DIR = import.meta.dirname; const CLI_PATH = join(SRC_DIR, 'cli.ts'); const ANSI = /\x1b\[/; /** * Runs the CLI in a subprocess writing to a pipe and returns the RAW stdout * (unlike runCli, which strips terminal escapes). A pipe is never a TTY, so * this is exactly the `| less`, `| code -` case. */ function runRaw(args: string[], overrides: Record<string, string> = {}): string { const env: NodeJS.ProcessEnv = { ...process.env, DISABLE_TELEMETRY: '1' }; // The detection contract is defined entirely by the overrides below. for (const key of ['NO_COLOR', 'FORCE_COLOR', 'CI', 'TERM']) delete env[key]; Object.assign(env, overrides); const cwd = mkdtempSync(join(tmpdir(), 'skills-color-test-')); try { return execFileSync(process.execPath, [CLI_PATH, ...args], { encoding: 'utf-8', cwd, stdio: ['pipe', 'pipe', 'pipe'], env, }); } finally { rmSync(cwd, { recursive: true, force: true }); } } describe('color support detection', () => { it.each(['list', '--help'])('emits no ANSI codes when piped: `skills %s`', (args) => { const output = runRaw([args]); expect(output.trim()).not.toBe(''); expect(output).not.toMatch(ANSI); }); it.each<Record<string, string>>([{ FORCE_COLOR: '1' }, { CI: 'true' }])( 'emits color when %o', (env) => { expect(runRaw(['list'], env)).toMatch(ANSI); } ); it('honors --color', () => { expect(runRaw(['list', '--color'])).toMatch(ANSI); }); it.each<Record<string, string>>([ { NO_COLOR: '1', FORCE_COLOR: '1' }, { NO_COLOR: '1', CI: 'true' }, ])('NO_COLOR wins: %o', (env) => { expect(runRaw(['list'], env)).not.toMatch(ANSI); }); it('honors --no-color over FORCE_COLOR', () => { expect(runRaw(['list', '--no-color'], { FORCE_COLOR: '1' })).not.toMatch(ANSI); }); }); /** Non-test source files under src/, as forward-slash paths relative to src/. */ function sourceFiles(): string[] { return readdirSync(SRC_DIR, { recursive: true, encoding: 'utf-8' }) .map((f) => f.replaceAll('\\', '/')) .filter((f) => f.endsWith('.ts') && !f.endsWith('.test.ts') && f !== 'test-utils.ts'); } describe('escape code hygiene', () => { // Files allowed to contain raw escape literals: // - color.ts: the gated palette itself // - sanitize.ts: regexes that strip escapes from untrusted metadata // - find.ts, prompts/search-multiselect.ts: cursor control for interactive // pickers, which only run on a TTY const ALLOWED = new Set(['color.ts', 'sanitize.ts', 'find.ts', 'prompts/search-multiselect.ts']); const RAW_ESCAPE = /\\x1b\[|\\u001b\[|\\033\[|\\e\[/; it('keeps raw ANSI literals out of the rest of src/', () => { const offenders = sourceFiles() .filter((f) => !ALLOWED.has(f)) .filter((f) => RAW_ESCAPE.test(readFileSync(join(SRC_DIR, f), 'utf-8'))); // Import from ./color.ts so NO_COLOR and pipes are respected. expect(offenders).toEqual([]); }); it('routes picocolors through color.ts', () => { const offenders = sourceFiles() .filter((f) => f !== 'color.ts') .filter((f) => /from ['"]picocolors['"]/.test(readFileSync(join(SRC_DIR, f), 'utf-8'))); // picocolors' own detection turns color on for every win32 process, pipes included. expect(offenders).toEqual([]); }); }); - src/color.ts (1762 bytes)
import { createColors } from 'picocolors'; /** * The single place that decides whether the CLI emits terminal escape codes. * * - `NO_COLOR` / `--no-color` disable color (https://no-color.org). * - `FORCE_COLOR` / `--color` / `CI` enable it. * - Otherwise stdout must be a TTY with `TERM != dumb`. * * This is picocolors' rule minus its "always on for win32" shortcut, which * would leak escapes into pipes on Windows. Import `pc` from here instead of * `picocolors` so every command follows it. * * Cursor/line control is separate: it only makes sense on a real terminal, so * it stays off in pipes even when color is forced. * * Do not write raw `\x1b[` literals elsewhere; add them here instead * (enforced by color.test.ts). */ const env = process.env; const argv = process.argv; const isTTY = process.stdout.isTTY === true; export const colorEnabled = !(env.NO_COLOR || argv.includes('--no-color')) && !!(env.FORCE_COLOR || argv.includes('--color') || env.CI || (isTTY && env.TERM !== 'dumb')); export const pc = createColors(colorEnabled); const sgr = (code: string): string => (colorEnabled ? `\x1b[${code}m` : ''); export const RESET = sgr('0'); export const BOLD = sgr('1'); // 256-color grays - visible on both light and dark backgrounds export const DIM = sgr('38;5;102'); // darker gray for secondary text export const TEXT = sgr('38;5;145'); // lighter gray for primary text export const CYAN = sgr('36'); export const YELLOW = sgr('33'); // 256-color middle grays (lighter → darker) for the logo gradient export const GRAYS = [250, 248, 245, 243, 240, 238].map((n) => sgr(`38;5;${n}`)); /** Returns the cursor to column 0 and erases the line; empty when not a TTY. */ export const CLEAR_LINE = isTTY ? '\r\x1b[K' : ''; - src/concurrency.ts (901 bytes)
const DEFAULT_FETCH_CONCURRENCY = 4; /** How many sources may clone or download at once; override with SKILLS_CLONE_CONCURRENCY. */ export function fetchConcurrency(): number { const parsed = Number.parseInt(process.env.SKILLS_CLONE_CONCURRENCY ?? '', 10); return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_FETCH_CONCURRENCY; } /** Map `items` through `fn` with at most `limit` in flight; results keep input order. */ export async function mapConcurrent<T, R>( items: readonly T[], fn: (item: T) => Promise<R>, limit = fetchConcurrency() ): Promise<R[]> { const results = new Array<R>(items.length); let next = 0; const worker = async () => { while (next < items.length) { const index = next++; results[index] = await fn(items[index]!); } }; await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); return results; } - src/constants.ts (262 bytes)
export const AGENTS_DIR = '.agents'; export const SKILLS_SUBDIR = 'skills'; export const UNIVERSAL_SKILLS_DIR = '.agents/skills'; /** Maximum skill-directory depth searched inside a known container by default. */ export const DEFAULT_SKILL_CONTAINER_DEPTH = 3;
- src/detect-agent.test.ts (1370 bytes)
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; describe('detectAgent', () => { beforeEach(() => { vi.resetModules(); vi.unstubAllEnvs(); }); afterEach(() => { vi.unstubAllEnvs(); }); it('does not treat Cursor integrated terminal (CURSOR_TRACE_ID only) as agent', async () => { vi.stubEnv('CURSOR_TRACE_ID', 'trace-123'); vi.stubEnv('CURSOR_AGENT', ''); vi.stubEnv('CURSOR_EXTENSION_HOST_ROLE', ''); const { detectAgent } = await import('./detect-agent.ts'); const result = await detectAgent(); expect(result.isAgent).toBe(false); }); it('treats Cursor agent execution (CURSOR_AGENT) as agent', async () => { vi.stubEnv('CURSOR_TRACE_ID', 'trace-123'); vi.stubEnv('CURSOR_AGENT', '1'); const { detectAgent } = await import('./detect-agent.ts'); const result = await detectAgent(); expect(result.isAgent).toBe(true); expect(result.agent?.name).toBe('cursor-cli'); }); it('treats Cursor agent execution (agent-exec role) as agent', async () => { vi.stubEnv('CURSOR_TRACE_ID', 'trace-123'); vi.stubEnv('CURSOR_EXTENSION_HOST_ROLE', 'agent-exec'); const { detectAgent } = await import('./detect-agent.ts'); const result = await detectAgent(); expect(result.isAgent).toBe(true); expect(result.agent?.name).toBe('cursor-cli'); }); }); - src/detect-agent.ts (2849 bytes)
import { determineAgent, type AgentResult } from '@vercel/detect-agent'; import { setDetectedAgent } from './telemetry.ts'; import type { AgentType } from './types.ts'; let cachedResult: AgentResult | null = null; /** * @vercel/detect-agent treats any CURSOR_TRACE_ID as a Cursor agent, but that * variable is also present in Cursor's integrated terminal for regular user * sessions. Require stronger execution signals before enabling agent mode. */ function hasStrongCursorAgentSignal(): boolean { return ( Boolean(process.env.CURSOR_AGENT?.trim()) || process.env.CURSOR_EXTENSION_HOST_ROLE === 'agent-exec' ); } function refineAgentResult(result: AgentResult): AgentResult { if (!result.isAgent || !result.agent) { return result; } if (result.agent.name === 'cursor' || result.agent.name === 'cursor-cli') { if (!hasStrongCursorAgentSignal()) { return { isAgent: false, agent: undefined }; } if (result.agent.name === 'cursor') { return { isAgent: true, agent: { name: 'cursor-cli' } }; } } return result; } /** * Map from @vercel/detect-agent names to skills-cli AgentType identifiers. * Only includes agents that exist in both systems. */ const agentNameToType: Record<string, AgentType> = { cursor: 'cursor', 'cursor-cli': 'cursor', claude: 'claude-code', cowork: 'claude-code', devin: 'universal', // Devin not in skills-cli agent list, use universal replit: 'replit', gemini: 'gemini-cli', codex: 'codex', antigravity: 'antigravity', 'augment-cli': 'augment', opencode: 'opencode', 'github-copilot': 'github-copilot', }; /** * Detect if the CLI is being run inside an AI agent environment. * Results are cached after the first call. Also updates telemetry with the agent name. */ export async function detectAgent(): Promise<AgentResult> { if (cachedResult) return cachedResult; cachedResult = refineAgentResult(await determineAgent()); if (cachedResult.isAgent) { setDetectedAgent(cachedResult.agent.name); } return cachedResult; } /** * Returns true if the CLI is running inside a detected AI agent. * When true, the CLI should skip interactive prompts and use sensible defaults. */ export async function isRunningInAgent(): Promise<boolean> { const result = await detectAgent(); return result.isAgent; } /** * Returns the name of the detected agent, or null if not running in an agent. */ export async function getAgentName(): Promise<string | null> { const result = await detectAgent(); return result.isAgent ? result.agent.name : null; } /** * Maps a detected agent name to the corresponding skills-cli AgentType. * Returns null if the agent can't be mapped to a specific skills-cli agent. */ export function getAgentType(agentName: string): AgentType | null { return agentNameToType[agentName] ?? null; } - src/diagnostics.ts (21505 bytes)
import { defineDiagnostics, Diagnostic, type InferDiagnosticCodes } from 'nostics'; import { ansiFormatter } from 'nostics/formatters/ansi'; import { pc } from './color.ts'; // An empty fix is omitted from the output. const availableSkills = (names: string[]) => names.length > 0 ? ['Available skills:', ...names.map((name) => ` - ${name}`)].join('\n') : ''; /** * Codes are `SKILLS_<WHAT_WENT_WRONG>` and permanent: never rename or reuse * one. Entries are grouped by area: command line, sources and skill selection, * download, archive, install, package.json "skills" field, Notion, * `skills use`, internal. Groups that callers match as a whole get their own * catalog below, so `catalog.is(error)` checks the group. */ const baseDiagnostics = defineDiagnostics({ // `why` is the full user-facing message; `fix` only carries guidance that is // printed as its own line. codes: { SKILLS_INVALID_AGENTS: { why: (p: { invalid: string[]; valid: string[] }) => `Invalid agents: ${p.invalid.join(', ')}`, fix: (p: { valid: string[] }) => `Valid agents: ${p.valid.join(', ')}`, }, SKILLS_OPTION_REQUIRES_VALUE: { why: (p: { option: string; value: string }) => `${p.option} requires ${p.value}`, }, SKILLS_OPTION_TAKES_NO_VALUE: { why: (p: { option: string }) => `${p.option} does not take a value`, }, SKILLS_UNKNOWN_OPTION: { why: (p: { option: string }) => `Unknown option: ${p.option}`, }, SKILLS_INVALID_OPTION_VALUE: { why: (p: { option: string; expected: string }) => `${p.option} must be ${p.expected}`, }, SKILLS_DUPLICATE_OPTION: { why: (p: { option: string }) => `Only one ${p.option} value can be provided`, }, SKILLS_REMOVE_ALL_WITH_NAMES: { why: 'Cannot combine --all with specific skill names.', fix: (p: { example: string }) => 'Use `skills remove --all` to remove every skill, or omit --all to remove only the named skills.' + `\n Example: skills remove ${p.example} -y`, }, SKILLS_PROMPT_REQUIRES_TTY: { why: 'Interactive prompt required but stdin is not a TTY. Nothing was installed. ' + "Use --agent <name> (or --agent '*') and -y to run non-interactively.", }, SKILLS_MISSING_ARGUMENT: { why: (p: { name: string }) => `Missing required argument: ${p.name}`, }, SKILLS_MULTIPLE_SOURCES: { why: (p: { received: string[] }) => `Expected one source, received ${p.received.length}: ${p.received.join(', ')}`, }, SKILLS_UNKNOWN_COMMAND: { why: (p: { command: string }) => `Unknown command: ${p.command}`, fix: 'Run skills --help for usage.', }, SKILLS_REMOVE_GLOBALLY_TRACKED: { why: (p: { skills: string[] }) => `Tracked in the global lock: ${p.skills.join(', ')}`, fix: (p: { skills: string[] }) => `Remove globally with: skills remove ${p.skills.join(' ')} -g`, }, SKILLS_REMOVE_UNTRACKED_SKIPPED: { why: (p: { skills: string[] }) => `Skipped ${p.skills.length} untracked skill(s) not recorded in the lock file: ${p.skills.join(', ')}`, fix: 'Remove them by name, e.g. skills remove <name>', }, SKILLS_REMOVE_UNMANAGED_DIR_KEPT: { why: (p: { path: string }) => `Kept ${p.path}: it is not an unmodified copy installed by skills`, fix: 'Delete it by hand if you no longer need it', }, SKILLS_UNSAFE_SUBPATH: { why: (p: { subpath: string }) => `Unsafe subpath: "${p.subpath}" contains path traversal segments. ` + `Subpaths must not contain ".." components.`, }, SKILLS_SUBPATH_OUTSIDE_REPO: { why: (p: { subpath: string }) => `Invalid subpath: "${p.subpath}" resolves outside the repository directory. Subpath must not contain ".." segments that escape the base path.`, }, SKILLS_NO_MATCHING_SKILLS: { why: (p: { requested: string[] }) => `No matching skills found for: ${p.requested.join(', ')}`, fix: (p: { available: string[] }) => availableSkills(p.available), }, SKILLS_NO_VALID_SKILLS: { why: 'No valid skills found. Skills require a SKILL.md with name and description.', }, SKILLS_MULTIPLE_SKILLS_IN_SOURCE: { why: (p: { names: string[] }) => [ 'This source contains multiple skills. Specify exactly one skill:', ...p.names.map((name) => ` - ${name}`), ].join('\n'), fix: (p: { source: string; names: string[] }) => { const example = p.names[0] ?? '<skill>'; return `Examples:\n skills use ${p.source}@${example}\n skills use ${p.source} --skill ${example}`; }, }, SKILLS_RENAME_MULTIPLE_SKILLS: { why: (p: { count: number }) => `--rename installs one skill under a new name, but ${p.count} skills were selected.`, fix: 'Pick one skill with --skill <name> or <source>@<skill>.', }, SKILLS_AMBIGUOUS_SKILL_SELECTOR: { why: (p: { selector: string }) => `Skill selector "${p.selector}" matched multiple skills.`, }, SKILLS_CONFLICTING_SKILL_SELECTORS: { why: (p: { fromSource: string; fromOption: string }) => `Conflicting skill selectors: source selects "${p.fromSource}" but --skill selects "${p.fromOption}". Provide one selector.`, }, SKILLS_LOCAL_PATH_NOT_FOUND: { why: (p: { path: string }) => `Local path does not exist: ${p.path}`, }, SKILLS_WELLKNOWN_SCOPE_NOT_FOUND: { why: (p: { scopePath: string; rootUrl: string }) => `No skills found for the scoped path '${p.scopePath}' on ${p.rootUrl}. ` + `Not falling back to the root skills index because that would install every skill the host publishes. ` + `Check the URL, or run 'skills add ${p.rootUrl}' to install from the root index.`, }, SKILLS_WELLKNOWN_DIGEST_MISMATCH: { why: (p: { skill: string; expected: string; actual: string }) => `Digest mismatch for skill '${p.skill}': expected ${p.expected}, received ${p.actual}.`, }, SKILLS_WELLKNOWN_FILE_FETCH_FAILED: { why: (p: { skill: string; path: string; status?: number }) => `Failed to download "${p.path}" for skill "${p.skill}"` + (p.status === undefined ? '.' : ` (HTTP ${p.status}).`) + ' The skill cannot be installed without all listed files.', }, SKILLS_WELLKNOWN_INDEX_NOT_FOUND: { why: 'No skills found at this URL. Make sure the server has a /.well-known/agent-skills/index.json or /.well-known/skills/index.json file.', }, SKILLS_SKILL_SKIPPED: { why: (p: { path: string; reason: string }) => `⚠ Skipped ${p.path} — ${p.reason}`, data: (p: { path: string }) => ({ path: p.path }), }, SKILLS_DOWNLOAD_HTTP_ERROR: { why: (p: { status: number }) => `Download failed with HTTP ${p.status}`, }, SKILLS_DOWNLOAD_TOO_LARGE: { why: (p: { maxBytes: number }) => `Download is larger than ${p.maxBytes} bytes. Set SKILLS_DOWNLOAD_MAX_BYTES to override.`, }, SKILLS_DOWNLOAD_NO_BODY: { why: 'Download response has no body', }, SKILLS_DOWNLOAD_EMPTY: { why: 'Downloaded URL is empty', }, SKILLS_DOWNLOAD_NOT_A_SKILL: { why: 'Downloaded URL is not a valid SKILL.md file or supported archive', }, SKILLS_DOWNLOAD_NOT_LOCKED: { why: (p: { url: string; skills: string[] }) => `Not recording ${p.skills.join(', ')} in the lock file: ${p.url} has a query string or credentials, which may be secret`, fix: 'To let `skills update` fetch it again, serve it from a URL without them.', }, // Never shown: callers treat an unreadable archive as "not an archive". SKILLS_ARCHIVE_INVALID: { why: (p: { reason: string }) => p.reason, }, SKILLS_ARCHIVE_MULTI_DISK_ZIP: { why: 'Multi-disk zip archives are not supported', }, SKILLS_ARCHIVE_UNSUPPORTED_COMPRESSION: { why: (p: { method: number }) => `Unsupported zip compression method: ${p.method}`, }, SKILLS_ARCHIVE_UNSUPPORTED_FORMAT: { why: 'Unsupported archive format', }, SKILLS_ARCHIVE_MISSING_SKILL_MD: { why: 'Archive missing root SKILL.md', }, SKILLS_WELLKNOWN_ARCHIVE_UNSAFE_PATH: { why: (p: { path: string }) => `Unsafe archive path: ${p.path}`, }, SKILLS_WELLKNOWN_ARCHIVE_TOO_LARGE: { why: 'Archive exceeds maximum unpacked size', }, SKILLS_WELLKNOWN_ARCHIVE_TOO_MANY_FILES: { why: 'Archive contains too many files', }, SKILLS_UNSAFE_SKILL_NAME: { why: 'Invalid skill name: potential path traversal detected', }, SKILLS_CATEGORY_DIR_CONFLICT: { why: (p: { path: string; skills: string[] }) => `Refusing to replace ${p.path}: it is a category directory with nested skills ` + `(${p.skills.slice(0, 8).join(', ')}${p.skills.length > 8 ? ', ...' : ''}). ` + 'Installing would delete them.', fix: 'Move or rename the category directory, then install again.', data: (p: { path: string; skills: string[] }) => ({ path: p.path, skills: p.skills }), }, SKILLS_CLEANUP_OUTSIDE_TEMP_DIR: { why: 'Attempted to clean up directory outside of temp directory', }, SKILLS_BROKEN_SYMLINK: { why: (p: { path: string }) => `Skipping broken symlink: ${p.path}`, data: (p: { path: string }) => ({ path: p.path }), }, SKILLS_LOCK_MISSING_SOURCE_URL: { why: (p: { skill: string }) => `Cannot restore ${p.skill}: skills-lock.json is missing sourceUrl for this generic Git source`, }, SKILLS_INVALID_LOCAL_LOCK: { why: (p: { path: string; reason: string }) => `Invalid ${p.path}: ${p.reason}. Fix or delete the file, then retry.`, }, SKILLS_LOCAL_LOCK_BUSY: { why: (p: { path: string }) => `Timed out waiting for ${p.path}: another skills process is updating skills-lock.json. If none is running, delete the file, then retry.`, }, SKILLS_SYMLINK_OUTSIDE_SKILL: { why: (p: { path: string }) => `Skipping symlink that points outside the skill directory: ${p.path}`, data: (p: { path: string }) => ({ path: p.path }), }, SKILLS_SYMLINK_CYCLE: { why: (p: { path: string }) => `Skipping symlink that creates a directory cycle: ${p.path}`, data: (p: { path: string }) => ({ path: p.path }), }, SKILLS_PACKAGE_SKILLS_NOT_ARRAY: { why: 'package.json: "skills" must be an array', }, SKILLS_PACKAGE_SKILLS_INVALID_ENTRY: { why: (p: { declarer: string; entry: string }) => `${p.declarer}: invalid "skills" entry ${p.entry}`, }, SKILLS_PACKAGE_SKILLS_NOT_GIT_SOURCE: { why: (p: { declarer: string; source: string }) => `${p.declarer}: "${p.source}" is not a git source`, }, SKILLS_PACKAGE_SKILLS_DUPLICATE_REF: { why: (p: { declarer: string; source: string }) => `${p.declarer}: "${p.source}" already has a ref; remove "ref"`, }, SKILLS_PACKAGE_SKILLS_REF_NOT_ALLOWED: { why: (p: { declarer: string; source: string }) => `${p.declarer}: "ref" cannot be used with "${p.source}"`, }, SKILLS_PACKAGE_SKILLS_UNRESOLVED_NPM: { why: (p: { declarer: string; pkg: string }) => `${p.declarer}: cannot resolve "npm:${p.pkg}"; is it a dependency?`, }, SKILLS_NOTION_CLI_MISSING: { why: 'Notion CLI (ntn) is required. Install it from:\nhttps://developers.notion.com/cli/get-started/overview\nThen run `ntn login`.', }, SKILLS_NOTION_API_FAILED: { why: (p: { stderr: string; exitCode: number | null }) => `ntn api failed${p.stderr ? `: ${p.stderr}` : ` with exit code ${p.exitCode ?? 'unknown'}`}`, }, SKILLS_NOTION_API_TIMEOUT: { why: (p: { seconds: number }) => `ntn api timed out after ${p.seconds} seconds`, }, SKILLS_NOTION_API_OUTPUT_TOO_LARGE: { why: 'ntn api output exceeded 10 MiB', }, SKILLS_NOTION_CLI_START_FAILED: { why: (p: { detail: string }) => `Unable to start ntn: ${p.detail}`, }, SKILLS_NOTION_RESPONSE_MISSING_FIELD: { why: (p: { response: 'response' | 'list response'; field: string }) => `Notion Agent Plugins ${p.response} is missing ${p.field}`, }, SKILLS_NOTION_RESPONSE_INVALID_FIELD: { why: (p: { response: 'response' | 'list response'; field: string }) => `Notion Agent Plugins ${p.response} has an invalid ${p.field}`, }, SKILLS_NOTION_INVALID_PACK: { why: 'Notion Agent Plugins response contains an invalid pack', }, SKILLS_NOTION_INVALID_LIST_RESPONSE: { why: 'Notion Agent Plugins list response is invalid', }, SKILLS_NOTION_INVALID_DIRECTORY_RESPONSE: { why: (p: { label: string }) => `Notion ${p.label} directory response is invalid`, }, SKILLS_NOTION_INVALID_JSON: { why: (p: { label: string }) => `ntn returned invalid JSON for ${p.label}`, }, SKILLS_NOTION_INVALID_CURSOR: { why: 'Notion Agent Plugins pagination returned an invalid cursor', }, SKILLS_NOTION_NO_PACKS: { why: 'Notion returned no packs for the authenticated workspace', }, SKILLS_NOTION_NO_MATCHING_PACKS: { why: (p: { requested: string[] }) => `No matching Notion packs found for: ${p.requested.join(', ')}`, }, SKILLS_NOTION_PACK_CHANGED: { why: (p: { pack: string }) => `Notion pack ${JSON.stringify(p.pack)} changed while preparing installation`, }, SKILLS_NOTION_PACK_PREPARE_FAILED: { why: (p: { pack: string; detail: string }) => `Failed to prepare Notion pack ${JSON.stringify(p.pack)}: ${p.detail}`, }, SKILLS_NOTION_PACK_NO_SKILLS: { why: 'pack contains no valid skills', }, SKILLS_USE_AGENT_UNSUPPORTED: { why: (p: { agent: string }) => `Running ${p.agent} is not supported yet.`, fix: (p: { supported: string[] }) => `Supported agents for skills use --agent: ${p.supported.join(', ')}`, }, SKILLS_USE_AGENT_COMMAND_NOT_FOUND: { why: (p: { agent: string; command: string }) => `Could not launch ${p.agent}: command not found: ${p.command}`, }, SKILLS_USE_AGENT_WILDCARD: { why: "skills use --agent does not support '*'; specify exactly one agent.", }, SKILLS_USE_MULTIPLE_AGENTS: { why: 'skills use --agent accepts exactly one agent.', }, SKILLS_USE_NO_MATCHING_SKILL: { why: (p: { selector: string }) => `No matching skill found for: ${p.selector}`, fix: (p: { available: string[] }) => availableSkills(p.available), }, // Programmatic API (src/api). Thrown, or carried as `code` by per-skill failures. SKILLS_SOURCE_FETCH_FAILED: { why: (p: { source: string; detail: string }) => `Could not fetch ${p.source}: ${p.detail}`, }, SKILLS_SOURCE_DISPOSED: { why: 'This source was already disposed. Resolve it again with resolveSource().', }, SKILLS_DUPLICATE_SKILL_NAME: { - src/download-source.ts (9787 bytes)
import { createWriteStream, type Stats } from 'node:fs'; import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { dirname, join, normalize, resolve, sep } from 'node:path'; import { pipeline } from 'node:stream/promises'; import * as tar from 'tar'; import type { Diagnostic } from 'nostics'; import { readZipArchive } from './archive.ts'; import { diagnostics, rejectedArchiveDiagnostics } from './diagnostics.ts'; import { parseFrontmatter } from './frontmatter.ts'; const DEFAULT_DOWNLOAD_MAX_BYTES = 10 * 1024 * 1024; const DEFAULT_EXTRACT_MAX_BYTES = 25 * 1024 * 1024; const DEFAULT_EXTRACT_MAX_FILES = 1000; const FETCH_TIMEOUT_MS = 30_000; interface DownloadLimits { downloadMaxBytes: number; extractMaxBytes: number; extractMaxFiles: number; } interface ExtractState { bytes: number; entries: number; } export interface DownloadedSource { rootDir: string; tempDir: string; kind: 'skill-md' | 'archive'; } export interface DownloadSourceOptions { downloadMaxBytes?: number; extractMaxBytes?: number; extractMaxFiles?: number; } function positiveIntegerOr(value: number | undefined, fallback: number): number { return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : fallback; } function getPositiveIntegerEnv(name: string, fallback: number): number { const raw = process.env[name]; if (!raw) return fallback; const parsed = Number.parseInt(raw, 10); return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; } function getDownloadLimits(options: DownloadSourceOptions): DownloadLimits { return { downloadMaxBytes: getPositiveIntegerEnv( 'SKILLS_DOWNLOAD_MAX_BYTES', positiveIntegerOr(options.downloadMaxBytes, DEFAULT_DOWNLOAD_MAX_BYTES) ), extractMaxBytes: getPositiveIntegerEnv( 'SKILLS_EXTRACT_MAX_BYTES', positiveIntegerOr(options.extractMaxBytes, DEFAULT_EXTRACT_MAX_BYTES) ), extractMaxFiles: getPositiveIntegerEnv( 'SKILLS_EXTRACT_MAX_FILES', positiveIntegerOr(options.extractMaxFiles, DEFAULT_EXTRACT_MAX_FILES) ), }; } function isPathSafe(basePath: string, targetPath: string): boolean { const normalizedBase = normalize(resolve(basePath)); const normalizedTarget = normalize(resolve(targetPath)); return normalizedTarget.startsWith(normalizedBase + sep) || normalizedTarget === normalizedBase; } function validateArchivePath(path: string): string | null { const normalized = path.replace(/\\/g, '/').replace(/^\.\//, ''); if (!normalized || normalized.endsWith('/')) return normalized; if (normalized.startsWith('/') || /^[a-zA-Z]:\//.test(normalized)) return null; if (normalized.split('/').includes('..')) return null; return normalized; } /** A readable archive whose contents are refused, as opposed to one that is not an archive at all. */ function isRejectedArchive(error: unknown): error is Diagnostic { return rejectedArchiveDiagnostics.is(error); } function incrementEntry(state: ExtractState, size: number, limits: DownloadLimits): void { state.entries += 1; if (state.entries > limits.extractMaxFiles) { throw diagnostics.SKILLS_ARCHIVE_TOO_MANY_FILES({ count: state.entries, max: limits.extractMaxFiles, overrideEnv: 'SKILLS_EXTRACT_MAX_FILES', }); } state.bytes += size; if (state.bytes > limits.extractMaxBytes) { throw diagnostics.SKILLS_ARCHIVE_TOO_LARGE({ maxBytes: limits.extractMaxBytes, overrideEnv: 'SKILLS_EXTRACT_MAX_BYTES', }); } } async function downloadToFile( url: string, targetFile: string, limits: DownloadLimits ): Promise<void> { const response = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), redirect: 'follow', }); if (!response.ok) { throw diagnostics.SKILLS_DOWNLOAD_HTTP_ERROR({ status: response.status }); } const contentLength = response.headers.get('content-length'); if (contentLength) { const parsed = Number.parseInt(contentLength, 10); if (Number.isFinite(parsed) && parsed > limits.downloadMaxBytes) { throw diagnostics.SKILLS_DOWNLOAD_TOO_LARGE({ maxBytes: limits.downloadMaxBytes }); } } if (!response.body) { throw diagnostics.SKILLS_DOWNLOAD_NO_BODY(); } let downloaded = 0; const limitStream = new TransformStream<Uint8Array, Uint8Array>({ transform(chunk, controller) { downloaded += chunk.byteLength; if (downloaded > limits.downloadMaxBytes) { throw diagnostics.SKILLS_DOWNLOAD_TOO_LARGE({ maxBytes: limits.downloadMaxBytes }); } controller.enqueue(chunk); }, }); await pipeline(response.body.pipeThrough(limitStream), createWriteStream(targetFile)); } async function isValidSkillMarkdown(filePath: string): Promise<boolean> { try { const content = await readFile(filePath, 'utf-8'); const { data } = parseFrontmatter(content); return typeof data.name === 'string' && typeof data.description === 'string'; } catch { return false; } } async function extractZip( filePath: string, extractDir: string, limits: DownloadLimits ): Promise<void> { const files = readZipArchive(await readFile(filePath), { maxExtractedBytes: limits.extractMaxBytes, maxEntries: limits.extractMaxFiles, }); for (const [path, contents] of files) { const targetPath = join(extractDir, path); if (!isPathSafe(extractDir, targetPath)) { throw diagnostics.SKILLS_ARCHIVE_UNSAFE_PATH({ path }); } await mkdir(dirname(targetPath), { recursive: true }); await writeFile(targetPath, contents); } } function getTarEntryType(entry: tar.ReadEntry | Stats): string { if (entry instanceof tar.ReadEntry) { return entry.type; } if (entry.isFile()) return 'File'; if (entry.isDirectory()) return 'Directory'; return ''; } function isTarEntryFile(entry: tar.ReadEntry | Stats): boolean { const type = getTarEntryType(entry); return type === 'File' || type === 'OldFile' || type === 'ContiguousFile'; } async function extractTar( filePath: string, extractDir: string, limits: DownloadLimits ): Promise<void> { const state: ExtractState = { bytes: 0, entries: 0 }; let validationError: Diagnostic | undefined; await tar.x({ strict: true, filter(entryPath, entry) { if (validationError) return false; try { const safePath = validateArchivePath(entryPath); if (safePath === null) { throw diagnostics.SKILLS_ARCHIVE_UNSAFE_PATH({ path: entryPath }); } const targetPath = join(extractDir, safePath); if (!isPathSafe(extractDir, targetPath)) { throw diagnostics.SKILLS_ARCHIVE_UNSAFE_PATH({ path: entryPath }); } incrementEntry(state, entry.size, limits); if (isTarEntryFile(entry)) { return true; } return getTarEntryType(entry) === 'Directory'; } catch (error) { if (isRejectedArchive(error)) { validationError = error; return false; } throw error; } }, cwd: extractDir, preservePaths: false, noChmod: true, file: filePath, }); if (validationError) { throw validationError; } } async function tryExtractArchive( filePath: string, extractDir: string, limits: DownloadLimits ): Promise<boolean> { const header = await readFile(filePath).then((buffer) => buffer.subarray(0, 512)); const isZip = header[0] === 0x50 && header[1] === 0x4b; const isGzip = header[0] === 0x1f && header[1] === 0x8b; try { if (isZip) { await extractZip(filePath, extractDir, limits); return true; } if (isGzip) { await extractTar(filePath, extractDir, limits); return true; } await extractTar(filePath, extractDir, limits); return true; } catch (error) { await rm(extractDir, { recursive: true, force: true }).catch(() => {}); await mkdir(extractDir, { recursive: true }); if (isRejectedArchive(error)) { throw error; } return false; } } async function getSingleTopLevelDirectory(dir: string): Promise<string | null> { const { readdir } = await import('node:fs/promises'); const entries = await readdir(dir, { withFileTypes: true }); const visibleEntries = entries.filter((entry) => entry.name !== '__MACOSX'); if (visibleEntries.length !== 1 || !visibleEntries[0]!.isDirectory()) return null; return join(dir, visibleEntries[0]!.name); } export async function downloadSource( url: string, options: DownloadSourceOptions = {} ): Promise<DownloadedSource> { const limits = getDownloadLimits(options); const tempDir = await mkdtemp(join(tmpdir(), 'skills-download-')); const downloadedFile = join(tempDir, 'source.download'); const extractDir = join(tempDir, 'extract'); try { await downloadToFile(url, downloadedFile, limits); const downloadedStats = await stat(downloadedFile); if (downloadedStats.size === 0) { throw diagnostics.SKILLS_DOWNLOAD_EMPTY(); } if (await isValidSkillMarkdown(downloadedFile)) { const skillDir = join(tempDir, 'skill'); await mkdir(skillDir, { recursive: true }); await writeFile(join(skillDir, 'SKILL.md'), await readFile(downloadedFile)); return { rootDir: skillDir, tempDir, kind: 'skill-md' }; } await mkdir(extractDir, { recursive: true }); if (await tryExtractArchive(downloadedFile, extractDir, limits)) { const rootDir = (await getSingleTopLevelDirectory(extractDir)) ?? extractDir; return { rootDir, tempDir, kind: 'archive' }; } throw diagnostics.SKILLS_DOWNLOAD_NOT_A_SKILL(); } catch (error) { await rm(tempDir, { recursive: true, force: true }).catch(() => {}); throw error; } } - src/find.test.ts (5992 bytes)
import { afterEach, describe, expect, it, vi } from 'vitest'; import { parseFindOptions, runFind, searchSkills, searchSkillsAPI } from './find.ts'; afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); vi.restoreAllMocks(); }); describe('parseFindOptions', () => { it('separates and normalizes an owner from a multi-word query', () => { expect(parseFindOptions(['react', 'native', '--owner', 'Vercel'])).toEqual({ query: 'react native', options: { owner: 'vercel' }, errors: [], }); }); it('supports the --owner=value form', () => { expect(parseFindOptions(['--owner=vercel-labs', 'next'])).toEqual({ query: 'next', options: { owner: 'vercel-labs' }, errors: [], }); }); it('rejects missing and invalid owners', () => { expect(parseFindOptions(['react', '--owner']).errors.map((e) => e.message)).toEqual([ '--owner requires a GitHub owner', ]); expect( parseFindOptions(['react', '--owner', 'not/an/owner']).errors.map((e) => e.message) ).toEqual(['--owner must be a valid GitHub owner']); }); }); describe('searchSkillsAPI', () => { it('sends the owner as an API query parameter', async () => { const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ skills: [] }), }); vi.stubGlobal('fetch', fetchMock); await searchSkillsAPI('react native', 'vercel'); const url = new URL(fetchMock.mock.calls[0]![0] as string); expect(url.pathname).toBe('/api/search'); expect(url.searchParams.get('q')).toBe('react native'); expect(url.searchParams.get('owner')).toBe('vercel'); expect(url.searchParams.has('limit')).toBe(false); }); it('preserves API relevance order over install counts', async () => { const skills = [ { id: 'owner/repo/eval-harness', name: 'eval-harness', installs: 100, source: 'owner/repo', }, { id: 'owner/repo/hyperframes-registry', name: 'hyperframes-registry', installs: 732200, source: 'owner/repo', }, ]; vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ skills }), }) ); const results = await searchSkillsAPI('eval'); expect(results.map((skill) => skill.name)).toEqual(['eval-harness', 'hyperframes-registry']); }); it('prints every result in API order for a non-interactive query', async () => { const skills = Array.from({ length: 25 }, (_, index) => ({ id: `owner/repo/skill-${index + 1}`, name: `skill-${index + 1}`, installs: index + 1, source: 'owner/repo', })); vi.stubGlobal( 'fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ skills }), }) ); vi.stubEnv('DISABLE_TELEMETRY', '1'); const log = vi.spyOn(console, 'log').mockImplementation(() => {}); await runFind(['owner/repo']); const output = log.mock.calls.map((args) => args.join(' ')).join('\n'); expect(output).toContain('owner/repo@skill-1'); expect(output).toContain('owner/repo@skill-25'); expect(output.indexOf('owner/repo@skill-1')).toBeLessThan( output.indexOf('owner/repo@skill-25') ); }); }); describe('searchSkills', () => { const skill = (name: string, installs = 1) => ({ id: `owner/repo/${name}`, name, installs, source: 'owner/repo', }); function stubSearch(byQuery: Record<string, ReturnType<typeof skill>[]>) { const fetchMock = vi.fn(async (input: string) => { const q = new URL(input).searchParams.get('q') ?? ''; return { ok: true, json: async () => ({ skills: byQuery[q] ?? [] }) }; }); vi.stubGlobal('fetch', fetchMock); return fetchMock; } it('does not fan out when the exact query has enough results', async () => { const many = Array.from({ length: 10 }, (_, i) => skill(`s-${i}`)); const fetchMock = stubSearch({ 'next bundle analyzer': many }); const result = await searchSkills('next bundle analyzer'); expect(fetchMock).toHaveBeenCalledTimes(1); expect(result.exactCount).toBe(10); }); it('does not fan out for single-term queries', async () => { const fetchMock = stubSearch({}); await searchSkills('analyzer'); expect(fetchMock).toHaveBeenCalledTimes(1); }); it('appends partial matches when an extra term hides a relevant skill', async () => { const fetchMock = stubSearch({ 'next bundle analyzer': [skill('next-bundle-analyzer')], 'bundle analyzer': [skill('bundle-analyzer'), skill('next-bundle-analyzer')], 'next analyzer': [skill('next-bundle-analyzer')], 'next bundle': [skill('next-bundle-optimizer', 3700), skill('next-perf')], }); const result = await searchSkills('next bundle analyzer'); expect(fetchMock).toHaveBeenCalledTimes(4); expect(result.exactCount).toBe(1); expect(result.skills.map((s) => s.name)).toEqual([ 'next-bundle-analyzer', 'next-bundle-optimizer', 'bundle-analyzer', 'next-perf', ]); }); it('ranks skills found by more subqueries first', async () => { stubSearch({ 'a b': [skill('only-ab')], 'a c': [skill('both')], 'b c': [skill('both')], }); const result = await searchSkills('a b c'); expect(result.exactCount).toBe(0); expect(result.skills.map((s) => s.name)).toEqual(['both', 'only-ab']); }); it('labels partial matches in non-interactive output', async () => { stubSearch({ 'next bundle': [skill('next-bundle-optimizer')] }); vi.stubEnv('DISABLE_TELEMETRY', '1'); const log = vi.spyOn(console, 'log').mockImplementation(() => {}); await runFind(['next', 'bundle', 'analyzer']); const output = log.mock.calls.map((args) => args.join(' ')).join('\n'); expect(output).toContain('No skills matched every term'); expect(output).toContain('owner/repo@next-bundle-optimizer'); }); }); - src/find.ts (14216 bytes)
import * as readline from 'readline'; import type { Diagnostic } from 'nostics'; import { runAdd, parseAddOptions } from './add.ts'; import { diagnostics, formatError } from './diagnostics.ts'; import { parseCliArgs } from './cli-args.ts'; import { sanitizeMetadata } from './sanitize.ts'; import { track } from './telemetry.ts'; import { isRepoPrivate } from './source-parser.ts'; import { isRunningInAgent } from './detect-agent.ts'; import { BOLD, CYAN, DIM, RESET, TEXT, YELLOW } from './color.ts'; // API endpoint for skills search const SEARCH_API_BASE = process.env.SKILLS_API_URL || 'https://skills.sh'; function formatInstalls(count: number): string { if (!count || count <= 0) return ''; if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1).replace(/\.0$/, '')}M installs`; if (count >= 1_000) return `${(count / 1_000).toFixed(1).replace(/\.0$/, '')}K installs`; return `${count} install${count === 1 ? '' : 's'}`; } export interface SearchSkill { name: string; slug: string; source: string; installs: number; } export interface FindOptions { owner?: string; } export interface ParseFindOptionsResult { query: string; options: FindOptions; errors: Diagnostic[]; } const GITHUB_OWNER_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,38})$/i; export function parseFindOptions(args: string[]): ParseFindOptionsResult { const { values, positionals, errors } = parseCliArgs(args, { owner: { type: 'string', value: 'a GitHub owner' }, }); const options: FindOptions = {}; const ownerValue = values.owner?.at(-1); if (ownerValue !== undefined) { const owner = ownerValue.trim().toLowerCase(); if (GITHUB_OWNER_PATTERN.test(owner)) { options.owner = owner; } else { errors.push( diagnostics.SKILLS_INVALID_OPTION_VALUE({ option: '--owner', expected: 'a valid GitHub owner', }) ); } } return { query: positionals.join(' '), options, errors }; } // Search via API export async function searchSkillsAPI(query: string, owner?: string): Promise<SearchSkill[]> { try { const params = new URLSearchParams({ q: query }); if (owner) params.set('owner', owner); const url = `${SEARCH_API_BASE}/api/search?${params.toString()}`; const res = await fetch(url); if (!res.ok) return []; const data = (await res.json()) as { skills: Array<{ id: string; name: string; installs: number; source: string; }>; }; return data.skills.map((skill) => ({ name: sanitizeMetadata(skill.name), slug: sanitizeMetadata(skill.id), source: sanitizeMetadata(skill.source || ''), installs: skill.installs, })); } catch { return []; } } // The search API requires every query term to match, so one extra word (e.g. // "next bundle analyzer") can hide an otherwise relevant skill. When a // multi-term query returns few results, retry with each term dropped and // append those partial matches after the exact ones. const MIN_EXACT_RESULTS = 10; const MAX_FALLBACK_TERMS = 6; const MAX_MERGED_RESULTS = 25; export interface SearchResult { skills: SearchSkill[]; /** Number of leading results that matched every query term. */ exactCount: number; } export async function searchSkills(query: string, owner?: string): Promise<SearchResult> { const exact = await searchSkillsAPI(query, owner); const terms = [...new Set(query.trim().split(/\s+/).filter(Boolean))]; if (exact.length >= MIN_EXACT_RESULTS || terms.length < 2 || terms.length > MAX_FALLBACK_TERMS) { return { skills: exact, exactCount: exact.length }; } const subqueries = terms.map((_, i) => terms.filter((_, j) => j !== i).join(' ')); const partialLists = await Promise.all(subqueries.map((q) => searchSkillsAPI(q, owner))); const seen = new Set(exact.map((skill) => skill.slug)); const candidates = new Map<string, { skill: SearchSkill; hits: number; bestRank: number }>(); for (const list of partialLists) { list.forEach((skill, rank) => { if (seen.has(skill.slug)) return; const entry = candidates.get(skill.slug); if (entry) { entry.hits++; entry.bestRank = Math.min(entry.bestRank, rank); } else { candidates.set(skill.slug, { skill, hits: 1, bestRank: rank }); } }); } const partial = [...candidates.values()] .sort( (a, b) => b.hits - a.hits || a.bestRank - b.bestRank || (b.skill.installs || 0) - (a.skill.installs || 0) ) .slice(0, Math.max(0, MAX_MERGED_RESULTS - exact.length)) .map((entry) => entry.skill); return { skills: [...exact, ...partial], exactCount: exact.length }; } // ANSI escape codes for terminal control const HIDE_CURSOR = '\x1b[?25l'; const SHOW_CURSOR = '\x1b[?25h'; const CLEAR_DOWN = '\x1b[J'; const MOVE_UP = (n: number) => `\x1b[${n}A`; const MOVE_TO_COL = (n: number) => `\x1b[${n}G`; // Custom fzf-style search prompt using raw readline async function runSearchPrompt(initialQuery = '', owner?: string): Promise<SearchSkill | null> { let results: SearchSkill[] = []; let selectedIndex = 0; let query = initialQuery; let loading = false; let debounceTimer: ReturnType<typeof setTimeout> | null = null; let lastRenderedLines = 0; // Enable raw mode for keypress events if (process.stdin.isTTY) { process.stdin.setRawMode(true); } // Setup readline for keypress events but don't let it echo readline.emitKeypressEvents(process.stdin); // Resume stdin to start receiving events process.stdin.resume(); // Hide cursor during selection process.stdout.write(HIDE_CURSOR); function render(): void { // Move cursor up to overwrite previous render if (lastRenderedLines > 0) { process.stdout.write(MOVE_UP(lastRenderedLines) + MOVE_TO_COL(1)); } // Clear from cursor to end of screen (removes ghost trails) process.stdout.write(CLEAR_DOWN); const lines: string[] = []; // Search input line with cursor const cursor = `${BOLD}_${RESET}`; lines.push(`${TEXT}Search skills:${RESET} ${query}${cursor}`); lines.push(''); // Results - keep showing existing results while loading new ones if (!query || query.length < 2) { lines.push(`${DIM}Start typing to search (min 2 chars)${RESET}`); } else if (results.length === 0 && loading) { lines.push(`${DIM}Searching…${RESET}`); } else if (results.length === 0) { lines.push(`${DIM}No skills found${RESET}`); } else { const maxVisible = 8; const visible = results.slice(0, maxVisible); for (let i = 0; i < visible.length; i++) { const skill = visible[i]!; const isSelected = i === selectedIndex; const arrow = isSelected ? `${BOLD}>${RESET}` : ' '; const name = isSelected ? `${BOLD}${skill.name}${RESET}` : `${TEXT}${skill.name}${RESET}`; const source = skill.source ? ` ${DIM}${skill.source}${RESET}` : ''; const installs = formatInstalls(skill.installs); const installsBadge = installs ? ` ${CYAN}${installs}${RESET}` : ''; const loadingIndicator = loading && i === 0 ? ` ${DIM}…${RESET}` : ''; lines.push(` ${arrow} ${name}${source}${installsBadge}${loadingIndicator}`); } } lines.push(''); lines.push(`${DIM}up/down navigate | enter select | esc cancel${RESET}`); // Write each line for (const line of lines) { process.stdout.write(line + '\n'); } lastRenderedLines = lines.length; } function triggerSearch(q: string): void { // Always clear any pending debounce timer if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = null; } // Always reset loading state when starting a new search loading = false; if (!q || q.length < 2) { results = []; selectedIndex = 0; render(); return; } // Use API search for all queries (debounced) loading = true; render(); // Adaptive debounce: shorter queries = longer wait (user still typing) // 2 chars: 250ms, 3 chars: 200ms, 4 chars: 150ms, 5+ chars: 150ms const debounceMs = Math.max(150, 350 - q.length * 50); debounceTimer = setTimeout(async () => { try { results = (await searchSkills(q, owner)).skills; selectedIndex = 0; } catch { results = []; } finally { loading = false; debounceTimer = null; render(); } }, debounceMs); } // Trigger initial search if there's a query, then render if (initialQuery) { triggerSearch(initialQuery); } render(); return new Promise((resolve) => { function cleanup(): void { process.stdin.removeListener('keypress', handleKeypress); if (process.stdin.isTTY) { process.stdin.setRawMode(false); } process.stdout.write(SHOW_CURSOR); // Pause stdin to fully release it for child processes process.stdin.pause(); } function handleKeypress(_ch: string | undefined, key: readline.Key): void { if (!key) return; if (key.name === 'escape' || (key.ctrl && key.name === 'c')) { // Cancel cleanup(); resolve(null); return; } if (key.name === 'return') { // Submit cleanup(); resolve(results[selectedIndex] || null); return; } if (key.name === 'up') { selectedIndex = Math.max(0, selectedIndex - 1); render(); return; } if (key.name === 'down') { selectedIndex = Math.min(Math.max(0, results.length - 1), selectedIndex + 1); render(); return; } if (key.name === 'backspace') { if (query.length > 0) { query = query.slice(0, -1); triggerSearch(query); } return; } // Regular character input if (key.sequence && !key.ctrl && !key.meta && key.sequence.length === 1) { const char = key.sequence; if (char >= ' ' && char <= '~') { query += char; triggerSearch(query); } } } process.stdin.on('keypress', handleKeypress); }); } // Parse owner/repo from a package string (for the find command) function getOwnerRepoFromString(pkg: string): { owner: string; repo: string } | null { // Handle owner/repo or owner/repo@skill const atIndex = pkg.lastIndexOf('@'); const repoPath = atIndex > 0 ? pkg.slice(0, atIndex) : pkg; const match = repoPath.match(/^([^/]+)\/([^/]+)$/); if (match) { return { owner: match[1]!, repo: match[2]! }; } return null; } async function isRepoPublic(owner: string, repo: string): Promise<boolean> { const isPrivate = await isRepoPrivate(owner, repo); // Return true only if we know it's public (isPrivate === false) // Return false if private or unable to determine return isPrivate === false; } export async function runFind(args: string[]): Promise<void> { const { query, options: findOptions, errors } = parseFindOptions(args); const owner = findOptions.owner; const isNonInteractive = !process.stdin.isTTY; const agentTip = `${DIM}Tip: if running in a coding agent, follow these steps:${RESET} ${DIM} 1) npx skills find [query] [--owner <owner>]${RESET} ${DIM} 2) npx skills add <owner/repo@skill>${RESET}`; if (errors.length > 0) { for (const error of errors) console.error(formatError(error)); console.error('Usage: npx skills find <query> [--owner <owner>]'); return; } // Non-interactive mode: just print results and exit if (query) { const { skills: results, exactCount } = await searchSkills(query, owner); // Track telemetry for non-interactive search track({ event: 'find', query, resultCount: String(results.length), }); if (results.length === 0) { const ownerSuffix = owner ? ` from owner "${owner}"` : ''; console.log(`${DIM}No skills found for "${query}"${ownerSuffix}${RESET}`); return; } console.log(`${DIM}Install with${RESET} npx skills add <owner/repo@skill>`); console.log(); for (const [index, skill] of results.entries()) { if (index === exactCount) { console.log( exactCount === 0 ? `${DIM}No skills matched every term in "${query}". Partial matches:${RESET}` : `${DIM}Partial matches (some terms of "${query}"):${RESET}` ); console.log(); } const pkg = skill.source || skill.slug; const installs = formatInstalls(skill.installs); console.log( `${TEXT}${pkg}@${skill.name}${RESET}${installs ? ` ${CYAN}${installs}${RESET}` : ''}` ); console.log(`${DIM}└ https://skills.sh/${skill.slug}${RESET}`); console.log(); } return; } // Skip interactive search when running inside an AI agent or non-TTY if (isNonInteractive || (await isRunningInAgent())) { console.log(agentTip); console.log(); console.log(`${DIM}Usage: npx skills find <query> [--owner <owner>]${RESET}`); return; } const selected = await runSearchPrompt('', owner); // Track telemetry for interactive search track({ event: 'find', query: '', resultCount: selected ? '1' : '0', interactive: '1', }); if (!selected) { console.log(`${DIM}Search cancelled${RESET}`); console.log(); return; } // Use source (owner/repo) and skill name for installation const pkg = selected.source || selected.slug; const skillName = selected.name; console.log(); console.log(`${TEXT}Installing ${BOLD}${skillName}${RESET} from ${DIM}${pkg}${RESET}…`); console.log(); // Run add directly since we're in the same CLI const { source, options: addOptions } = parseAddOptions([pkg, '--skill', skillName]); await runAdd(source, addOptions); console.log(); const info = getOwnerRepoFromString(pkg); if (info && (await isRepoPublic(info.owner, info.repo))) { console.log( `${DIM}View the skill at${RESET} ${TEXT}https://skills.sh/${selected.slug}${RESET}` ); } else { console.log(`${DIM}Discover more skills at${RESET} ${TEXT}https://skills.sh${RESET}`); } console.log(); } - src/frontmatter.test.ts (3472 bytes)
import { describe, it, expect } from 'vitest'; import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { parseFrontmatter, setFrontmatterName } from './frontmatter.ts'; import { parseSkillMd } from './skills.ts'; describe('parseFrontmatter', () => { it.each([ ['LF', '\n', ''], ['CRLF', '\r\n', ''], ['BOM and LF', '\n', '\uFEFF'], ['BOM and CRLF', '\r\n', '\uFEFF'], ])('reads YAML with %s', (_label, newline, prefix) => { const raw = prefix + ['---', 'name: example', 'description: Example skill', '---', '# Body', ''].join(newline); expect(parseFrontmatter(raw)).toEqual({ data: { name: 'example', description: 'Example skill' }, content: '# Body' + newline, }); }); it.each(['', '\uFEFF'])('keeps JavaScript frontmatter unsupported (prefix %j)', (prefix) => { const raw = prefix + '---js\n({ name: "example", description: "Example skill" })\n---\n# Body'; expect(parseFrontmatter(raw)).toEqual({ data: {}, content: raw }); }); it('preserves text without frontmatter', () => { const raw = '\uFEFF# Body\n'; expect(parseFrontmatter(raw)).toEqual({ data: {}, content: raw }); }); }); describe('parseSkillMd', () => { it.each(['\n', '\r\n'])('loads a BOM-prefixed skill with newline %j', async (newline) => { const dir = await mkdtemp(join(tmpdir(), 'skills-bom-')); const path = join(dir, 'SKILL.md'); const raw = '\uFEFF' + ['---', 'name: example', 'description: Example skill', '---', '# Body', ''].join(newline); try { await writeFile(path, raw, 'utf8'); const skill = await parseSkillMd(path); expect(skill).toMatchObject({ name: 'example', description: 'Example skill', path: dir, rawContent: raw, }); } finally { await rm(dir, { recursive: true, force: true }); } }); }); describe('setFrontmatterName', () => { it('replaces the name and keeps everything else byte for byte', () => { const raw = '---\nname: alpha\ndescription: d\nlicense: MIT\n---\n# Body\nname: alpha\n'; expect(setFrontmatterName(raw, 'beta')).toBe( '---\nname: beta\ndescription: d\nlicense: MIT\n---\n# Body\nname: alpha\n' ); }); it('keeps CRLF line endings and a BOM', () => { const raw = '\uFEFF---\r\nname: alpha\r\ndescription: d\r\n---\r\n# Body\r\n'; expect(setFrontmatterName(raw, 'beta')).toBe( '\uFEFF---\r\nname: beta\r\ndescription: d\r\n---\r\n# Body\r\n' ); }); it('replaces a quoted or multi-line name', () => { expect(setFrontmatterName('---\nname: "Alpha Skill"\ndescription: d\n---\n', 'beta')).toBe( '---\nname: beta\ndescription: d\n---\n' ); expect( setFrontmatterName('---\nname: >\n Alpha\n Skill\ndescription: d\n---\n', 'beta') ).toBe('---\nname: beta\ndescription: d\n---\n'); }); it('adds a missing name first', () => { expect(setFrontmatterName('---\ndescription: d\n---\n', 'beta')).toBe( '---\nname: beta\ndescription: d\n---\n' ); }); it('quotes names YAML would read as another type', () => { const renamed = setFrontmatterName('---\nname: alpha\n---\n', '123'); expect(parseFrontmatter(renamed).data.name).toBe('123'); }); it('leaves content without frontmatter unchanged', () => { expect(setFrontmatterName('# Just markdown\n', 'beta')).toBe('# Just markdown\n'); }); }); - src/frontmatter.ts (1615 bytes)
import { parse as parseYaml, stringify } from 'yaml'; /** * Minimal frontmatter parser. Only supports YAML (the `---` delimiter). * Does NOT support `---js` / `---javascript` to avoid eval()-based RCE * that exists in gray-matter's built-in JS engine. */ export function parseFrontmatter(raw: string): { data: Record<string, unknown>; content: string; } { const match = raw.match(/^\uFEFF?---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/); if (!match) return { data: {}, content: raw }; const data = (parseYaml(match[1]!) as Record<string, unknown>) ?? {}; return { data, content: match[2] ?? '' }; } /** * `raw` with its frontmatter `name` set to `name`, replacing the existing * value (including the continuation lines of a multi-line one) or adding it * first. Everything else is kept byte for byte. Without frontmatter, `raw` is * returned unchanged. */ export function setFrontmatterName(raw: string, name: string): string { const match = raw.match(/^(\uFEFF?---(\r?\n))([\s\S]*?)(\r?\n---(?:\r?\n|$))/); if (!match) return raw; const [whole, open, eol, body, close] = match as unknown as [ string, string, string, string, string, ]; const nameLine = stringify({ name }).trimEnd(); const lines = body.split(/\r?\n/); const index = lines.findIndex((line) => /^name\s*:/.test(line)); if (index === -1) { lines.unshift(nameLine); } else { let end = index + 1; while (end < lines.length && /^[ \t]/.test(lines[end]!)) end++; lines.splice(index, end - index, nameLine); } return open + lines.join(eol) + close + raw.slice(whole.length); } - src/git.test.ts (19436 bytes)
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { rmSync } from 'fs'; const simpleGitMock = vi.hoisted(() => vi.fn()); const execFileMock = vi.hoisted(() => vi.fn()); vi.mock('simple-git', () => ({ simpleGit: simpleGitMock, })); vi.mock('child_process', async () => { const actual = await vi.importActual<typeof import('child_process')>('child_process'); return { ...actual, execFile: execFileMock, }; }); import { cloneRepo, getGitTreeHash, isCommitSha, isGitHubHttpsCloneUrl, isGitHubSsoAuthError, isMissingRefError, parseGitHubRepoUrl, } from './git.ts'; function createGitClientMock(clone: ReturnType<typeof vi.fn>) { const client = { clone, env: vi.fn(), cwd: vi.fn(), submoduleUpdate: vi.fn(), }; client.env.mockReturnValue(client); client.cwd.mockResolvedValue(client); client.submoduleUpdate.mockResolvedValue(undefined); return client; } // A client mock for the commit-SHA fetch path (cloneAtSha): // cwd().init().addRemote().fetch().checkout(). function createShaClientMock(overrides: Partial<Record<string, ReturnType<typeof vi.fn>>> = {}) { const env = vi.fn(); const client = { cwd: overrides.cwd ?? vi.fn().mockResolvedValue(undefined), init: overrides.init ?? vi.fn().mockResolvedValue(undefined), addRemote: overrides.addRemote ?? vi.fn().mockResolvedValue(undefined), fetch: overrides.fetch ?? vi.fn().mockResolvedValue(undefined), checkout: overrides.checkout ?? vi.fn().mockResolvedValue(undefined), env, }; env.mockReturnValue(client); return client; } const FULL_SHA = '6c6076a293e7ffeb108bad2a231cbd855890d3b5'; function mockExecFileSuccess(stdout = '', stderr = '') { execFileMock.mockImplementationOnce( (_file: string, _args: string[], _options: unknown, callback: (...args: unknown[]) => void) => { callback(null, stdout, stderr); } ); } function mockExecFileError(message: string) { execFileMock.mockImplementationOnce( (_file: string, _args: string[], _options: unknown, callback: (...args: unknown[]) => void) => { const error = Object.assign(new Error(message), { code: 1 }); callback(error, '', message); } ); } describe('git clone fallbacks', () => { const createdDirs: string[] = []; beforeEach(() => { simpleGitMock.mockReset(); execFileMock.mockReset(); }); afterEach(() => { vi.unstubAllEnvs(); for (const dir of createdDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); } }); it('parses GitHub HTTPS and SSH clone URLs', () => { expect(parseGitHubRepoUrl('https://github.com/Giphy/giphy-codex-skills.git')).toEqual({ owner: 'Giphy', repo: 'giphy-codex-skills', slug: 'Giphy/giphy-codex-skills', sshUrl: '[email protected]:Giphy/giphy-codex-skills.git', }); expect(parseGitHubRepoUrl('[email protected]:Giphy/giphy-codex-skills.git')).toEqual({ owner: 'Giphy', repo: 'giphy-codex-skills', slug: 'Giphy/giphy-codex-skills', sshUrl: '[email protected]:Giphy/giphy-codex-skills.git', }); }); it('recognizes the configured GitHub Enterprise host', () => { vi.stubEnv('GH_HOST', 'github.example.com'); expect(parseGitHubRepoUrl('https://github.example.com/acme/agent-skills.git')).toEqual({ owner: 'acme', repo: 'agent-skills', slug: 'acme/agent-skills', sshUrl: '[email protected]:acme/agent-skills.git', }); expect(isGitHubHttpsCloneUrl('https://github.example.com/acme/agent-skills.git')).toBe(true); }); it('detects GitHub SAML SSO clone failures', () => { expect( isGitHubSsoAuthError("remote: The 'Giphy' organization has enabled or enforced SAML SSO.") ).toBe(true); expect(isGitHubSsoAuthError('fatal: Authentication failed')).toBe(false); }); it('only enables automatic auth fallback for GitHub HTTPS clone URLs', () => { expect(isGitHubHttpsCloneUrl('https://github.com/Giphy/giphy-codex-skills.git')).toBe(true); expect(isGitHubHttpsCloneUrl('http://github.com/Giphy/giphy-codex-skills.git')).toBe(false); expect(isGitHubHttpsCloneUrl('[email protected]:Giphy/giphy-codex-skills.git')).toBe(false); expect(isGitHubHttpsCloneUrl('https://gitlab.com/Giphy/giphy-codex-skills.git')).toBe(false); }); it('allows the hard-coded LFS filter overrides required for clone', async () => { vi.stubEnv('EDITOR', 'skills-test-editor'); vi.stubEnv('GIT_ASKPASS', 'skills-test-askpass'); vi.stubEnv('PAGER', 'skills-test-pager'); const clone = vi.fn().mockResolvedValue(undefined); const client = createGitClientMock(clone); const submoduleClient = createGitClientMock(vi.fn()); simpleGitMock.mockReturnValueOnce(client).mockReturnValueOnce(submoduleClient); const tempDir = await cloneRepo('https://github.com/Giphy/giphy-codex-skills.git'); createdDirs.push(tempDir); expect(simpleGitMock).toHaveBeenCalledWith( expect.objectContaining({ config: [ 'filter.lfs.required=false', 'filter.lfs.smudge=', 'filter.lfs.clean=', 'filter.lfs.process=', 'core.longpaths=true', ], unsafe: { allowUnsafeAlias: true, allowUnsafeAskPass: true, allowUnsafeCommandBinaries: true, allowUnsafeConfigEnvCount: true, allowUnsafeConfigPaths: true, allowUnsafeCredentialHelper: true, allowUnsafeDiffExternal: true, allowUnsafeDiffTextConv: true, allowUnsafeEditor: true, allowUnsafeExec: true, allowUnsafeFilter: true, allowUnsafeFsMonitor: true, allowUnsafeGpgProgram: true, allowUnsafeGitProxy: true, allowUnsafeHooksPath: true, allowUnsafeInclude: true, allowUnsafeMergeDriver: true, allowUnsafePack: true, allowUnsafePager: true, allowUnsafeProtocolOverride: true, allowUnsafeSshCommand: true, allowUnsafeSubmodule: true, allowUnsafeTemplateDir: true, allowUnsafeUrlRewrite: true, }, allowEnvironment: expect.arrayContaining([ 'EDITOR', 'GIT_ASKPASS', 'GIT_TERMINAL_PROMPT', 'GIT_LFS_SKIP_SMUDGE', 'PAGER', ]), }) ); expect(simpleGitMock.mock.calls[0]![0]).not.toHaveProperty('env'); expect(client.env).toHaveBeenCalledWith( expect.objectContaining({ EDITOR: 'skills-test-editor', GIT_ASKPASS: 'skills-test-askpass', GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', PAGER: 'skills-test-pager', }) ); expect(submoduleClient.cwd).toHaveBeenCalledWith(tempDir); expect(submoduleClient.submoduleUpdate).toHaveBeenCalledWith([ '--init', '--recursive', '--depth', '1', ]); }); it('warns but completes the clone when submodule initialization fails', async () => { const clone = vi.fn().mockResolvedValue(undefined); const submoduleClient = createGitClientMock(vi.fn()); submoduleClient.submoduleUpdate.mockRejectedValue(new Error('submodule access denied')); simpleGitMock .mockReturnValueOnce(createGitClientMock(clone)) .mockReturnValueOnce(submoduleClient); const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}); const tempDir = await cloneRepo('https://gitlab.com/acme/skills.git'); createdDirs.push(tempDir); expect(warning).toHaveBeenCalledWith( 'Warning: failed to initialize Git submodules; installed skills may be incomplete.' ); }); it('falls back to gh repo clone for GitHub HTTPS auth failures', async () => { const primaryClone = vi .fn() .mockRejectedValue( new Error( "remote: The 'Giphy' organization has enabled or enforced SAML SSO.\n" + "fatal: unable to access 'https://github.com/Giphy/giphy-codex-skills.git/': The requested URL returned error: 403" ) ); const submoduleClient = createGitClientMock(vi.fn()); simpleGitMock .mockReturnValueOnce(createGitClientMock(primaryClone)) .mockReturnValueOnce(submoduleClient); mockExecFileSuccess('Git operations protocol: https\n'); mockExecFileSuccess(); const tempDir = await cloneRepo('https://github.com/Giphy/giphy-codex-skills.git'); createdDirs.push(tempDir); expect(execFileMock).toHaveBeenNthCalledWith( 1, 'gh', ['auth', 'status', '-h', 'github.com'], expect.any(Object), expect.any(Function) ); expect(submoduleClient.submoduleUpdate).toHaveBeenCalledWith([ '--init', '--recursive', '--depth', '1', ]); expect(execFileMock).toHaveBeenNthCalledWith( 2, 'gh', ['repo', 'clone', 'Giphy/giphy-codex-skills', tempDir, '--', '--depth=1'], expect.any(Object), expect.any(Function) ); }); it('uses the enterprise host for gh authentication fallback', async () => { vi.stubEnv('GH_HOST', 'github.example.com'); const primaryClone = vi.fn().mockRejectedValue(new Error('fatal: Authentication failed')); simpleGitMock .mockReturnValueOnce(createGitClientMock(primaryClone)) .mockReturnValueOnce(createGitClientMock(vi.fn())); mockExecFileSuccess('Git operations protocol: https\n'); mockExecFileSuccess(); const tempDir = await cloneRepo('https://github.example.com/acme/agent-skills.git'); createdDirs.push(tempDir); expect(execFileMock).toHaveBeenNthCalledWith( 1, 'gh', ['auth', 'status', '-h', 'github.example.com'], expect.any(Object), expect.any(Function) ); expect(execFileMock).toHaveBeenNthCalledWith( 2, 'gh', ['repo', 'clone', 'acme/agent-skills', tempDir, '--', '--depth=1'], expect.any(Object), expect.any(Function) ); }); it('falls back to SSH when gh clone is unavailable or fails', async () => { const primaryClone = vi.fn().mockRejectedValue(new Error('fatal: Authentication failed')); const sshClone = vi.fn().mockResolvedValue(undefined); const primaryClient = createGitClientMock(primaryClone); const sshClient = createGitClientMock(sshClone); const submoduleClient = createGitClientMock(vi.fn()); simpleGitMock .mockReturnValueOnce(primaryClient) .mockReturnValueOnce(sshClient) .mockReturnValueOnce(submoduleClient); mockExecFileSuccess('Git operations protocol: ssh\n'); mockExecFileError('gh repo clone failed'); const tempDir = await cloneRepo('https://github.com/Giphy/giphy-codex-skills.git'); createdDirs.push(tempDir); expect(sshClone).toHaveBeenCalledWith('[email protected]:Giphy/giphy-codex-skills.git', tempDir, [ '--depth', '1', ]); expect(sshClient.env).toHaveBeenCalledWith( expect.objectContaining({ GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? 'ssh -o BatchMode=yes', }) ); expect(submoduleClient.env).toHaveBeenCalledWith( expect.objectContaining({ GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? 'ssh -o BatchMode=yes', }) ); }); it('surfaces a targeted SAML SSO message when all fallbacks fail', async () => { const primaryClone = vi .fn() .mockRejectedValue( new Error( "remote: The 'Giphy' organization has enabled or enforced SAML SSO.\n" + "fatal: unable to access 'https://github.com/Giphy/giphy-codex-skills.git/': The requested URL returned error: 403" ) ); const sshClone = vi.fn().mockRejectedValue(new Error('Permission denied (publickey).')); simpleGitMock .mockReturnValueOnce(createGitClientMock(primaryClone)) .mockReturnValueOnce(createGitClientMock(sshClone)); mockExecFileError('gh auth unavailable'); try { await cloneRepo('https://github.com/Giphy/giphy-codex-skills.git'); throw new Error('Expected cloneRepo to throw'); } catch (error) { expect(error).toMatchObject({ code: 'SKILLS_GIT_SAML_SSO_BLOCKED' }); expect((error as Error).message).toMatch(/SAML SSO/); expect((error as Error).message).toMatch(/git@github\.com:Giphy\/giphy-codex-skills\.git/); } }); it('does not try gh fallback for GitLab clone URLs', async () => { const primaryClone = vi .fn() .mockRejectedValue( new Error('fatal: unable to access repo: The requested URL returned error: 403') ); simpleGitMock.mockReturnValueOnce(createGitClientMock(primaryClone)); await expect( cloneRepo('https://gitlab.com/Giphy/giphy-codex-skills.git') ).rejects.toMatchObject({ code: 'SKILLS_GIT_AUTH_FAILED' }); expect(execFileMock).not.toHaveBeenCalled(); }); it('does not try gh fallback for GitHub SSH clone URLs', async () => { const primaryClone = vi.fn().mockRejectedValue(new Error('Permission denied (publickey).')); simpleGitMock.mockReturnValueOnce(createGitClientMock(primaryClone)); await expect(cloneRepo('[email protected]:Giphy/giphy-codex-skills.git')).rejects.toMatchObject({ code: 'SKILLS_GIT_AUTH_FAILED', }); expect(execFileMock).not.toHaveBeenCalled(); }); it('reads a locked skill folder tree hash from an authenticated clone', async () => { const treeHash = 'a'.repeat(40); mockExecFileSuccess(`${treeHash}\n`); await expect( getGitTreeHash('/tmp/private-repo', 'skills/private-skill/SKILL.md') ).resolves.toBe(treeHash); expect(execFileMock).toHaveBeenCalledWith( 'git', [ '-C', '/tmp/private-repo', 'rev-parse', '--verify', '--end-of-options', 'HEAD:skills/private-skill', ], expect.any(Object), expect.any(Function) ); }); it('rejects the command-executing ext transport before invoking git', async () => { await expect(cloneRepo('ext::sh -c id')).rejects.toThrow('Unsupported Git transport: ext'); expect(simpleGitMock).not.toHaveBeenCalled(); expect(execFileMock).not.toHaveBeenCalled(); }); it('falls back to a commit-SHA fetch when --branch reports a missing ref', async () => { const primaryClone = vi .fn() .mockRejectedValue( new Error(`fatal: Remote branch ${FULL_SHA} not found in upstream origin`) ); const shaClient = createShaClientMock(); simpleGitMock .mockReturnValueOnce(createGitClientMock(primaryClone)) .mockReturnValueOnce(shaClient); const tempDir = await cloneRepo('https://gitlab.com/group/repo.git', FULL_SHA); createdDirs.push(tempDir); expect(primaryClone).toHaveBeenCalledWith('https://gitlab.com/group/repo.git', tempDir, [ '--depth', '1', '--branch', FULL_SHA, ]); expect(shaClient.fetch).toHaveBeenCalledWith(['--depth', '1', 'origin', FULL_SHA]); expect(shaClient.checkout).toHaveBeenCalledWith('FETCH_HEAD') - src/git.ts (16074 bytes)
import { simpleGit } from 'simple-git'; import { join, normalize, resolve, sep } from 'path'; import { mkdtemp, mkdir, rm } from 'fs/promises'; import { tmpdir } from 'os'; import { execFile } from 'child_process'; import { promisify } from 'util'; import { diagnostics } from './diagnostics.ts'; import { isGitHubHost } from './github-host.ts'; const DEFAULT_CLONE_TIMEOUT_MS = 300_000; // 5 minutes const ALLOWED_GIT_PROTOCOLS = 'https:http:ssh:git:file'; const CLONE_TIMEOUT_MS = (() => { const raw = process.env.SKILLS_CLONE_TIMEOUT_MS; if (!raw) return DEFAULT_CLONE_TIMEOUT_MS; const parsed = Number.parseInt(raw, 10); return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_CLONE_TIMEOUT_MS; })(); const execFileAsync = promisify(execFile); /** * Whether a ref is a full 40-character Git commit SHA. * * Used only to decide whether the commit-SHA fetch fallback is worth attempting * after a `--branch` clone fails. The fetch-by-SHA protocol requires the full * 40-char SHA; abbreviated SHAs are rejected by the server, so they are not * matched here. Branch and tag detection is never inferred from the string: * `--branch` is always tried first, so any real branch or tag (including a * hex-looking name like "deadbeef" or a 40-char-hex name) resolves correctly * before the SHA fallback is ever considered. */ export function isCommitSha(ref: string): boolean { return /^[0-9a-f]{40}$/i.test(ref); } /** * Whether a clone or fetch error means the requested ref does not exist as a * branch or tag. `git clone --branch <sha>` fails this way because `--branch` * only accepts branch or tag names, never a bare commit SHA. * * These messages come from the git client and the server `upload-pack`, not from * the host, so they are identical across GitHub, GitLab, self-hosted git, and * `gh` (which wraps git). Verified on git 2.53. The variants cover the different * code paths a missing ref can surface through: * - `clone --branch <ref>` -> "Remote branch <ref> not found in upstream origin" * - GitHub shorthand fetch path -> "couldn't find remote ref <ref>" * - server-side fetch by SHA rejected -> "upload-pack: not our ref <ref>" */ export function isMissingRefError(message: string): boolean { return ( /Remote branch .* not found in upstream origin/i.test(message) || /couldn't find remote ref/i.test(message) || /upload-pack: not our ref/i.test(message) ); } /** * Clone a repository pinned to a specific commit SHA. * * `git clone --branch` cannot target a bare SHA, and a `--depth 1` clone does * not contain arbitrary commits. Instead, init an empty repo and fetch only the * requested commit, then check it out. This requires the server to allow * fetching reachable commits by SHA (`uploadpack.allowReachableSHA1InWant`), * which GitHub and GitLab.com both enable. If the server rejects it, the caller * falls back to the standard error handling. */ async function cloneAtSha( url: string, sha: string, tempDir: string, extraEnv?: NodeJS.ProcessEnv ): Promise<void> { const git = createGitClient(extraEnv); await git.cwd(tempDir); await git.init(); await git.addRemote('origin', url); await git.fetch(['--depth', '1', 'origin', sha]); await git.checkout('FETCH_HEAD'); } interface GitHubRepoInfo { owner: string; repo: string; slug: string; sshUrl: string; } export function parseGitHubRepoUrl(url: string): GitHubRepoInfo | null { const sshMatch = url.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/i); if (sshMatch && isGitHubHost(sshMatch[1]!)) { const host = sshMatch[1]!; const owner = sshMatch[2]!; const repo = sshMatch[3]!; return { owner, repo, slug: `${owner}/${repo}`, sshUrl: `git@${host}:${owner}/${repo}.git`, }; } try { const parsed = new URL(url); if (!isGitHubHost(parsed.host)) return null; const match = parsed.pathname.match(/^\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/); if (!match) return null; const owner = match[1]!; const repo = match[2]!; return { owner, repo, slug: `${owner}/${repo}`, sshUrl: `git@${parsed.host}:${owner}/${repo}.git`, }; } catch { return null; } } export function isGitHubHttpsCloneUrl(url: string): boolean { try { const parsed = new URL(url); return parsed.protocol === 'https:' && isGitHubHost(parsed.host); } catch { return false; } } export function isGitHubSsoAuthError(message: string): boolean { const lower = message.toLowerCase(); return ( lower.includes('saml sso') || lower.includes('enforced sso') || lower.includes('enabled or enforced saml') || lower.includes('re-authorize the oauth application') ); } function isAuthFailure(message: string): boolean { return ( message.includes('Authentication failed') || message.includes('could not read Username') || message.includes('Permission denied') || message.includes('Repository not found') || message.includes('requested URL returned error: 403') || isGitHubSsoAuthError(message) ); } function createGitClient(extraEnv?: NodeJS.ProcessEnv) { const env: NodeJS.ProcessEnv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_ALLOW_PROTOCOL: ALLOWED_GIT_PROTOCOLS, // When git-lfs IS installed, tell it not to download LFS content // during checkout. See #952 for context and empirical impact. GIT_LFS_SKIP_SMUDGE: '1', // isMissingRefError and isAuthFailure match git's English messages. A // translated git (e.g. LANG=de_DE.UTF-8) would skip the commit-SHA and // auth fallbacks, so force untranslated output. LC_ALL=C also overrides // LANGUAGE and LC_MESSAGES. See #2505. LC_ALL: 'C', ...extraEnv, }; const git = simpleGit({ timeout: { block: CLONE_TIMEOUT_MS }, // When git-lfs is NOT installed, GIT_LFS_SKIP_SMUDGE has no effect — // git sees `filter=lfs` in .gitattributes, tries to run // `git-lfs filter-process`, and aborts the checkout with: // git-lfs filter-process: git-lfs: command not found // fatal: the remote end hung up unexpectedly // warning: Clone succeeded, but checkout failed. // Overriding filter.lfs.* at the command level disables the filter // entirely for this clone, so checkout succeeds regardless of whether // git-lfs is installed. LFS-tracked files are left as ~130-byte // pointer files, which the skills installer doesn't read anyway // (skills are plain text — HTML/MD/JSON — never LFS-tracked). // // Reported downstream: heygen-com/hyperframes#407. // // Windows checks a path against MAX_PATH (260 chars) unless long paths are // enabled. Git opts in per-invocation with core.longpaths, and the option // has to reach every command that writes the working tree: CLONE checks // out in-process, while the commit-SHA fallback checks out FETCH_HEAD in a // separate invocation. Setting it here covers both because simple-git // prefixes every command with the instance config. // // Reported downstream: vercel-labs/skills#2613. config: [ 'filter.lfs.required=false', 'filter.lfs.smudge=', 'filter.lfs.clean=', 'filter.lfs.process=', 'core.longpaths=true', ], // simple-git v3.36+ rejects all `filter.*` configuration by default. // These values are hard-coded above and only disable the LFS filter for // this clone; no caller-controlled filter command is ever allowed. // // Calling `.env()` below replaces simple-git's normally inherited process // environment. Preserve that existing Git behavior for credentials, // configuration, SSH, proxies, editors, pagers, and related tooling. These // allowances apply only to trusted environment variables already controlled // by the caller (plus the hard-coded SSH fallback). This client is used only // for clone with fixed options; the clone URL and ref cannot configure them. // // simple-git v4 also strips or rejects Git-related variables (GIT_*, // PAGER, SSH_ASKPASS, ...) unless they are listed in allowEnvironment. // Allow every variable we pass so the inherited environment reaches git // unchanged, as it did with v3. allowEnvironment: Object.keys(env), unsafe: { allowUnsafeAlias: true, allowUnsafeAskPass: true, allowUnsafeCommandBinaries: true, allowUnsafeConfigEnvCount: true, allowUnsafeConfigPaths: true, allowUnsafeCredentialHelper: true, allowUnsafeDiffExternal: true, allowUnsafeDiffTextConv: true, allowUnsafeEditor: true, allowUnsafeExec: true, allowUnsafeFilter: true, allowUnsafeFsMonitor: true, allowUnsafeGpgProgram: true, allowUnsafeGitProxy: true, allowUnsafeHooksPath: true, allowUnsafeInclude: true, allowUnsafeMergeDriver: true, allowUnsafePack: true, allowUnsafePager: true, allowUnsafeProtocolOverride: true, allowUnsafeSshCommand: true, allowUnsafeSubmodule: true, allowUnsafeTemplateDir: true, allowUnsafeUrlRewrite: true, }, }); git.env(env); return git; } async function resetTempDir(dir: string): Promise<void> { await rm(dir, { recursive: true, force: true }).catch(() => {}); await mkdir(dir, { recursive: true }); } async function initializeSubmodules(repoDir: string, extraEnv?: NodeJS.ProcessEnv): Promise<void> { try { const git = createGitClient(extraEnv); await git.cwd(repoDir); await git.submoduleUpdate(['--init', '--recursive', '--depth', '1']); } catch { console.warn( 'Warning: failed to initialize Git submodules; installed skills may be incomplete.' ); } } async function tryGhClone(repo: GitHubRepoInfo, tempDir: string, ref?: string): Promise<boolean> { let cloneTarget = repo.slug; const host = repo.sshUrl.match(/^git@([^:]+):/)?.[1] || 'github.com'; try { const { stdout, stderr } = await execFileAsync('gh', ['auth', 'status', '-h', host], { timeout: 5000, env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }, }); const statusOutput = `${stdout}${stderr}`; if (/Git operations protocol:\s+ssh/i.test(statusOutput)) { cloneTarget = repo.sshUrl; } } catch { return false; } const gitFlags = ref ? ['--depth=1', '--branch', ref] : ['--depth=1']; await execFileAsync('gh', ['repo', 'clone', cloneTarget, tempDir, '--', ...gitFlags], { timeout: CLONE_TIMEOUT_MS, env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_ALLOW_PROTOCOL: ALLOWED_GIT_PROTOCOLS, }, }); return true; } function authError(url: string, repo: GitHubRepoInfo | null, message: string, cause: unknown) { const host = repo?.sshUrl.match(/^git@([^:]+):/)?.[1] || 'github.com'; if (repo && isGitHubSsoAuthError(message)) { return diagnostics.SKILLS_GIT_SAML_SSO_BLOCKED({ url, sshUrl: repo.sshUrl, host, cause }); } return diagnostics.SKILLS_GIT_AUTH_FAILED({ url, sshUrl: repo?.sshUrl, host, cause }); } export async function cloneRepo(url: string, ref?: string): Promise<string> { if (/^ext::/i.test(url)) { throw diagnostics.SKILLS_UNSUPPORTED_GIT_TRANSPORT({ transport: 'ext' }); } const tempDir = await mkdtemp(join(tmpdir(), 'skills-')); const cloneOptions = ref ? ['--depth', '1', '--branch', ref] : ['--depth', '1']; const refCanBeSha = !!ref && isCommitSha(ref); const repo = parseGitHubRepoUrl(url); try { await createGitClient().clone(url, tempDir, cloneOptions); await initializeSubmodules(tempDir); return tempDir; } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); // `--branch` cannot target a bare commit SHA. If the ref is a full SHA and // the clone failed because the ref was not a branch or tag, retry by // fetching the commit directly. This runs only after `--branch` fails, so a // real branch or tag (any name) is always resolved first. if (refCanBeSha && isMissingRefError(errorMessage)) { try { await resetTempDir(tempDir); await cloneAtSha(url, ref!, tempDir); await initializeSubmodules(tempDir); return tempDir; } catch { // Fall through to the standard error handling below. } } const isTimeout = errorMessage.includes('block timeout') || errorMessage.includes('timed out'); const isAuthError = isAuthFailure(errorMessage); if (isTimeout) { await rm(tempDir, { recursive: true, force: true }).catch(() => {}); throw diagnostics.SKILLS_GIT_CLONE_TIMEOUT({ seconds: Math.round(CLONE_TIMEOUT_MS / 1000), cause: error, }); } if (isAuthError && repo && isGitHubHttpsCloneUrl(url)) { try { await resetTempDir(tempDir); if (await tryGhClone(repo, tempDir, ref)) { await initializeSubmodules(tempDir); return tempDir; } } catch { // Fall through to SSH retry. } try { await resetTempDir(tempDir); const sshEnv = { GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND ?? 'ssh -o BatchMode=yes', }; try { await createGitClient(sshEnv).clone(repo.sshUrl, tempDir, cloneOptions); await initializeSubmodules(tempDir, sshEnv); } catch (sshError) { const sshMessage = sshError instanceof Error ? sshError.message : String(sshError); if (refCanBeSha && isMissingRefError(sshMessage)) { await resetTempDir(tempDir); await cloneAtSha(repo.sshUrl, ref!, tempDir, sshEnv); await initializeSubmodules(tempDir, sshEnv); } else { throw sshError; } } return tempDir; } catch { // Fall through to the targeted auth error below. } } await rm(tempDir, { recursive: true, force: true }).catch(() => {}); if (isAuthError) { throw authError(url, repo, errorMessage, error); } throw diagnostics.SKILLS_GIT_CLONE_FAILED({ url, detail: errorMessage, cause: error }); } } /** * Resolve the Git tree object for a locked skill path in a cloned repository. * This matches the folder SHA returned by GitHub's Trees API. */ export async function getGitTreeHash(repoDir: string, skillPath: string): Promise<string | null> { const normalizedPath = skillPath.replace(/\\/g, '/'); const segments = normalizedPath.split('/'); segments.pop(); const folderPath = segments.join('/'); return revParse(repoDir, folderPath ? `HEAD:${folderPath}` : 'HEAD^{tree}'); } /** The commit checked out in a cloned repository, or null when it cannot be read. */ export function getHeadCommit(repoDir: string): Promise<string | null> { return revParse(repoDir, 'HEAD^{commit}'); } async function revParse(repoDir: string, revision: string): Promise<string | null> { try { const stdout = await - src/github-host.ts (1036 bytes)
const DEFAULT_GITHUB_HOST = 'github.com'; /** * Return the GitHub host selected by the GitHub CLI. * * GH_HOST is expected to be a hostname, not a URL. * Invalid values fall back to github.com instead of being interpolated into * clone URLs. */ export function getGitHubHost(): string { const configuredHost = process.env.GH_HOST?.trim(); if (!configuredHost) { return DEFAULT_GITHUB_HOST; } try { const parsed = new URL(`https://${configuredHost}`); if ( parsed.username || parsed.password || parsed.port || parsed.pathname !== '/' || parsed.search || parsed.hash ) { return DEFAULT_GITHUB_HOST; } return parsed.hostname; } catch { return DEFAULT_GITHUB_HOST; } } /** Whether a host is GitHub.com or the configured GitHub Enterprise host. */ export function isGitHubHost(host: string): boolean { const normalizedHost = host.toLowerCase(); return normalizedHost === DEFAULT_GITHUB_HOST || normalizedHost === getGitHubHost().toLowerCase(); } - src/index.ts (1170 bytes)
/** * Public programmatic API of `skills`. * * Every export is listed by name on purpose: this file is the whole public * contract and is guarded by the tsnapi snapshot in `__snapshots__/tsnapi`. * Never `export *`, and never re-export internal types. See docs/api.md. */ export { getSupportedAgents, detectAgents } from './api/agents.ts'; export { resolveSource } from './api/resolve.ts'; export { installSkills } from './api/install.ts'; export { listSkills } from './api/list.ts'; export { removeSkills } from './api/remove.ts'; export { diagnostics, isDiagnostic } from './diagnostics.ts'; export { version } from './api/version.ts'; export type { AgentInfo, AgentsConfig, BaseOptions, DetectAgentsResult, Diagnostic, DiagnosticCode, InstalledSkillInfo, InstalledSkillTarget, InstallFailure, InstallMode, InstallOptions, InstallResult, InstallSettings, ListOptions, ListResult, ProgressEvent, ProgressHandler, RemoveFailure, RemoveOptions, RemoveResult, ResolveOptions, Scope, SkillInfo, SkillsConfig, SkillSource, SkippedSkillTarget, SourceInfo, SourceType, WarningHandler, } from './api/types.ts'; - src/init.test.ts (4353 bytes)
import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { existsSync, rmSync, readFileSync, mkdirSync } from 'fs'; import { join } from 'path'; import { tmpdir } from 'os'; import { runCliOutput, stripLogo } from './test-utils.ts'; import { parseFrontmatter } from './frontmatter.ts'; describe('init command', () => { let testDir: string; beforeEach(() => { testDir = join(tmpdir(), `skills-test-${Date.now()}`); mkdirSync(testDir, { recursive: true }); }); afterEach(() => { if (existsSync(testDir)) { rmSync(testDir, { recursive: true, force: true }); } }); it('should initialize a skill and create SKILL.md', () => { const output = stripLogo(runCliOutput(['init', 'my-test-skill'], testDir)); expect(output).toMatchInlineSnapshot(` "Initialized skill: my-test-skill Created: my-test-skill/SKILL.md Next steps: 1. Edit my-test-skill/SKILL.md to define your skill instructions 2. Update the name and description in the frontmatter Publishing: GitHub: Push to a repo, then npx skills add <owner>/<repo> URL: Host the file, then npx skills add https://example.com/my-test-skill/SKILL.md Browse existing skills for inspiration at https://skills.sh/ " `); const skillPath = join(testDir, 'my-test-skill', 'SKILL.md'); expect(existsSync(skillPath)).toBe(true); const content = readFileSync(skillPath, 'utf-8'); expect(content).toMatchInlineSnapshot(` "--- name: my-test-skill description: A brief description of what this skill does --- # my-test-skill Instructions for the agent to follow when this skill is activated. ## When to use Describe when this skill should be used. ## Instructions 1. First step 2. Second step 3. Additional steps as needed " `); }); it.for(['demo: x', 'my skill # best', 'true', '123', '[demo]', 'say "hello"'])( 'preserves %j as a string in frontmatter', (name, { skip }) => { if (process.platform === 'win32' && /[:"]/.test(name)) skip(); runCliOutput(['init', name], testDir); const content = readFileSync(join(testDir, name, 'SKILL.md'), 'utf-8'); expect(parseFrontmatter(content).data.name).toBe(name); } ); it('escapes the directory name when initializing in cwd', () => { const cwd = join(testDir, 'my skill # best'); mkdirSync(cwd); runCliOutput(['init'], cwd); const content = readFileSync(join(cwd, 'SKILL.md'), 'utf-8'); expect(parseFrontmatter(content).data.name).toBe('my skill # best'); }); it('should allow multiple skills in same directory', () => { runCliOutput(['init', 'hydration-fix'], testDir); runCliOutput(['init', 'waterfall-data-fetching'], testDir); expect(existsSync(join(testDir, 'hydration-fix', 'SKILL.md'))).toBe(true); expect(existsSync(join(testDir, 'waterfall-data-fetching', 'SKILL.md'))).toBe(true); }); it('should init SKILL.md in cwd when no name provided', () => { const output = stripLogo(runCliOutput(['init'], testDir)); expect(output).toContain('Initialized skill:'); expect(output).toContain('Created:\n SKILL.md'); // directly in cwd, not in a subfolder expect(output).toContain('Publishing:'); expect(output).toContain('GitHub:'); expect(output).toContain('npx skills add <owner>/<repo>'); expect(output).toContain('URL:'); expect(output).toContain('npx skills add https://example.com/SKILL.md'); expect(existsSync(join(testDir, 'SKILL.md'))).toBe(true); }); it('should show publishing hints with skill path', () => { const output = stripLogo(runCliOutput(['init', 'my-skill'], testDir)); expect(output).toContain('Publishing:'); expect(output).toContain('GitHub: Push to a repo, then npx skills add <owner>/<repo>'); expect(output).toContain( 'URL: Host the file, then npx skills add https://example.com/my-skill/SKILL.md' ); }); it('should show error if skill already exists', () => { runCliOutput(['init', 'existing-skill'], testDir); const output = stripLogo(runCliOutput(['init', 'existing-skill'], testDir)); expect(output).toMatchInlineSnapshot(` "Skill already exists at existing-skill/SKILL.md " `); }); }); - src/install.ts (12726 bytes)
import { existsSync } from 'fs'; import * as p from '@clack/prompts'; import { pc } from './color.ts'; import { getLockedSkillState, readLocalLock } from './local-lock.ts'; import { fetchSources, installFromSource, renameSkill } from './add.ts'; import { runSync, parseSyncOptions } from './sync.ts'; import { agents, detectInstalledAgents, getUniversalAgents, isUniversalAgent } from './agents.ts'; import { diagnostics, formatError } from './diagnostics.ts'; import { buildLocalUpdateSource } from './update-source.ts'; import { parseSource } from './source-parser.ts'; import { isCI } from './ci.ts'; import { getCanonicalPath, getInstallPath, installSkillForAgent } from './installer.ts'; import { getLastSelectedAgents } from './skill-lock.ts'; import type { AgentType, Skill } from './types.ts'; /** * The agents a restore installs to, without prompting: `--agent` when given, * else the last selection saved by `skills add`, else the agents detected on * this machine. Universal agents are always included, so with nothing else the * restore only fills `.agents/skills/`. */ export async function resolveRestoreAgents( requested: string[] | undefined, cwd: string ): Promise<AgentType[]> { const valid = Object.keys(agents) as AgentType[]; if (requested?.includes('*')) return valid; let chosen: AgentType[]; if (requested && requested.length > 0) { const invalid = requested.filter((a) => !valid.includes(a as AgentType)); if (invalid.length > 0) throw diagnostics.SKILLS_INVALID_AGENTS({ invalid, valid }); chosen = requested as AgentType[]; } else { const last = (await getLastSelectedAgents().catch(() => undefined))?.filter((a) => valid.includes(a as AgentType) ) as AgentType[] | undefined; chosen = last && last.length > 0 ? last : await detectInstalledAgents(cwd); } return [...new Set([...chosen, ...getUniversalAgents()])]; } /** * Install the skills from the local skills-lock.json that are not already in * .agents/skills/ (all of them with --force) into the agents picked by * `resolveRestoreAgents`, honouring each entry's recorded `installMode`. * Skills already installed only get the agent links they are missing. * Groups skills by source and installs each group. A source that cannot be * fetched, or no longer has a locked skill, fails only its own entries: the * rest are restored, failed entries keep their lock entries unchanged, and the * command ends with a summary and exit code 1. * * node_modules skills are handled via sync. */ export async function runInstallFromLock(args: string[]): Promise<void> { const cwd = process.cwd(); const { options: syncOptions } = parseSyncOptions(args); const frozen = syncOptions.frozenLockfile ?? isCI(); const force = args.includes('--force'); // A v1 lock is rewritten as v2 unless this run must not write the lock const lock = await readLocalLock(cwd, { persistMigration: !frozen && !syncOptions.dryRun }); const skillEntries = Object.entries(lock.skills); if (skillEntries.length === 0) { if (frozen) { p.log.error( 'Cannot install with --frozen-lockfile because skills-lock.json is absent or has no skills' ); process.exitCode = 1; return; } p.log.warn('No project skills found in skills-lock.json'); p.log.info( `Add project-level skills with ${pc.cyan('npx skills add <package>')} (without ${pc.cyan('-g')})` ); return; } let targetAgents: AgentType[]; try { targetAgents = await resolveRestoreAgents(syncOptions.agent, cwd); } catch (error) { p.log.error(formatError(error)); process.exitCode = 1; return; } const linkedAgents = targetAgents.filter((agent) => !isUniversalAgent(agent)); // Separate node_modules skills from remote skills const nodeModuleSkills: string[] = []; const alreadyInstalled: string[] = []; // Installed, but the files no longer match the lock; restored over const modifiedSkills: string[] = []; // Lock entries that could not be restored; their lock entries are left untouched const failedSkills: string[] = []; // Keyed by source, install mode, download, and pinned ref, so copied skills stay copies const bySource = new Map< string, { source: string; /** Set when `source` is pinned to the locked commit: the ref the lock keeps tracking. */ lockedRef?: { ref?: string }; copy: boolean; download: boolean; /** Lock keys: the installed names. */ skills: string[]; /** Installed names per lowercased source name; a renamed skill differs from its source name. */ installNames: Map<string, string[]>; } >(); for (const [skillName, entry] of skillEntries) { if (entry.sourceType === 'node_modules') { nodeModuleSkills.push(skillName); continue; } if (!force) { const state = await getLockedSkillState(skillName, entry, cwd); if (state === 'tracked') { alreadyInstalled.push(skillName); continue; } if (state === 'modified') modifiedSkills.push(skillName); } // A download is fetched again from its URL as-is; it has no folder or ref to append. // A Git source is fetched at its locked commit, so upstream changes cannot break the restore. const pinned = entry.sourceType !== 'download' && !!entry.commit; const installSource = entry.sourceType === 'download' ? (entry.sourceUrl ?? null) : buildLocalUpdateSource({ ...entry, ref: entry.commit ?? entry.ref }); if (!installSource) { p.log.error( formatError(diagnostics.SKILLS_LOCK_MISSING_SOURCE_URL({ skill: pc.cyan(skillName) })) ); failedSkills.push(skillName); continue; } const copy = entry.installMode === 'copy'; const download = entry.sourceType === 'download'; const key = `${copy ? 'copy' : 'symlink'}:${download ? 'download' : 'source'}:${installSource}\n${pinned ? (entry.ref ?? '') : ''}`; const group = bySource.get(key) ?? { source: installSource, ...(pinned && { lockedRef: { ref: entry.ref } }), copy, download, skills: [] as string[], installNames: new Map<string, string[]>(), }; group.skills.push(skillName); const sourceName = (entry.skillName ?? skillName).toLowerCase(); group.installNames.set(sourceName, [...(group.installNames.get(sourceName) ?? []), skillName]); bySource.set(key, group); } if (alreadyInstalled.length > 0) { p.log.info( `${pc.cyan(String(alreadyInstalled.length))} skill${alreadyInstalled.length !== 1 ? 's' : ''} already installed ${pc.dim('(use --force to reinstall)')}` ); } if (modifiedSkills.length > 0) { p.log.warn( `${modifiedSkills.map((name) => pc.cyan(name)).join(', ')} ${modifiedSkills.length === 1 ? 'does' : 'do'} not match skills-lock.json; ${syncOptions.dryRun ? 'would restore' : 'restoring'} the locked version` ); } const remoteCount = skillEntries.length - nodeModuleSkills.length - alreadyInstalled.length; if (remoteCount > 0) { p.log.info( `${syncOptions.dryRun ? 'Would restore' : 'Restoring'} ${pc.cyan(String(remoteCount))} skill${remoteCount !== 1 ? 's' : ''} from skills-lock.json into ${pc.dim('.agents/skills/')}` ); } if (linkedAgents.length > 0 && (remoteCount > 0 || alreadyInstalled.length > 0)) { p.log.info( `${syncOptions.dryRun ? 'Would link' : 'Linking'} to ${linkedAgents.map((a) => agents[a].displayName).join(', ')}` ); } if (syncOptions.dryRun) { for (const { source, copy, skills } of bySource.values()) { p.log.message( `${skills.map((name) => pc.cyan(name)).join(', ')} ${pc.dim(`from ${source}${copy ? ' (copy)' : ''}`)}` ); } // Nothing is fetched or installed; node_modules entries below are reported by sync's own dry run. bySource.clear(); } else { await linkInstalledSkills(alreadyInstalled, lock, linkedAgents, cwd); } // Download every source at once, then install them in order const requests = [...bySource.values()].map( ({ source, lockedRef, copy, download, skills, installNames }) => ({ source, lockedRef, copy, parsed: download ? { type: 'download' as const, url: source } : parseSource(source), // Fetch renamed skills by the name their source uses skills: skills.map((name) => lock.skills[name]?.skillName ?? name), lockKeys: skills, installNames, // A pack or archive can hold its skills at any depth. ...(download && { fullDepth: true }), }) ); const fetched = await fetchSources(requests); let restoredCount = 0; for (const [ index, { source, lockedRef, copy, skills: sourceNames, lockKeys: skills, installNames }, ] of requests.entries()) { const fetchedSource = fetched[index]!; // Fetched at the locked commit; the lock keeps tracking the branch or tag it came from. const result = await installFromSource( lockedRef ? { ...fetchedSource, parsed: { ...fetchedSource.parsed, ref: lockedRef.ref } } : fetchedSource, { skills: sourceNames, // Install each found skill under every name the lock has it as ...(skills.some((name) => lock.skills[name]?.skillName) && { select: async (found: Skill[]) => found.flatMap((skill) => (installNames.get(skill.name.toLowerCase()) ?? [skill.name]).map((name) => name.toLowerCase() === skill.name.toLowerCase() ? skill : renameSkill(skill, name) ) ), }), agents: targetAgents, ...(copy && { installMode: 'copy' as const }), ...(frozen && { frozenLock: lock }), } ); if (result.error) { p.log.error( `Failed to restore ${skills.map((name) => pc.cyan(name)).join(', ')} from ${pc.cyan(source)}: ${result.error}` ); failedSkills.push(...skills); continue; } restoredCount += result.installed.length; p.log.success(`Restored ${result.installed.map((name) => pc.cyan(name)).join(', ')}`); // A skill renamed or removed upstream is missing from the source const installedNames = new Set(result.installed.map((name) => name.toLowerCase())); const notFound = skills.filter((name) => !installedNames.has(name.toLowerCase())); if (notFound.length > 0) { p.log.error( `${notFound.map((name) => pc.cyan(name)).join(', ')} not found in ${pc.cyan(source)}` ); failedSkills.push(...notFound); } for (const failure of result.failed) p.log.error(failure); if (result.failed.length > 0) process.exitCode = 1; } // Handle node_modules skills via sync if (nodeModuleSkills.length > 0) { p.log.info( `${pc.cyan(String(nodeModuleSkills.length))} skill${nodeModuleSkills.length !== 1 ? 's' : ''} from node_modules` ); try { await runSync(args, { ...syncOptions, frozenLockfile: frozen, yes: true, agent: targetAgents, }); } catch (error) { p.log.error( `Failed to sync node_modules skills: ${error instanceof Error ? formatError(error) : 'Unknown error'}` ); failedSkills.push(...nodeModuleSkills); } } if (failedSkills.length > 0) { const restored = restoredCount > 0 ? `Restored ${restoredCount} skill${restoredCount !== 1 ? 's' : ''}; failed` : 'Failed'; p.log.error( `${restored} to restore ${failedSkills.length} skill${failedSkills.length !== 1 ? 's' : ''} from skills-lock.json: ${failedSkills.map((name) => pc.cyan(name)).join(', ')}` ); process.exitCode = 1; } } /** * Give already installed skills the agent links they lack: a symlink to the * canonical copy, or a copy when the entry was installed with `--copy`. Agent * dirs that already hold the skill are left as they are. */ async function linkInstalledSkills( skillNames: string[], lock: Awaited<ReturnType<typeof readLocalLock>>, targetAgents: AgentType[], cwd: string ): Promise<void> { for (const name of skillNames) { const path = getCanonicalPath(name, { cwd }); const mode = lock.skills[name]?.installMode === 'copy' ? 'copy' : 'symlink'; for (const agent of targetAgents) { if (existsSync(getInstallPath(name, agent, { cwd }))) continue; const result = await installSkillForAgent({ name, description: '', path }, agent, { cwd, mode, createMissingAgentRoot: true, }); if (!result.success) { p.log.error( `Failed to link ${pc.cyan(name)} to ${agents[agent].displayName}: ${result.error}` ); process.exitCode = 1; } } } } - src/installer.ts (47817 bytes)
import { mkdir, cp, access, readdir, symlink, lstat, rm, readFile, writeFile, stat, chmod, realpath, } from 'fs/promises'; import { existsSync } from 'fs'; import { join, basename, normalize, resolve, sep, relative, dirname, extname } from 'path'; import { homedir, platform } from 'os'; import type { Skill, AgentType, RemoteSkill } from './types.ts'; import type { WellKnownSkill } from './providers/wellknown.ts'; import { agents, detectInstalledAgents, isUniversalAgent, readsCanonicalGlobally, getEveSubagents, EVE_SUBAGENTS_DIR, } from './agents.ts'; import { AGENTS_DIR, SKILLS_SUBDIR } from './constants.ts'; import { diagnostics } from './diagnostics.ts'; import { parseFrontmatter, setFrontmatterName } from './frontmatter.ts'; import { stringify } from 'yaml'; import { parseSkillMd } from './skills.ts'; import { warn } from './warnings.ts'; import { isExcluded, isExcludedPath } from './skill-hash.ts'; import { sanitizeName } from './sanitize.ts'; export { sanitizeName }; /** * - `symlink`: copy into the canonical dir, symlink agent dirs to it * - `copy`: copy into each agent dir * - `link`: symlink the canonical dir to the skill's source, symlink agent dirs to it */ export type InstallMode = 'symlink' | 'copy' | 'link'; interface InstallOptions { global?: boolean; cwd?: string; mode?: InstallMode; eveSubagent?: string; /** Create a missing agent-specific project root because the user selected this agent. */ createMissingAgentRoot?: boolean; } interface InstallResult { success: boolean; path: string; canonicalPath?: string; mode: InstallMode; symlinkFailed?: boolean; skipped?: boolean; skipReason?: 'missing-agent-project-directory'; error?: string; } /** * Validates that a path is within an expected base directory * @param basePath - The expected base directory * @param targetPath - The path to validate * @returns true if targetPath is within basePath */ function isPathSafe(basePath: string, targetPath: string): boolean { const normalizedBase = normalize(resolve(basePath)); const normalizedTarget = normalize(resolve(targetPath)); return normalizedTarget.startsWith(normalizedBase + sep) || normalizedTarget === normalizedBase; } export function pathsOverlap(pathA: string, pathB: string): boolean { return isPathSafe(pathA, pathB) || isPathSafe(pathB, pathA); } function shouldSkipProjectAgentSymlink( agentType: AgentType, isGlobal: boolean, cwd: string, createMissingAgentRoot: boolean ): boolean { if ( isGlobal || isUniversalAgent(agentType) || createMissingAgentRoot || agents[agentType].createProjectSkillsDirByDefault ) { return false; } const agentRoot = agents[agentType].skillsDir.split('/')[0]!; return !existsSync(join(cwd, agentRoot)); } // Dirent.isDirectory() is false for symlinks; follow and verify the target is a directory. export async function isDirEntryOrSymlinkToDir( entry: { isDirectory(): boolean; isSymbolicLink(): boolean }, entryPath: string ): Promise<boolean> { if (entry.isDirectory()) return true; if (!entry.isSymbolicLink()) return false; try { return (await stat(entryPath)).isDirectory(); } catch { return false; } } export function getCanonicalSkillsDir(global: boolean, cwd?: string): string { const baseDir = global ? homedir() : cwd || process.cwd(); return join(baseDir, AGENTS_DIR, SKILLS_SUBDIR); } /** * Resolve the skills directory for a specific Eve subagent, relative to the * project root: `agent/subagents/<name>/skills`. The subagent name is * sanitized to prevent directory traversal when it originates from user input. */ export function getEveSubagentSkillsDir(subagent: string, cwd?: string): string { const baseDir = cwd || process.cwd(); return join(baseDir, EVE_SUBAGENTS_DIR, sanitizeName(subagent), 'skills'); } /** * Gets the base directory for an agent's skills, respecting universal agents. * Universal agents always use the canonical directory, which prevents * redundant symlinks and double-listing of skills. * * For Eve, an optional `eveSubagent` targets a subagent's skills directory * (`agent/subagents/<name>/skills`) instead of the root agent's `agent/skills`. */ export function getAgentBaseDir( agentType: AgentType, global: boolean, cwd?: string, eveSubagent?: string ): string { if (global ? readsCanonicalGlobally(agentType) : isUniversalAgent(agentType)) { return getCanonicalSkillsDir(global, cwd); } // Eve subagents are inherently project-scoped — they live under the project's // agent/ directory, so the `global` flag does not apply here. if (agentType === 'eve' && eveSubagent) { return getEveSubagentSkillsDir(eveSubagent, cwd); } const agent = agents[agentType]; const baseDir = global ? homedir() : cwd || process.cwd(); if (global) { if (agent.globalSkillsDir === undefined) { // This should be caught by callers checking support return join(baseDir, agent.skillsDir); } return agent.globalSkillsDir; } return join(baseDir, agent.skillsDir); } /** * Names of the nested skills if `path` is an agent category directory, e.g. Hermes * `~/.hermes/skills/<category>/<skill>/SKILL.md` (#1723): a real directory with * no root SKILL.md and at least one child directory with a SKILL.md. Otherwise * `[]`. A skill that bundles child skills has a root SKILL.md, so it is not a * category. Symlinks are not categories: removing a link leaves its target alone. */ export async function findCategoryDirSkills(path: string): Promise<string[]> { const stats = await lstat(path).catch(() => undefined); if (!stats?.isDirectory() || existsSync(join(path, 'SKILL.md'))) return []; const entries = await readdir(path).catch(() => []); return entries.filter((name) => existsSync(join(path, name, 'SKILL.md'))); } /** Throws if `path` is an agent category directory: deleting it would wipe unrelated skills. */ async function assertNotCategoryDir(path: string): Promise<void> { const skills = await findCategoryDirSkills(path); if (skills.length > 0) throw diagnostics.SKILLS_CATEGORY_DIR_CONFLICT({ path, skills }); } /** * Cleans and recreates a directory for skill installation. * * This ensures: * 1. Renamed/deleted files from previous installs are removed * 2. Symlinks (including self-referential ones causing ELOOP) are handled * when canonical and agent paths resolve to the same location */ async function cleanAndCreateDirectory(path: string): Promise<void> { await assertNotCategoryDir(path); try { await rm(path, { recursive: true, force: true }); } catch { // Ignore cleanup errors - mkdir will fail if there's a real problem } await mkdir(path, { recursive: true }); } /** * Resolve a path's parent directory through symlinks, keeping the final component. * This handles the case where a parent directory (e.g., ~/.claude/skills) is a symlink * to another location (e.g., ~/.agents/skills). In that case, computing relative paths * from the symlink path produces broken symlinks. * * Returns the real path of the parent + the original basename. * If realpath fails (parent doesn't exist), returns the original resolved path. */ async function resolveParentSymlinks(path: string): Promise<string> { const resolved = resolve(path); const dir = dirname(resolved); const base = basename(resolved); try { const realDir = await realpath(dir); return join(realDir, base); } catch { return resolved; } } /** * Creates a symlink, handling cross-platform differences * Returns true if symlink was created, false if fallback to copy is needed */ async function createSymlink(target: string, linkPath: string): Promise<boolean> { try { const resolvedTarget = resolve(target); const resolvedLinkPath = resolve(linkPath); // Use realpath to handle cases where parent directories are symlinked. // This prevents deleting the canonical directory if the agent directory // is a symlink to the canonical location. const [realTarget, realLinkPath] = await Promise.all([ realpath(resolvedTarget).catch(() => resolvedTarget), realpath(resolvedLinkPath).catch(() => resolvedLinkPath), ]); if (realTarget === realLinkPath) { return true; } // Also check with symlinks resolved in parent directories. // This handles cases where e.g. ~/.claude/skills is a symlink to ~/.agents/skills, // so ~/.claude/skills/<skill> and ~/.agents/skills/<skill> are physically the same. const realTargetWithParents = await resolveParentSymlinks(target); const realLinkPathWithParents = await resolveParentSymlinks(linkPath); if (realTargetWithParents === realLinkPathWithParents) { return true; } // Throws past the catch below: falling back to copy would hit the same guard. await assertNotCategoryDir(linkPath); try { const stats = await lstat(linkPath); if (stats.isSymbolicLink()) { // A link that already resolves to target returned above, so this one points // elsewhere or nowhere. await rm(linkPath); } else { await rm(linkPath, { recursive: true }); } } catch (err: unknown) { // ELOOP = circular symlink, ENOENT = doesn't exist // For ELOOP, try to remove the broken symlink if (err && typeof err === 'object' && 'code' in err && err.code === 'ELOOP') { try { await rm(linkPath, { force: true }); } catch { // If we can't remove it, symlink creation will fail and trigger copy fallback } } // For ENOENT or other errors, continue to symlink creation } const linkDir = dirname(linkPath); await mkdir(linkDir, { recursive: true }); // A relative link is resolved from the directory it physically lives in, so compute it // from the fully resolved linkDir. linkDir can itself be a symlink, e.g. ~/.claude/skills // pointing into a dotfiles repo. const realLinkDir = await realpath(linkDir).catch(() => linkDir); const relativePath = relative(realLinkDir, target); const symlinkType = platform() === 'win32' ? 'junction' : undefined; const symlinkTarget = symlinkType === 'junction' ? resolvedTarget : relativePath; await symlink(symlinkTarget, linkPath, symlinkType); return true; } catch (error) { if (diagnostics.SKILLS_CATEGORY_DIR_CONFLICT.is(error)) throw error; return false; } } export async function installSkillForAgent( skill: Skill, agentType: AgentType, options: InstallOptions = {} ): Promise<InstallResult> { const agent = agents[agentType]; const isGlobal = options.global ?? false; const cwd = options.cwd || process.cwd(); const eveSubagent = options.eveSubagent; // Check if agent supports global installation if (isGlobal && agent.globalSkillsDir === undefined) { return { success: false, path: '', mode: options.mode ?? 'symlink', error: `${agent.displayName} does not support global skill installation`, }; } // Sanitize skill name to prevent directory traversal const rawSkillName = skill.name || basename(skill.path); const skillName = sanitizeName(rawSkillName); const installMode = options.mode ?? 'symlink'; // Canonical location: .agents/skills/<skill-name> const canonicalBase = agentType === 'eve' && installMode === 'symlink' ? getAgentBaseDir(agentType, isGlobal, cwd, eveSubagent) : getCanonicalSkillsDir(isGlobal, cwd); const canonicalDir = join(canonicalBase, skillName); // Agent-specific location (for symlink) const agentBase = getAgentBaseDir(agentType, isGlobal, cwd, eveSubagent); const agentDir = join(agentBase, skillName); // Validate paths if (!isPathSafe(canonicalBase, canonicalDir)) { return { success: false, path: agentDir, mode: installMode, error: 'Invalid skill name: potential path traversal detected', }; } if (!isPathSafe(agentBase, agentDir)) { return { success: false, path: agentDir, mode: installMode, error: 'Invalid skill name: potential path traversal detected', }; } try { // Never install onto (or inside) the source directory. This can happen with // agent-specific project directories like OpenClaw's "skills" when users run // `skills add ./skills --all`: the source `./skills/<name>` and destination // `./skills/<name>` are the same path. Cleaning the destination would delete // the user's source skill before we can link or copy it. if (pathsOverlap(skill.path, agentDir)) { return { success: true, path: agentDir, mode: installMode, skipped: true, }; } // For copy mode, skip canonical directory and copy directly to agent location if (installMode === 'copy') { await cleanAndCreateDirectory(agentDir); await copyDirectory(skill.path, agentDir, agentType); return { success: true, path: agentDir, mode: 'copy', }; } const sourceIsCanonical = resolve(skill.path) === resolve(canonicalDir); if (!sourceIsCanonical && pathsOverlap(skill.path, canonicalDir)) { return { success: true, path: canonicalDir, canonicalPath: canonicalDir, mode: installMode, skipped: true, }; } const linksAgentDir = !(isGlobal && readsCanonicalGlobally(agentType)) && !shouldSkipProjectAgentSymlink( agentType, isGlobal, cwd, options.createMissingAgentRoot ?? false ); // Check every target before writing, so a refusal leaves nothing behind (#1723). if (!sourceIsCanonical) await assertNotCategoryDir(canonicalDir); if (linksAgentDir) await assertNotCategoryDir(agentDir); // Reuse an existing canonical copy when only adding another agent's link. if (!sourceIsCanonical) { if (installMode === 'link') { // Link mode: the canonical dir itself points at the source, nothing is copied. if (!(await createSymlink(skill.path, canonicalDir))) { await cleanAndCreateDirectory(canonicalDir); await copyDirectory(skill.path, canonicalDir, agentType); } } else { // Symlink mode: copy to canonical location and symlink to agent location await cleanAndCreateDirectory(canonicalDir); await copyDirectory(skill.path, canonicalDir, agentType); } } // For universal agents with global install, the skill is already in the canonical // ~/.agents/skills directory. Skip creating a symlink to the agent-specific global dir // (e.g. ~/.copilot/skills) to avoid duplicates. if (isGlobal && readsCanonicalGlobally(agentType)) { return { success: true, path: canonicalDir, canonicalPath: canonicalDir, mode: installMode, }; } // For project-level inst - src/list.test.ts (15226 bytes)
import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { existsSync, rmSync, mkdirSync, writeFileSync } from 'fs'; import { join } from 'path'; import { tmpdir } from 'os'; import { runCli } from './test-utils.ts'; import { parseListOptions } from './list.ts'; import { computeSkillFolderHash } from './skill-hash.ts'; describe('list command', () => { let testDir: string; beforeEach(() => { testDir = join(tmpdir(), `skills-list-test-${Date.now()}`); mkdirSync(testDir, { recursive: true }); }); afterEach(() => { if (existsSync(testDir)) { rmSync(testDir, { recursive: true, force: true }); } }); function createTestSkill(root: string, name: string, description: string): string { const skillDir = join(root, '.agents', 'skills', name); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: ${name} description: ${description} --- # ${name} ` ); return skillDir; } describe('parseListOptions', () => { it('should parse empty args', () => { const options = parseListOptions([]); expect(options).toEqual({}); }); it('should parse -g flag', () => { const options = parseListOptions(['-g']); expect(options.global).toBe(true); }); it('should parse --global flag', () => { const options = parseListOptions(['--global']); expect(options.global).toBe(true); }); it('should parse -a flag with single agent', () => { const options = parseListOptions(['-a', 'claude-code']); expect(options.agent).toEqual(['claude-code']); }); it('should parse --agent flag with single agent', () => { const options = parseListOptions(['--agent', 'cursor']); expect(options.agent).toEqual(['cursor']); }); it('should parse -a flag with multiple agents', () => { const options = parseListOptions(['-a', 'claude-code', 'cursor', 'codex']); expect(options.agent).toEqual(['claude-code', 'cursor', 'codex']); }); it('should parse combined flags', () => { const options = parseListOptions(['-g', '-a', 'claude-code', 'cursor']); expect(options.global).toBe(true); expect(options.agent).toEqual(['claude-code', 'cursor']); }); it('should parse --json flag', () => { const options = parseListOptions(['--json']); expect(options.json).toBe(true); }); it('should parse combined --json and -g flags', () => { const options = parseListOptions(['-g', '--json']); expect(options.global).toBe(true); expect(options.json).toBe(true); }); it('should stop collecting agents at next flag', () => { const options = parseListOptions(['-a', 'claude-code', '-g']); expect(options.agent).toEqual(['claude-code']); expect(options.global).toBe(true); }); }); describe('CLI integration', () => { it('should run list command', () => { const result = runCli(['list'], testDir); // Empty project dir shows "No project skills found" expect(result.stdout).toContain('No project skills found'); expect(result.exitCode).toBe(0); }); it('should run ls alias', () => { const result = runCli(['ls'], testDir); expect(result.stdout).toContain('No project skills found'); expect(result.exitCode).toBe(0); }); it('should output empty JSON array when no skills', () => { const result = runCli(['list', '--json'], testDir); expect(result.exitCode).toBe(0); const parsed = JSON.parse(result.stdout.trim()); expect(parsed).toEqual([]); }); it('should output valid JSON with --json flag', () => { createTestSkill(testDir, 'json-skill', 'A skill for JSON testing'); const result = runCli(['list', '--json'], testDir); expect(result.exitCode).toBe(0); const parsed = JSON.parse(result.stdout.trim()); expect(Array.isArray(parsed)).toBe(true); expect(parsed.length).toBe(1); expect(parsed[0].name).toBe('json-skill'); expect(parsed[0].path).toContain('json-skill'); expect(parsed[0].scope).toBe('project'); expect(Array.isArray(parsed[0].agents)).toBe(true); // No ANSI codes in JSON output expect(result.stdout).not.toMatch(/\x1b\[/); }); it('should report project skill provenance from skills-lock.json', () => { createTestSkill(testDir, 'project-skill', 'A tracked project skill'); writeFileSync( join(testDir, 'skills-lock.json'), JSON.stringify({ version: 2, skills: { 'project-skill': { source: 'owner/project-skills', sourceUrl: 'https://github.com/owner/project-skills', sourceType: 'github', computedHash: 'project-hash', }, }, }) ); const result = runCli(['list', '--json'], testDir); const [skill] = JSON.parse(result.stdout.trim()); expect(skill).toMatchObject({ source: 'owner/project-skills', sourceUrl: 'https://github.com/owner/project-skills', sourceType: 'github', }); expect(skill).not.toHaveProperty('origin'); }); it('should output multiple skills as JSON array', () => { createTestSkill(testDir, 'skill-alpha', 'Alpha'); createTestSkill(testDir, 'skill-beta', 'Beta'); const result = runCli(['list', '--json'], testDir); expect(result.exitCode).toBe(0); const parsed = JSON.parse(result.stdout.trim()); expect(parsed.length).toBe(2); const names = parsed.map((s: any) => s.name); expect(names).toContain('skill-alpha'); expect(names).toContain('skill-beta'); }); it('should show message when no project skills found', () => { const result = runCli(['list'], testDir); expect(result.stdout).toContain('No project skills found'); expect(result.stdout).toContain('Try listing global skills with -g'); expect(result.exitCode).toBe(0); }); it('should list project skills', () => { createTestSkill(testDir, 'test-skill', 'A test skill for listing'); const result = runCli(['list'], testDir); expect(result.stdout).toContain('test-skill'); expect(result.stdout).toContain('Project Skills'); // Description should not be shown expect(result.stdout).not.toContain('A test skill for listing'); expect(result.exitCode).toBe(0); }); it('should show a tracked project skill source in human output', () => { createTestSkill(testDir, 'tracked-skill', 'A tracked project skill'); writeFileSync( join(testDir, 'skills-lock.json'), JSON.stringify({ version: 2, skills: { 'tracked-skill': { source: 'owner/project-skills', sourceType: 'github', computedHash: 'project-hash', }, }, }) ); const result = runCli(['list'], testDir); expect(result.stdout).toContain('Source:'); expect(result.stdout).toContain('owner/project-skills'); expect(result.stdout).not.toContain('Origin:'); }); describe('lock status', () => { beforeEach(async () => { createTestSkill(testDir, 'tracked-skill', 'Installed and locked'); createTestSkill(testDir, 'handmade-skill', 'Installed, not locked'); createTestSkill(testDir, 'edited-skill', 'Installed, changed since locked'); const entry = { source: 'owner/repo', sourceType: 'github', computedHash: 'h' }; const trackedHash = await computeSkillFolderHash( join(testDir, '.agents', 'skills', 'tracked-skill') ); writeFileSync( join(testDir, 'skills-lock.json'), JSON.stringify({ version: 2, skills: { 'tracked-skill': { ...entry, computedHash: trackedHash }, 'edited-skill': entry, 'gone-skill': entry, }, }) ); }); it('reports each skill as tracked, untracked, modified or missing in JSON', () => { const skills: Array<{ name: string; status: string }> = JSON.parse( runCli(['list', '--json'], testDir).stdout.trim() ); expect(Object.fromEntries(skills.map((s) => [s.name, s.status]))).toEqual({ 'tracked-skill': 'tracked', 'handmade-skill': 'untracked', 'edited-skill': 'modified', 'gone-skill': 'missing', }); }); it('labels untracked skills and lists missing ones', () => { const { stdout } = runCli(['list'], testDir); expect(stdout).toContain('Source: untracked'); expect(stdout).toMatch(/edited-skill[\s\S]*modified/); expect(stdout).toContain('Missing'); expect(stdout).toContain('gone-skill'); }); it('does not report missing skills when filtering by agent', () => { const { stdout } = runCli(['list', '-a', 'claude-code'], testDir); expect(stdout).not.toContain('gone-skill'); }); }); it('should keep untrusted source metadata on one output line', () => { createTestSkill(testDir, 'tracked-skill', 'A tracked project skill'); writeFileSync( join(testDir, 'skills-lock.json'), JSON.stringify({ version: 2, skills: { 'tracked-skill': { source: 'owner/\nFORGED', sourceType: 'github', computedHash: 'project-hash', }, }, }) ); const result = runCli(['list'], testDir); expect(result.stdout).toContain('Source: owner/ FORGED'); expect(result.stdout).not.toContain('\nFORGED'); }); it('should list multiple skills', () => { createTestSkill(testDir, 'skill-one', 'First skill'); createTestSkill(testDir, 'skill-two', 'Second skill'); const result = runCli(['list'], testDir); expect(result.stdout).toContain('skill-one'); expect(result.stdout).toContain('skill-two'); expect(result.stdout).toContain('Project Skills'); expect(result.exitCode).toBe(0); }); it('should respect -g flag for global only', () => { createTestSkill(testDir, 'project-skill', 'A project skill'); const testHome = join(testDir, 'home'); createTestSkill(testHome, 'global-skill', 'A global skill'); const result = runCli(['list', '-g'], testDir, { HOME: testHome }); // Should not show project skill when -g is specified expect(result.stdout).not.toContain('project-skill'); expect(result.stdout).toContain('global-skill'); expect(result.stdout).toContain('Global Skills'); }); it('should report global provenance when a lock key differs from its folder name', () => { const testHome = join(testDir, 'home'); createTestSkill(testHome, 'ce-review', 'A tracked global plugin skill'); const lockDir = join(testHome, '.local', 'state', 'skills'); mkdirSync(lockDir, { recursive: true }); writeFileSync( join(lockDir, '.skill-lock.json'), JSON.stringify({ version: 3, skills: { 'ce:review': { source: 'everyinc/compound-engineering-plugin', sourceUrl: 'https://github.com/everyinc/compound-engineering-plugin', sourceType: 'github', skillFolderHash: 'global-hash', installedAt: '2026-07-01T00:00:00.000Z', updatedAt: '2026-07-01T00:00:00.000Z', }, }, }) ); const result = runCli(['list', '-g', '--json'], testDir, { HOME: testHome }); const skills = JSON.parse(result.stdout.trim()); expect(skills).toHaveLength(1); expect(skills[0]).toMatchObject({ name: 'ce-review', source: 'everyinc/compound-engineering-plugin', sourceUrl: 'https://github.com/everyinc/compound-engineering-plugin', sourceType: 'github', }); }); it('should show error for invalid agent filter', () => { const result = runCli(['list', '-a', 'invalid-agent'], testDir); expect(result.stdout).toContain('Invalid agents'); expect(result.stdout).toContain('invalid-agent'); expect(result.exitCode).toBe(1); }); it('should filter by valid agent', () => { createTestSkill(testDir, 'test-skill', 'A test skill'); const result = runCli(['list', '-a', 'claude-code'], testDir); expect(result.stdout).toContain('test-skill'); expect(result.exitCode).toBe(0); }); it('should ignore directories without SKILL.md', () => { createTestSkill(testDir, 'valid-skill', 'Valid skill'); // Create an invalid directory (no SKILL.md) const invalidDir = join(testDir, '.agents', 'skills', 'invalid-skill'); mkdirSync(invalidDir, { recursive: true }); writeFileSync(join(invalidDir, 'README.md'), '# Not a skill'); const result = runCli(['list'], testDir); expect(result.stdout).toContain('valid-skill'); expect(result.stdout).not.toContain('invalid-skill'); expect(result.exitCode).toBe(0); }); it('should handle SKILL.md with missing frontmatter', () => { createTestSkill(testDir, 'valid-skill', 'Valid skill'); // Create a skill with invalid SKILL.md (no frontmatter) const invalidDir = join(testDir, '.agents', 'skills', 'invalid-skill'); mkdirSync(invalidDir, { recursive: true }); writeFileSync(join(invalidDir, 'SKILL.md'), '# Invalid\nNo frontmatter here'); const result = runCli(['list'], testDir); expect(result.stdout).toContain('valid-skill'); expect(result.stdout).not.toContain('invalid-skill'); expect(result.exitCode).toBe(0); }); it('should show skill path', () => { createTestSkill(testDir, 'test-skill', 'A test skill'); const result = runCli(['list'], testDir); // Path is shown inline with skill name (handles both Unix / and Windows \) expect(result.stdout).toMatch(/\.agents[/\\]skills[/\\]test-skill/); }); }); describe('help output', () => { it('should include list command in help', () => { const result = runCli(['--help']); expect(result.stdout).toContain('list, ls'); expect(result.stdout).toContain('List installed skills'); }); it('should include list options in help', () => { const result = runCli(['--help']); expect(result.stdout).toContain('List Options:'); expect(result.stdout).toContain('-g, --global'); expect(result.stdout).toContain('-a, --agent'); }); it('should include list examples in help', () => { const result = runCli(['--help']); expect(result.stdout).toContain('skills list'); expect(result.stdout).toContain('skills ls -g'); expect(result.stdout).toContain('skills ls -a claude-code'); }); }); describe('banner', () => { - src/list.ts (11301 bytes)
import { homedir } from 'os'; import type { AgentType } from './types.ts'; import { agents } from './agents.ts'; import { diagnostics, formatError } from './diagnostics.ts'; import { parseCliArgs, throwFirstError } from './cli-args.ts'; import { listInstalledSkills, sanitizeName, type InstalledSkill } from './installer.ts'; import { sanitizeMetadata } from './sanitize.ts'; import { getAllLockedSkills } from './skill-lock.ts'; import { getLockedSkillState, readLocalLock } from './local-lock.ts'; import { BOLD, CYAN, DIM, RESET, YELLOW } from './color.ts'; interface ListOptions { global?: boolean; agent?: string[]; json?: boolean; } interface ListLockEntry { source: string; sourceUrl?: string; sourceType: string; pluginName?: string; /** Project lock only; lets `list` tell a modified skill from a tracked one. */ computedHash?: string; skillName?: string; } /** ` (renamed from <name>)` for a skill installed under another name, else empty. */ function renamedLabel(entry: ListLockEntry | undefined): string { return entry?.skillName ? ` ${DIM}(renamed from ${sanitizeMetadata(entry.skillName)})${RESET}` : ''; } /** * Shortens a path for display: replaces homedir with ~ and cwd with . */ function shortenPath(fullPath: string, cwd: string): string { const home = homedir(); if (fullPath.startsWith(home)) { return fullPath.replace(home, '~'); } if (fullPath.startsWith(cwd)) { return '.' + fullPath.slice(cwd.length); } return fullPath; } /** * Formats a list of items, truncating if too many */ function formatList(items: string[], maxShow: number = 5): string { if (items.length <= maxShow) { return items.join(', '); } const shown = items.slice(0, maxShow); const remaining = items.length - maxShow; return `${shown.join(', ')} +${remaining} more`; } export function parseListOptions(args: string[]): ListOptions { const { values, errors } = parseCliArgs(args, { global: { type: 'boolean', short: 'g' }, json: { type: 'boolean' }, agent: { type: 'list', short: 'a', value: 'an agent name' }, }); throwFirstError(errors); return { global: values.global, json: values.json, agent: values.agent }; } /** Listing is read-only, so an unusable lock only costs source info. */ async function readProjectLockOrWarn(cwd: string): Promise<Record<string, ListLockEntry>> { try { return (await readLocalLock(cwd)).skills; } catch (error) { if (!diagnostics.SKILLS_INVALID_LOCAL_LOCK.is(error)) throw error; console.error(`${YELLOW}Warning: ${formatError(error)}${RESET}`); return {}; } } export async function runList(args: string[]): Promise<void> { const options = parseListOptions(args); // Default to project only (local), use -g for global const scope = options.global === true ? true : false; // Validate agent filter if provided let agentFilter: AgentType[] | undefined; if (options.agent && options.agent.length > 0) { const validAgents = Object.keys(agents); const invalidAgents = options.agent.filter((a) => !validAgents.includes(a)); if (invalidAgents.length > 0) { console.log( formatError( diagnostics.SKILLS_INVALID_AGENTS({ invalid: invalidAgents, valid: validAgents }) ) ); process.exit(1); } agentFilter = options.agent as AgentType[]; } const installedSkills = await listInstalledSkills({ global: scope, agentFilter, }); const cwd = process.cwd(); // Fetch lock entries to get source and plugin grouping info for the selected scope. const lockedSkills: Record<string, ListLockEntry> = scope ? await getAllLockedSkills() : await readProjectLockOrWarn(cwd); const lockEntriesBySanitizedName = new Map( Object.entries(lockedSkills).map(([name, entry]) => [sanitizeName(name), entry]) ); const getLockEntry = (skillName: string): ListLockEntry | undefined => lockedSkills[skillName] ?? lockEntriesBySanitizedName.get(sanitizeName(skillName)); // An agent filter hides skills that are on disk, so only an unfiltered listing can tell // that a locked skill is missing. const installedNames = new Set(installedSkills.map((skill) => sanitizeName(skill.name))); const missingSkills = agentFilter ? [] : Object.entries(lockedSkills).filter(([name]) => !installedNames.has(sanitizeName(name))); // Project skills whose files no longer hash to their lock entry const modifiedNames = new Set<string>(); if (!scope) { await Promise.all( installedSkills.map(async (skill) => { const lockEntry = getLockEntry(skill.name); if (lockEntry?.computedHash === undefined) return; const state = await getLockedSkillState( skill.name, { computedHash: lockEntry.computedHash }, cwd, skill.canonicalPath ); if (state === 'modified') modifiedNames.add(skill.name); }) ); } const statusOf = (skill: InstalledSkill): 'tracked' | 'untracked' | 'modified' => !getLockEntry(skill.name) ? 'untracked' : modifiedNames.has(skill.name) ? 'modified' : 'tracked'; // JSON output mode: structured, no ANSI, untruncated agent lists if (options.json) { const jsonOutput = installedSkills.map((skill) => { const lockEntry = getLockEntry(skill.name); return { name: skill.name, path: skill.canonicalPath, scope: skill.scope, agents: skill.agents.map((a) => agents[a].displayName), source: lockEntry?.source ?? null, sourceUrl: lockEntry?.sourceUrl ?? null, sourceType: lockEntry?.sourceType ?? null, renamedFrom: lockEntry?.skillName ?? null, status: statusOf(skill), }; }); const missingOutput = missingSkills.map(([name, lockEntry]) => ({ name, path: null, scope: scope ? 'global' : 'project', agents: [], source: lockEntry.source, sourceUrl: lockEntry.sourceUrl ?? null, sourceType: lockEntry.sourceType, renamedFrom: lockEntry.skillName ?? null, status: 'missing', })); console.log(JSON.stringify([...jsonOutput, ...missingOutput], null, 2)); return; } const scopeLabel = scope ? 'Global' : 'Project'; if (installedSkills.length === 0 && missingSkills.length === 0) { if (options.json) { console.log('[]'); return; } console.log(`${DIM}No ${scopeLabel.toLowerCase()} skills found.${RESET}`); if (scope) { console.log(`${DIM}Try listing project skills without -g${RESET}`); } else { console.log(`${DIM}Try listing global skills with -g${RESET}`); } return; } function printSkill( skill: InstalledSkill, indent: boolean = false, maxNameLength: number = 0, maxPathLength: number = 0 ): void { const prefix = indent ? ' ' : ''; const shortPath = shortenPath(skill.canonicalPath, cwd); const agentNames = skill.agents.map((a) => agents[a].displayName); const agentInfo = skill.agents.length > 0 ? formatList(agentNames) : `${YELLOW}not linked${RESET}`; // Pad skill name and path for alignment const paddedName = sanitizeMetadata(skill.name).padEnd(maxNameLength); const paddedPath = shortPath.padEnd(maxPathLength); // Determine source from lock file const lockEntry = getLockEntry(skill.name); const source = lockEntry?.source ?? null; const sourceLabel = source ? sanitizeMetadata(source) + renamedLabel(lockEntry) : `${YELLOW}untracked${RESET}`; const modifiedLabel = statusOf(skill) === 'modified' ? ` ${YELLOW}modified${RESET} ${DIM}(differs from the lock)${RESET}` : ''; console.log(`${prefix}${CYAN}${paddedName}${RESET} ${DIM}${paddedPath}${RESET}`); console.log( `${prefix} ${DIM}Agents:${RESET} ${agentInfo} ${DIM}Source:${RESET} ${sourceLabel}${modifiedLabel}` ); } console.log(`${BOLD}${scopeLabel} Skills${RESET}`); console.log(); // Group skills by plugin const groupedSkills: Record<string, InstalledSkill[]> = {}; const ungroupedSkills: InstalledSkill[] = []; for (const skill of installedSkills) { const lockEntry = getLockEntry(skill.name); if (lockEntry?.pluginName) { const group = lockEntry.pluginName; if (!groupedSkills[group]) { groupedSkills[group] = []; } groupedSkills[group].push(skill); } else { ungroupedSkills.push(skill); } } const hasGroups = Object.keys(groupedSkills).length > 0; if (hasGroups) { // Print groups sorted alphabetically const sortedGroups = Object.keys(groupedSkills).sort(); for (const group of sortedGroups) { // Convert kebab-case to Title Case for display header const title = group .split('-') .map((w) => w.charAt(0).toUpperCase() + w.slice(1)) .join(' '); console.log(`${BOLD}${title}${RESET}`); const skills = groupedSkills[group]; if (skills) { // Calculate max lengths for alignment within this group let maxNameLength = 0; let maxPathLength = 0; for (const skill of skills) { const nameLength = sanitizeMetadata(skill.name).length; const pathLength = shortenPath(skill.canonicalPath, cwd).length; if (nameLength > maxNameLength) maxNameLength = nameLength; if (pathLength > maxPathLength) maxPathLength = pathLength; } for (const skill of skills) { printSkill(skill, true, maxNameLength, maxPathLength); } } console.log(); } // Print ungrouped skills if any exist if (ungroupedSkills.length > 0) { console.log(`${BOLD}General${RESET}`); // Calculate max lengths for alignment within ungrouped skills let maxNameLength = 0; let maxPathLength = 0; for (const skill of ungroupedSkills) { const nameLength = sanitizeMetadata(skill.name).length; const pathLength = shortenPath(skill.canonicalPath, cwd).length; if (nameLength > maxNameLength) maxNameLength = nameLength; if (pathLength > maxPathLength) maxPathLength = pathLength; } for (const skill of ungroupedSkills) { printSkill(skill, true, maxNameLength, maxPathLength); } console.log(); } } else { // No groups, print flat list as before // Calculate max lengths for alignment in flat list let maxNameLength = 0; let maxPathLength = 0; for (const skill of installedSkills) { const nameLength = sanitizeMetadata(skill.name).length; const pathLength = shortenPath(skill.canonicalPath, cwd).length; if (nameLength > maxNameLength) maxNameLength = nameLength; if (pathLength > maxPathLength) maxPathLength = pathLength; } for (const skill of installedSkills) { printSkill(skill, false, maxNameLength, maxPathLength); } console.log(); } if (missingSkills.length > 0) { console.log(`${BOLD}Missing${RESET} ${DIM}(in the lock file, not on disk)${RESET}`); for (const [name, entry] of missingSkills) { console.log( ` ${CYAN}${sanitizeMetadata(name)}${RESET} ${DIM}Source:${RESET} ${sanitizeMetadata(entry.source)}${renamedLabel(entry)}` ); } console.log(); } } - src/local-lock.ts (16821 bytes)
import { access, link, open, readFile, readdir, rename, stat, unlink, writeFile, } from 'fs/promises'; import type { Stats } from 'fs'; import { createHash, randomBytes } from 'crypto'; import { constants, existsSync } from 'fs'; import { isAbsolute, join, relative, resolve, sep } from 'path'; import { diagnostics } from './diagnostics.ts'; import { computeSkillFolderHash } from './skill-hash.ts'; import { sanitizeName } from './sanitize.ts'; import { AGENTS_DIR, SKILLS_SUBDIR } from './constants.ts'; export { computeSkillFolderHash }; const LOCAL_LOCK_FILE = 'skills-lock.json'; /** v2: computedHash is the portable hash from skill-hash.ts. v1 used a locale-dependent one. */ const CURRENT_VERSION = 2; /** * Represents a single skill entry in the local (project) lock file. * * Intentionally minimal and timestamp-free to minimize merge conflicts. * Two branches adding different skills produce non-overlapping JSON keys * that git can auto-merge cleanly. */ export interface LocalSkillLockEntry { /** Where the skill came from: npm package name, owner/repo, local path, etc. */ source: string; /** Original remote URL, when source was normalized for lock readability. */ sourceUrl?: string; /** Branch or tag ref used for installation */ ref?: string; /** * Git commit the skill was installed from. A restore fetches this commit * instead of the tip of `ref`, so an upstream change cannot break it; * `update` moves it forward. Unset for non-Git sources and older locks. */ commit?: string; /** The provider/source type (e.g., "github", "node_modules", "local") */ sourceType: string; /** * Path to the skill's SKILL.md within the source repo (e.g., "skills/pdf/SKILL.md"). * Required to re-install only this skill on update — without it, an update would * refetch every skill in the source repo. For node_modules sources it is relative * to the package root. Optional for backward compatibility with lock files written * before this field existed, and omitted for local paths. */ skillPath?: string; /** * Name of the skill in its source, when it is installed under another name * (`add --rename`); the lock key is the installed name. Omitted otherwise. */ skillName?: string; /** Version of the npm package that shipped the skill (node_modules sources only). */ version?: string; /** Package whose package.json `skills` field requested the skill; `.` is the project. */ via?: string; /** * SHA-256 of the files the installer writes for the skill (see * `computeSkillFolderHash`), so it can be checked against `.agents/skills/<name>`. * Empty when a v1 lock was migrated and the installed skill was absent or no * longer matched the v1 hash: there is nothing trusted to verify against. */ computedHash: string; /** * Eve subagent targets this skill was installed into, so `update` can * restore the same placement. Each entry is an Eve subagent directory name; * the empty string `''` denotes the root agent (`agent/skills`). Omitted for * non-Eve installs and for plain Eve root installs (treated as `['']`). */ subagents?: string[]; wellKnownDigest?: string; /** Set when the user chose copies over symlinks, so `update` reinstalls copies. */ installMode?: 'copy'; } /** * The structure of the local (project-scoped) skill lock file. * This file is meant to be checked into version control. * * Skills are sorted alphabetically by name when written to produce * deterministic output and minimize merge conflicts. */ export interface LocalSkillLockFile { /** Schema version for future migrations */ version: number; /** Map of skill name to its lock entry (sorted alphabetically) */ skills: Record<string, LocalSkillLockEntry>; } /** * Get the path to the local skill lock file for a project. */ export function getLocalLockPath(cwd?: string): string { return join(cwd || process.cwd(), LOCAL_LOCK_FILE); } /** Where a project skill is installed: `.agents/skills/<name>`. */ export function getInstalledSkillDir(skillName: string, cwd?: string): string { return join(cwd || process.cwd(), AGENTS_DIR, SKILLS_SUBDIR, sanitizeName(skillName)); } /** * Read the local skill lock file. * Returns an empty lock when the file does not exist; throws * SKILLS_INVALID_LOCAL_LOCK when it exists but cannot be used (merge conflict * markers, a missing `skills` map, or a schema version this CLI does not know), * since treating such a file as empty would let the next write drop every entry. * * A v1 lock is migrated to v2 without network access: each computedHash is * recomputed from the installed skill, or left empty when it is not installed. * With `persistMigration` the migrated lock is written back. */ export async function readLocalLock( cwd?: string, { persistMigration = false }: { persistMigration?: boolean } = {} ): Promise<LocalSkillLockFile> { const lockDir = cwd || process.cwd(); const lockPath = getLocalLockPath(lockDir); let content: string; try { content = await readFile(lockPath, 'utf-8'); } catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { return createEmptyLocalLock(); } throw error; } let parsed: unknown; try { parsed = JSON.parse(content); } catch (error) { const reason = error instanceof Error ? error.message : 'not valid JSON'; throw diagnostics.SKILLS_INVALID_LOCAL_LOCK({ path: lockPath, reason, cause: error }); } if (!isLocalLockShape(parsed)) { throw diagnostics.SKILLS_INVALID_LOCAL_LOCK({ path: lockPath, reason: 'expected an object with "version" and "skills"', }); } if (parsed.version !== CURRENT_VERSION && parsed.version !== 1) { throw diagnostics.SKILLS_INVALID_LOCAL_LOCK({ path: lockPath, reason: `unsupported lock version ${parsed.version} (expected ${CURRENT_VERSION})`, }); } for (const entry of Object.values(parsed.skills)) { if (entry.sourceType === 'local' && !isAbsolute(entry.source)) { entry.source = resolve(lockDir, entry.source); } } if (parsed.version === 1) { await Promise.all( Object.entries(parsed.skills).map(async ([name, entry]) => { entry.computedHash = await migrateComputedHash( getInstalledSkillDir(name, lockDir), entry.computedHash ); }) ); parsed.version = CURRENT_VERSION; if (persistMigration) await writeLocalLock(parsed, lockDir); } return parsed; } /** * The v2 hash for a v1 entry. Disk is trusted only when it still matches the * locked v1 hash; otherwise the entry gets no hash, so a frozen install fails * and a normal install fetches the skill again instead of trusting edited files. */ async function migrateComputedHash(dir: string, v1Hash: string): Promise<string> { if (!v1Hash || !existsSync(join(dir, 'SKILL.md'))) return ''; try { if ((await computeLegacySkillFolderHash(dir)) !== v1Hash) return ''; return await computeSkillFolderHash(dir); } catch { return ''; } } /** * The v1 computedHash, kept only to verify entries when migrating a v1 lock: * regular files except under .git/ and node_modules/, sorted with * localeCompare, each as path then content with no framing. */ export async function computeLegacySkillFolderHash(skillDir: string): Promise<string> { const files: Array<{ relativePath: string; content: Buffer }> = []; const collect = async (currentDir: string): Promise<void> => { const entries = await readdir(currentDir, { withFileTypes: true }); await Promise.all( entries.map(async (entry) => { const fullPath = join(currentDir, entry.name); if (entry.isDirectory()) { if (entry.name === '.git' || entry.name === 'node_modules') return; await collect(fullPath); } else if (entry.isFile()) { const relativePath = relative(skillDir, fullPath).split('\\').join('/'); files.push({ relativePath, content: await readFile(fullPath) }); } }) ); }; await collect(skillDir); files.sort((a, b) => a.relativePath.localeCompare(b.relativePath)); const hash = createHash('sha256'); for (const file of files) { hash.update(file.relativePath); hash.update(file.content); } return hash.digest('hex'); } /** * How the installed copy of a locked skill compares with its lock entry: * `missing` without a SKILL.md, `modified` when the files no longer hash to * computedHash or there is no hash to check them against, otherwise `tracked`. */ export async function getLockedSkillState( skillName: string, entry: Pick<LocalSkillLockEntry, 'computedHash'>, cwd?: string, /** Where the skill is installed, when not `.agents/skills/<name>`. */ dir: string = getInstalledSkillDir(skillName, cwd) ): Promise<'tracked' | 'missing' | 'modified'> { if (!existsSync(join(dir, 'SKILL.md'))) return 'missing'; // No hash means the files could not be verified when a v1 lock was migrated if (!entry.computedHash) return 'modified'; const hash = await computeSkillFolderHash(dir).catch(() => null); return hash === entry.computedHash ? 'tracked' : 'modified'; } function isLocalLockShape(value: unknown): value is LocalSkillLockFile { return ( typeof value === 'object' && value !== null && 'version' in value && typeof value.version === 'number' && 'skills' in value && typeof value.skills === 'object' && value.skills !== null ); } // The lock is held only for one read and one write, so a lock older than // STALE_LOCK_MS was left by a crashed process. It must be shorter than the // acquire timeout, or a waiter gives up before it may break the stale lock. const LOCK_ACQUIRE_TIMEOUT_MS = 10_000; const STALE_LOCK_MS = 5_000; function isNodeErrorCode(error: unknown, ...codes: string[]): boolean { return error instanceof Error && 'code' in error && codes.includes(String(error.code)); } /** * Remove a stale lock without removing a live one. Moving it to a unique name * lets only one waiter claim it. If another waiter broke it first and a new * holder took the lock in between, the moved file is that live lock: put it back. */ async function breakStaleLock(mutexPath: string, stale: Stats): Promise<void> { const claimed = `${mutexPath}.${process.pid}.${randomBytes(6).toString('hex')}.stale`; try { await rename(mutexPath, claimed); } catch { return; } const moved = await stat(claimed).catch(() => null); if (moved && moved.mtimeMs !== stale.mtimeMs) await link(claimed, mutexPath).catch(() => {}); await unlink(claimed).catch(() => {}); } /** * Serialize local lock mutations both in-process and across OS processes using * an exclusive companion lock file. */ async function withLocalLock<T>(lockPath: string, fn: () => Promise<T>): Promise<T> { const mutexPath = `${resolve(lockPath)}.lock`; const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS; while (true) { try { const handle = await open(mutexPath, 'wx'); await handle.close().catch(() => {}); break; } catch (error) { if (!isNodeErrorCode(error, 'EEXIST')) throw error; const lockStat = await stat(mutexPath).catch(() => null); if (lockStat && Date.now() - lockStat.mtimeMs > STALE_LOCK_MS) { await breakStaleLock(mutexPath, lockStat); continue; } if (Date.now() >= deadline) { throw diagnostics.SKILLS_LOCAL_LOCK_BUSY({ path: mutexPath, cause: error }); } await new Promise((r) => setTimeout(r, 10 + Math.floor(Math.random() * 15))); } } try { return await fn(); } finally { await unlink(mutexPath).catch(() => {}); } } async function renameWithWindowsRetry(src: string, dest: string): Promise<void> { const maxAttempts = process.platform === 'win32' ? 5 : 1; for (let attempt = 1; ; attempt++) { try { await rename(src, dest); return; } catch (error) { if (attempt < maxAttempts && isNodeErrorCode(error, 'EPERM', 'EBUSY')) { await new Promise((r) => setTimeout(r, attempt * 15)); continue; } throw error; } } } async function writeLocalLockUnlocked( lock: LocalSkillLockFile, lockDir: string, lockPath: string ): Promise<void> { // Sort skills alphabetically for deterministic output / clean diffs const sortedSkills = Object.fromEntries( Object.keys(lock.skills) .sort() .map((key): [string, LocalSkillLockEntry] => { const entry = lock.skills[key]!; return [ key, entry.sourceType === 'local' ? { ...entry, source: getPortableLocalSource(entry.source, lockDir) } : entry, ]; }) ); const sorted: LocalSkillLockFile = { version: lock.version, skills: sortedSkills }; const content = JSON.stringify(sorted, null, 2) + '\n'; // Preserve write-permission errors on read-only lock files across POSIX (where rename mutates the parent dir). try { await access(lockPath, constants.W_OK); } catch (error) { if (!isNodeErrorCode(error, 'ENOENT')) { throw error; } } const tempPath = `${lockPath}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`; await writeFile(tempPath, content, 'utf-8'); try { await renameWithWindowsRetry(tempPath, lockPath); } catch (error) { await unlink(tempPath).catch(() => {}); throw error; } } /** * Write the local skill lock file. * Skills are sorted alphabetically by name for deterministic output. */ export async function writeLocalLock(lock: LocalSkillLockFile, cwd?: string): Promise<void> { const lockDir = cwd || process.cwd(); const lockPath = getLocalLockPath(lockDir); await withLocalLock(lockPath, () => writeLocalLockUnlocked(lock, lockDir, lockPath)); } function getPortableLocalSource(source: string, lockDir: string): string { const absoluteSource = isAbsolute(source) ? source : resolve(lockDir, source); const relativeSource = relative(lockDir, absoluteSource); // Different Windows drives cannot be represented by a relative path. if (isAbsolute(relativeSource)) { return absoluteSource.split(sep).join('/'); } const portableSource = relativeSource.split(sep).join('/'); if (!portableSource) return '.'; if (portableSource === '..' || portableSource.startsWith('../')) return portableSource; return `./${portableSource}`; } /** * Add or update a skill entry in the local lock file. */ export async function addSkillToLocalLock( skillName: string, entry: LocalSkillLockEntry, cwd?: string ): Promise<void> { const lockDir = cwd || process.cwd(); const lockPath = getLocalLockPath(lockDir); await withLocalLock(lockPath, async () => { const lock = await readLocalLock(lockDir); lock.skills = { ...lock.skills, [skillName]: entry }; await writeLocalLockUnlocked(lock, lockDir, lockPath); }); } /** * Why recording `entry` for `s - src/notion-test.test.ts (14536 bytes)
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { downloadNotionUrl, fetchNotionPackDirectory, fetchNotionPacks, fetchNotionWorkspaceName, isNotionSource, parseNotionSkillUrl, prepareNotionPackSource, prepareNotionSkillSource, type NotionPack, type NtnRunner, } from './notion-test.ts'; import { discoverSkills } from './skills.ts'; const cleanupDirs: string[] = []; afterEach(() => { for (const dir of cleanupDirs.splice(0)) { if (existsSync(dir)) rmSync(dir, { recursive: true, force: true }); } }); function listResponse( results: unknown[], options: { hasMore?: boolean; nextCursor?: string | null } = {} ): string { return JSON.stringify({ object: 'list', results, next_cursor: options.nextCursor ?? null, has_more: options.hasMore ?? false, type: 'plugin', }); } function meResponse(workspaceName: unknown): string { return JSON.stringify({ object: 'user', type: 'bot', bot: { workspace_name: workspaceName } }); } describe('Notion pack prototype', () => { it('uses only paginated ntn list calls and returns packs without fetching details', async () => { const runNtn = vi.fn<NtnRunner>(async (args) => { const cursor = args.find((arg) => arg.startsWith('start_cursor==')); if (!cursor) { return listResponse( [ { id: '>tO?', name: 'Company-wide', description: '', version_id: 'a'.repeat(64), }, ], { hasMore: true, nextCursor: 'next123' } ); } return listResponse([ { id: '6be44900-5769-4e54-ba7e-a6411285f214', name: 'Draft Skills', description: 'Draft plugin pack', version_id: 'b'.repeat(64), }, ]); }); const packs = await fetchNotionPacks({ runNtn }); expect(packs.map((pack) => pack.name)).toEqual(['Company-wide', 'Draft Skills']); expect(runNtn).toHaveBeenCalledTimes(2); expect(runNtn).toHaveBeenNthCalledWith(1, [ 'api', '/v1/ai/plugins', 'page_size==100', '--notion-version', '2026-03-11', ]); expect(runNtn).toHaveBeenNthCalledWith(2, [ 'api', '/v1/ai/plugins', 'page_size==100', 'start_cursor==next123', '--notion-version', '2026-03-11', ]); expect(runNtn.mock.calls.flat(2).join(' ')).not.toContain('/v1/ai/plugins/>tO?'); expect(runNtn.mock.calls.flat(2).join(' ')).not.toContain( '/v1/ai/plugins/6be44900-5769-4e54-ba7e-a6411285f214' ); }); it('accepts omitted pack descriptions from the alpha API', async () => { const runNtn = vi.fn<NtnRunner>(async () => listResponse([ { id: '~R\\;', name: 'Product Design', version_id: 'a'.repeat(64), }, ]) ); const packs = await fetchNotionPacks({ runNtn }); expect(packs).toEqual([ { id: '~R\\;', name: 'Product Design', description: '', version_id: 'a'.repeat(64), }, ]); }); it('skips untitled packs without dropping valid packs', async () => { const runNtn = vi.fn<NtnRunner>(async () => listResponse([ { id: '3c2e06b0-59c4-801c-8759-e7644ddb1138', name: '', description: '', version_id: 'a'.repeat(64), }, { id: 'dbd17050-94d4-4c94-b311-ac5f9e49ea87', name: 'Weekly Metrics Review', description: 'Analyzes a metrics table.', version_id: 'b'.repeat(64), }, ]) ); const packs = await fetchNotionPacks({ runNtn }); expect(packs.map((pack) => pack.name)).toEqual(['Weekly Metrics Review']); }); it('percent-encodes opaque pack IDs for lazy directory lookup', async () => { const pack: NotionPack = { id: '>tO?', name: 'Company-wide', description: '', version_id: 'a'.repeat(64), }; const runNtn = vi.fn<NtnRunner>(async () => JSON.stringify({ id: pack.id, version_id: pack.version_id, url: 'https://downloads.example/company-wide.tgz', }) ); const directory = await fetchNotionPackDirectory(pack, { runNtn }); expect(directory.url).toBe('https://downloads.example/company-wide.tgz'); expect(runNtn).toHaveBeenCalledWith([ 'api', '/v1/ai/plugins/%3EtO%3F', '--notion-version', '2026-03-11', ]); }); it('stages selected packs as one grouped local install source', async () => { const pack: NotionPack = { id: '>tO?', name: 'Company-wide', description: '', version_id: 'a'.repeat(64), }; const downloadTemp = mkdtempSync(join(tmpdir(), 'notion-pack-download-test-')); cleanupDirs.push(downloadTemp); const downloadRoot = join(downloadTemp, 'company-wide'); const skillDir = join(downloadRoot, 'skills', 'write-update'); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), '---\nname: write-update\ndescription: Write a company update\n---\n' ); const runNtn = vi.fn<NtnRunner>(async (args) => { if (args[1] === '/v1/users/me') return meResponse('Acme HQ'); if (args[1] === '/v1/ai/plugins') return listResponse([pack]); return JSON.stringify({ id: pack.id, version_id: pack.version_id, url: 'https://downloads.example/company-wide.tgz', }); }); const prepared = await prepareNotionPackSource({ yes: true, runNtn, download: vi.fn(async () => ({ rootDir: downloadRoot, tempDir: downloadTemp, kind: 'archive' as const, })), }); expect(prepared).not.toBeNull(); cleanupDirs.push(prepared!.tempDir); const stagedSkills = await discoverSkills(prepared!.rootDir, undefined, { fullDepth: true }); expect( stagedSkills.map((skill) => ({ name: skill.name, pluginName: skill.pluginName })) ).toEqual([{ name: 'write-update', pluginName: 'Company-wide' }]); expect(prepared).toMatchObject({ packCount: 1, skillCount: 1 }); expect(prepared!.downloads).toEqual([ { url: 'notion://packs/%3EtO%3F', rootDir: join(prepared!.rootDir, 'packs', 'pack-1-company-wide'), }, ]); // list + workspace probe, then the pack directory lookup expect(runNtn).toHaveBeenCalledTimes(3); }); it('rejects invalid repeated pagination cursors', async () => { const runNtn = vi.fn<NtnRunner>(async () => listResponse([], { hasMore: true, nextCursor: 'same123' }) ); await expect(fetchNotionPacks({ runNtn })).rejects.toThrow( 'Notion Agent Plugins pagination returned an invalid cursor' ); expect(runNtn).toHaveBeenCalledTimes(2); }); it('reports invalid JSON returned by ntn', async () => { const runNtn = vi.fn<NtnRunner>(async () => 'not json'); await expect(fetchNotionPacks({ runNtn })).rejects.toThrow( 'ntn returned invalid JSON for the Notion packs list' ); }); it.each(['notion', 'NOTION'])('recognizes %s as a Notion source', (source) => { expect(isNotionSource(source)).toBe(true); }); it.each([ 'notion-test', 'https://www.notion.so/acme/Skills-123', 'https://acme.notion.site/Skills-123', 'notion.example', 'https://example.com/notion', 'owner/notion', ])('does not treat %s as a Notion source', (source) => { expect(isNotionSource(source)).toBe(false); }); }); describe('Notion single skill', () => { it.each([ [ 'https://app.notion.com/p/notiondevs/Capture-meeting-decisions-c169bd0a546a45d48344ffacad25d763?source=copy_link', 'c169bd0a-546a-45d4-8344-ffacad25d763', ], [ 'https://www.notion.so/Capture-meeting-decisions-c169bd0a546a45d48344ffacad25d763', 'c169bd0a-546a-45d4-8344-ffacad25d763', ], [ 'https://notion.so/acme/c169bd0a-546a-45d4-8344-ffacad25d763', 'c169bd0a-546a-45d4-8344-ffacad25d763', ], ])('extracts the page ID from %s', (source, expected) => { expect(parseNotionSkillUrl(source)).toBe(expected); }); it.each([ 'notion', 'vercel-labs/agent-skills', 'https://github.com/vercel-labs/agent-skills', 'https://notion.so/acme', 'https://notion.example.com/p/c169bd0a546a45d48344ffacad25d763', './local-skill', ])('does not treat %s as a Notion skill URL', (source) => { expect(parseNotionSkillUrl(source)).toBeNull(); }); it('downloads the skill directory for a page ID as a local install source', async () => { const pageId = 'c169bd0a-546a-45d4-8344-ffacad25d763'; const downloadTemp = mkdtempSync(join(tmpdir(), 'notion-skill-download-test-')); cleanupDirs.push(downloadTemp); const downloadRoot = join(downloadTemp, 'capture-meeting-decisions'); mkdirSync(downloadRoot, { recursive: true }); writeFileSync( join(downloadRoot, 'SKILL.md'), '---\nname: capture-meeting-decisions\ndescription: Capture decisions from meeting notes\n---\n' ); const runNtn = vi.fn<NtnRunner>(async (args) => args[1] === '/v1/users/me' ? meResponse('Acme HQ') : JSON.stringify({ id: pageId, version_id: 'c'.repeat(64), url: 'https://downloads.example/capture-meeting-decisions.tgz', }) ); const download = vi.fn(async () => ({ rootDir: downloadRoot, tempDir: downloadTemp, kind: 'archive' as const, })); const prepared = await prepareNotionSkillSource(pageId, { runNtn, download }); expect(prepared).toEqual({ rootDir: downloadRoot, tempDir: downloadTemp, // The lock keeps the page id only, not the temporary download URL. downloads: [ { url: 'https://www.notion.so/c169bd0a546a45d48344ffacad25d763', rootDir: downloadRoot }, ], }); expect(runNtn).toHaveBeenCalledWith([ 'api', `/v1/ai/skills/${pageId}`, '--notion-version', '2026-03-11', ]); expect(download).toHaveBeenCalledWith( 'https://downloads.example/capture-meeting-decisions.tgz' ); const skills = await discoverSkills(prepared.rootDir); expect(skills.map((skill) => skill.name)).toEqual(['capture-meeting-decisions']); }); it('reports invalid JSON returned by ntn for a skill', async () => { const runNtn = vi.fn<NtnRunner>(async () => 'not json'); await expect( prepareNotionSkillSource('c169bd0a-546a-45d4-8344-ffacad25d763', { runNtn }) ).rejects.toThrow( 'ntn returned invalid JSON for Notion skill c169bd0a-546a-45d4-8344-ffacad25d763' ); }); }); describe('Notion workspace reporting', () => { it('reads the workspace name from the authenticated ntn session', async () => { const runNtn = vi.fn<NtnRunner>(async () => meResponse('Notion Developers')); await expect(fetchNotionWorkspaceName({ runNtn })).resolves.toBe('Notion Developers'); expect(runNtn).toHaveBeenCalledWith(['api', '/v1/users/me', '--notion-version', '2026-03-11']); }); it.each([ ['invalid JSON', async () => 'not json'], ['a missing bot field', async () => JSON.stringify({ object: 'user' })], ['a non-string workspace name', async () => meResponse(42)], [ 'an ntn failure', async () => { throw new Error('ntn api failed'); }, ], ])('returns null rather than throwing on %s', async (_label, impl) => { await expect(fetchNotionWorkspaceName({ runNtn: vi.fn<NtnRunner>(impl) })).resolves.toBeNull(); }); it('still installs a skill when the workspace lookup fails', async () => { const pageId = 'c169bd0a-546a-45d4-8344-ffacad25d763'; const downloadTemp = mkdtempSync(join(tmpdir(), 'notion-skill-noworkspace-')); cleanupDirs.push(downloadTemp); const downloadRoot = join(downloadTemp, 'capture-meeting-decisions'); mkdirSync(downloadRoot, { recursive: true }); writeFileSync(join(downloadRoot, 'SKILL.md'), '---\nname: x\ndescription: y\n---\n'); const runNtn = vi.fn<NtnRunner>(async (args) => { if (args[1] === '/v1/users/me') throw new Error('workspace probe exploded'); return JSON.stringify({ id: pageId, version_id: 'c'.repeat(64), url: 'https://downloads.example/x.tgz', }); }); await expect( prepareNotionSkillSource(pageId, { runNtn, download: vi.fn(async () => ({ rootDir: downloadRoot, tempDir: downloadTemp, kind: 'archive' as const, })), }) ).resolves.toMatchObject({ rootDir: downloadRoot, tempDir: downloadTemp }); }); }); describe('Notion lock URLs', () => { const download = vi.fn(async (url: string) => ({ rootDir: url, tempDir: url, kind: 'archive' as const, })); it('downloads a locked pack through a fresh ntn directory URL', async () => { const pack = { id: 'pack-team', name: 'Team', description: '', version_id: 'v2' }; const runNtn = vi.fn<NtnRunner>(async (args) => args[1] === '/v1/ai/plugins' ? listResponse([pack]) : JSON.stringify({ id: pack.id, version_id: 'v2', url: 'https://dl.example/team.tgz' }) ); const downloaded = await downloadNotionUrl('notion://packs/pack-team', { runNtn, download }); expect(downloaded?.rootDir).toBe('https://dl.example/team.tgz'); }); it('fails when the locked pack is no longer in the workspace', async () => { const runNtn = vi.fn<NtnRunner>(async () => listResponse([])); await expect( downloadNotionUrl('notion://packs/pack-gone', { runNtn, download }) ).rejects.toThrow('No matching Notion packs found for: pack-gone'); }); it('downloads a locked skill page', async () => { const runNtn = vi.fn<NtnRunner>(async () => JSON.stringify({ id: 'x', version_id: 'p2', url: 'https://dl.example/page.tgz' }) ); const downloaded = await downloadNotionUrl( 'https://www.notion.so/c169bd0a546a45d48344ffacad25d763', { runNtn, download } ); expect(downloaded?.rootDir).toBe('https://dl.example/page.tgz'); expect(runNtn.mock.calls[0]![0][1]).toBe('/v1/ai/skills/c169bd0a-546a-45d4-8344-ffacad25d763'); }); it('leaves other URLs to a plain download', async () => { await expect(downloadNotionUrl('https://example.com/skill.md')).resolves.toBeNull(); }); }); - src/notion-test.ts (20020 bytes)
import * as p from '@clack/prompts'; import { pc } from './color.ts'; import { spawn } from 'node:child_process'; import { cp, mkdir, mkdtemp, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, relative, sep } from 'node:path'; import type { Diagnostic } from 'nostics'; import { diagnostics } from './diagnostics.ts'; import { downloadSource, type DownloadedSource } from './download-source.ts'; import { cleanupTempDir } from './git.ts'; import { sanitizeName } from './installer.ts'; import { sanitizeMetadata, stripTerminalEscapes } from './sanitize.ts'; import { searchMultiselect } from './prompts/search-multiselect.ts'; import { discoverSkills } from './skills.ts'; const NOTION_API_VERSION = '2026-03-11'; const NTN_TIMEOUT_MS = 30_000; const NTN_MAX_BUFFER_BYTES = 10 * 1024 * 1024; const NOTION_DOWNLOAD_MAX_BYTES = 50 * 1024 * 1024; const NOTION_EXTRACT_MAX_BYTES = 100 * 1024 * 1024; const NOTION_EXTRACT_MAX_FILES = 5000; export interface NotionPack { id: string; name: string; description: string; version_id: string; } interface NotionPackListResponse { results: NotionPack[]; next_cursor: string | null; has_more: boolean; } interface NotionDirectory { id: string; version_id: string; url: string; } /** A directory a Notion install was downloaded into, and the URL that downloads it again. */ export interface NotionDownloadRoot { url: string; rootDir: string; } export interface PreparedNotionPackSource { rootDir: string; tempDir: string; packCount: number; skillCount: number; /** One per selected pack, so each skill can be locked to its pack. */ downloads: NotionDownloadRoot[]; } export interface PreparedNotionSkillSource { rootDir: string; tempDir: string; downloads: NotionDownloadRoot[]; } export interface NotionPackSelectorOptions { yes?: boolean; list?: boolean; skill?: string[]; } export type NtnRunner = (args: string[]) => Promise<string>; interface FetchNotionPacksOptions { runNtn?: NtnRunner; } interface PrepareNotionPackSourceOptions extends NotionPackSelectorOptions { runNtn?: NtnRunner; download?: (url: string) => Promise<DownloadedSource>; discover?: typeof discoverSkills; } interface PrepareNotionSkillSourceOptions { runNtn?: NtnRunner; download?: (url: string) => Promise<DownloadedSource>; } function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === 'object' && value !== null && !Array.isArray(value); } function assertString(value: unknown, field: string): string { if (typeof value !== 'string' || value.length === 0) { throw diagnostics.SKILLS_NOTION_RESPONSE_MISSING_FIELD({ response: 'response', field }); } return value; } function optionalMetadata(value: unknown, field: string): string { if (value === undefined || value === null) return ''; if (typeof value !== 'string') { throw diagnostics.SKILLS_NOTION_RESPONSE_INVALID_FIELD({ response: 'response', field }); } return sanitizeMetadata(value); } function parsePack(value: unknown): NotionPack | null { if (!isRecord(value)) { throw diagnostics.SKILLS_NOTION_INVALID_PACK(); } if (typeof value.name !== 'string') { throw diagnostics.SKILLS_NOTION_RESPONSE_MISSING_FIELD({ response: 'response', field: 'pack.name', }); } const name = sanitizeMetadata(value.name); if (!name) return null; return { id: assertString(value.id, 'pack.id'), name, description: optionalMetadata(value.description, 'pack.description'), version_id: assertString(value.version_id, 'pack.version_id'), }; } function parsePackList(value: unknown): NotionPackListResponse { if (!isRecord(value) || !Array.isArray(value.results)) { throw diagnostics.SKILLS_NOTION_INVALID_LIST_RESPONSE(); } if (typeof value.has_more !== 'boolean') { throw diagnostics.SKILLS_NOTION_RESPONSE_MISSING_FIELD({ response: 'list response', field: 'has_more', }); } const nextCursor = value.next_cursor; if (nextCursor !== null && typeof nextCursor !== 'string') { throw diagnostics.SKILLS_NOTION_RESPONSE_INVALID_FIELD({ response: 'list response', field: 'next_cursor', }); } const results = value.results.map(parsePack).filter((pack) => pack !== null); return { results, next_cursor: nextCursor, has_more: value.has_more, }; } function parseDirectory(value: unknown, label: string): NotionDirectory { if (!isRecord(value)) { throw diagnostics.SKILLS_NOTION_INVALID_DIRECTORY_RESPONSE({ label }); } return { id: assertString(value.id, `${label} directory id`), version_id: assertString(value.version_id, `${label} directory version_id`), url: assertString(value.url, `${label} directory url`), }; } function downloadNotionDirectory(url: string): Promise<DownloadedSource> { return downloadSource(url, { downloadMaxBytes: NOTION_DOWNLOAD_MAX_BYTES, extractMaxBytes: NOTION_EXTRACT_MAX_BYTES, extractMaxFiles: NOTION_EXTRACT_MAX_FILES, }); } function debugNtn(args: string[]): void { if (process.env.SKILLS_DEBUG === '1') { console.error(`[notion] ntn ${args.join(' ')}`); } } export async function runNtnApi(args: string[]): Promise<string> { debugNtn(args); return new Promise((resolve, reject) => { const child = spawn('ntn', args, { env: process.env, stdio: ['ignore', 'pipe', 'pipe'], }); const stdoutChunks: Buffer[] = []; const stderrChunks: Buffer[] = []; let outputBytes = 0; let settled = false; const finish = (callback: () => void): void => { if (settled) return; settled = true; clearTimeout(timeout); callback(); }; const fail = (error: Diagnostic): void => finish(() => reject(error)); const append = (chunks: Buffer[], chunk: Buffer): void => { outputBytes += chunk.length; if (outputBytes > NTN_MAX_BUFFER_BYTES) { child.kill('SIGTERM'); fail(diagnostics.SKILLS_NOTION_API_OUTPUT_TOO_LARGE()); return; } chunks.push(chunk); }; const timeout = setTimeout(() => { child.kill('SIGTERM'); fail(diagnostics.SKILLS_NOTION_API_TIMEOUT({ seconds: NTN_TIMEOUT_MS / 1000 })); }, NTN_TIMEOUT_MS); child.stdout.on('data', (chunk: Buffer) => append(stdoutChunks, chunk)); child.stderr.on('data', (chunk: Buffer) => append(stderrChunks, chunk)); child.on('error', (error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') { fail(diagnostics.SKILLS_NOTION_CLI_MISSING({ cause: error })); return; } fail( diagnostics.SKILLS_NOTION_CLI_START_FAILED({ detail: stripTerminalEscapes(error.message), cause: error, }) ); }); child.on('close', (code) => { const stdout = Buffer.concat(stdoutChunks).toString('utf8'); const stderr = stripTerminalEscapes(Buffer.concat(stderrChunks).toString('utf8')).trim(); if (code === 0) { finish(() => resolve(stdout)); return; } fail(diagnostics.SKILLS_NOTION_API_FAILED({ stderr, exitCode: code })); }); }); } async function fetchNotionJson( args: string[], label: string, runNtn: NtnRunner = runNtnApi ): Promise<unknown> { const output = await runNtn(['api', ...args, '--notion-version', NOTION_API_VERSION]); try { return JSON.parse(output) as unknown; } catch (error) { if (error instanceof SyntaxError) { throw diagnostics.SKILLS_NOTION_INVALID_JSON({ label, cause: error }); } throw error; } } export async function fetchNotionPacks( options: FetchNotionPacksOptions = {} ): Promise<NotionPack[]> { const runNtn = options.runNtn ?? runNtnApi; const packs: NotionPack[] = []; const seenCursors = new Set<string>(); let cursor: string | null = null; do { const args = ['/v1/ai/plugins', 'page_size==100']; if (cursor) args.push(`start_cursor==${cursor}`); const value = await fetchNotionJson(args, 'the Notion packs list', runNtn); const page = parsePackList(value); packs.push(...page.results); if (!page.has_more) break; if (!page.next_cursor || seenCursors.has(page.next_cursor)) { throw diagnostics.SKILLS_NOTION_INVALID_CURSOR(); } cursor = page.next_cursor; seenCursors.add(cursor); } while (cursor); return packs; } export async function fetchNotionPackDirectory( pack: NotionPack, options: FetchNotionPacksOptions = {} ): Promise<NotionDirectory> { const value = await fetchNotionJson( [`/v1/ai/plugins/${encodeURIComponent(pack.id)}`], `Notion pack ${JSON.stringify(pack.name)}`, options.runNtn ); const directory = parseDirectory(value, 'pack'); if (directory.id !== pack.id || directory.version_id !== pack.version_id) { throw diagnostics.SKILLS_NOTION_PACK_CHANGED({ pack: pack.name }); } return directory; } /** Workspace `ntn` is authenticated against. Null on any failure, so a probe * can never block an install. */ export async function fetchNotionWorkspaceName( options: FetchNotionPacksOptions = {} ): Promise<string | null> { const runNtn = options.runNtn ?? runNtnApi; try { const args = ['api', '/v1/users/me', '--notion-version', NOTION_API_VERSION]; const value = JSON.parse(await runNtn(args)) as unknown; if (!isRecord(value) || !isRecord(value.bot)) return null; const name = value.bot.workspace_name; return typeof name === 'string' && name.length > 0 ? sanitizeMetadata(name) : null; } catch { return null; } } function inWorkspace(workspace: string | null): string { return workspace ? ` in workspace ${pc.cyan(workspace)}` : ''; } export function isNotionSource(source: string): boolean { return source.toLowerCase() === 'notion'; } const NOTION_HOSTNAME = /(^|\.)notion\.(so|com)$/; const NOTION_PAGE_ID = /(?:^|-)([0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/; function formatPageId(rawId: string): string { const hex = rawId.replace(/-/g, ''); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } /** Page ID from a Notion page URL, else null so other source formats still * fall through to the ordinary handling. */ export function parseNotionSkillUrl(source: string): string | null { let url: URL; try { url = new URL(source); } catch { return null; } if (url.protocol !== 'https:' && url.protocol !== 'http:') return null; if (!NOTION_HOSTNAME.test(url.hostname.toLowerCase())) return null; const lastSegment = url.pathname.split('/').filter(Boolean).pop(); if (!lastSegment) return null; let decoded: string; try { decoded = decodeURIComponent(lastSegment); } catch { decoded = lastSegment; } const match = decoded.toLowerCase().match(NOTION_PAGE_ID); return match ? formatPageId(match[1]!) : null; } const NOTION_PACK_URL_PREFIX = 'notion://packs/'; /** * The lock URL of a Notion pack. ntn hands out a temporary download URL, so * the lock records the pack id and `update` asks ntn for a fresh one. */ export function notionPackUrl(packId: string): string { return NOTION_PACK_URL_PREFIX + encodeURIComponent(packId); } function parseNotionPackUrl(url: string): string | null { if (!url.startsWith(NOTION_PACK_URL_PREFIX)) return null; const id = decodeURIComponent(url.slice(NOTION_PACK_URL_PREFIX.length)); return id || null; } /** The lock URL of a Notion skill page: its id only, without the title slug or query. */ export function notionPageUrl(pageId: string): string { return `https://www.notion.so/${pageId.replace(/-/g, '')}`; } export function isNotionPackUrl(url: string): boolean { return parseNotionPackUrl(url) !== null; } /** * Download a Notion pack or skill page recorded in a lock file, without * terminal output. Null when `url` is not a Notion lock URL. */ export async function downloadNotionUrl( url: string, options: PrepareNotionSkillSourceOptions = {} ): Promise<DownloadedSource | null> { const download = options.download ?? downloadNotionDirectory; const packId = parseNotionPackUrl(url); if (packId) { const packs = await fetchNotionPacks({ runNtn: options.runNtn }); const pack = packs.find((candidate) => candidate.id === packId); if (!pack) throw diagnostics.SKILLS_NOTION_NO_MATCHING_PACKS({ requested: [packId] }); const directory = await fetchNotionPackDirectory(pack, { runNtn: options.runNtn }); return download(directory.url); } const pageId = parseNotionSkillUrl(url); if (pageId) { const directory = await fetchNotionSkillDirectory(pageId, { runNtn: options.runNtn }); return download(directory.url); } return null; } export async function fetchNotionSkillDirectory( pageId: string, options: FetchNotionPacksOptions = {} ): Promise<NotionDirectory> { const value = await fetchNotionJson( [`/v1/ai/skills/${encodeURIComponent(pageId)}`], `Notion skill ${pageId}`, options.runNtn ); return parseDirectory(value, 'skill'); } /** The archive's one top-level directory holds SKILL.md, so the extracted root * is already usable as a local source. */ export async function prepareNotionSkillSource( pageId: string, options: PrepareNotionSkillSourceOptions = {} ): Promise<PreparedNotionSkillSource> { const download = options.download ?? downloadNotionDirectory; const spinner = p.spinner(); spinner.start('Fetching Notion skill with ntn…'); try { const [directory, workspace] = await Promise.all([ fetchNotionSkillDirectory(pageId, { runNtn: options.runNtn }), fetchNotionWorkspaceName({ runNtn: options.runNtn }), ]); const downloaded = await download(directory.url); spinner.stop(`Downloaded skill from Notion${inWorkspace(workspace)}`); return { rootDir: downloaded.rootDir, tempDir: downloaded.tempDir, downloads: [{ url: notionPageUrl(pageId), rootDir: downloaded.rootDir }], }; } catch (error) { spinner.stop(pc.red('Failed to prepare Notion skill')); throw error; } } function normalizeSelector(value: string): string { return value .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-|-$/g, ''); } function filterPacks(packs: NotionPack[], selectors: string[]): NotionPack[] { if (selectors.includes('*')) return packs; const normalized = new Set(selectors.map(normalizeSelector)); return packs.filter( (pack) => normalized.has(normalizeSelector(pack.name)) || normalized.has(pack.id.toLowerCase()) ); } function sortedPacks(packs: NotionPack[]): NotionPack[] { return [...packs].sort((a, b) => a.name.localeCompare(b.name)); } function printAvailablePacks(packs: NotionPack[]): void { console.log(); p.log.step(pc.bold('Available Notion packs')); for (const pack of sortedPacks(packs)) { p.log.message(pc.cyan(pack.name)); if (pack.description) p.log.message(` ${pc.dim(pack.description)}`); } - src/parse-remove-options.test.ts (1333 bytes)
import { describe, it, expect } from 'vitest'; import { parseRemoveOptions } from './remove.ts'; describe('parseRemoveOptions', () => { it('parses positional skill names', () => { const result = parseRemoveOptions(['skill-one', 'skill-two', '-y']); expect(result.skills).toEqual(['skill-one', 'skill-two']); expect(result.options.yes).toBe(true); }); it('parses -s/--skill names (documented remove flag)', () => { const result = parseRemoveOptions(['--skill', 'skill-one', 'skill-two', '-g']); expect(result.skills).toEqual(['skill-one', 'skill-two']); expect(result.options.global).toBe(true); }); it('does not treat --skill as an unknown token that drops the following name', () => { // Regression: --skill was previously ignored, so // `remove --skill foo --all` still collected `foo` as a positional name // while --all wiped every skill. const result = parseRemoveOptions(['--skill', 'agent-thread-visualizer', '--all', '-y']); expect(result.skills).toEqual(['agent-thread-visualizer']); expect(result.options.all).toBe(true); expect(result.options.yes).toBe(true); }); it('sets yes when --all is used', () => { const result = parseRemoveOptions(['--all']); expect(result.options.all).toBe(true); expect(result.options.yes).toBe(true); }); }); - src/plugin-manifest.ts (6778 bytes)
import { readFile } from 'fs/promises'; import { join, dirname, resolve, normalize, sep } from 'path'; /** * Check if a path is contained within a base directory. * Prevents path traversal attacks via `..` segments or absolute paths. */ function isContainedIn(targetPath: string, basePath: string): boolean { const normalizedBase = normalize(resolve(basePath)); const normalizedTarget = normalize(resolve(targetPath)); return normalizedTarget.startsWith(normalizedBase + sep) || normalizedTarget === normalizedBase; } /** * Validate that a relative path follows Claude Code conventions. * Paths must start with './' per the plugin manifest spec. */ function isValidRelativePath(path: string): boolean { return path.startsWith('./'); } /** * Plugin manifest types */ interface PluginManifestEntry { source?: string | { source: string; repo?: string }; skills?: string[]; /** Optional name for grouping skills (e.g., "document-skills") */ name?: string; } interface MarketplaceManifest { metadata?: { pluginRoot?: string }; plugins?: PluginManifestEntry[]; } interface PluginManifest { skills?: string[]; name?: string; } /** * Extract skill search directories from plugin manifests. * Handles both marketplace.json (multi-plugin) and plugin.json (single plugin). * Only resolves local paths - remote sources are skipped. * * Returns directories that CONTAIN skills (to be searched for child SKILL.md files). * For explicit skill paths in manifests, adds the parent directory so the * existing discovery loop finds them. */ export async function getPluginSkillPaths(basePath: string): Promise<string[]> { const searchDirs: string[] = []; // Helper: add skill paths for a plugin at a given base path // Only adds paths that are contained within basePath (security: prevents traversal) const addPluginSkillPaths = (pluginBase: string, skills?: string[]) => { // Validate pluginBase itself is contained if (!isContainedIn(pluginBase, basePath)) return; if (skills && skills.length > 0) { // Plugin explicitly declares skill paths - add parent dirs so existing loop finds them for (const skillPath of skills) { // Validate skill path starts with './' (per Claude Code convention) if (!isValidRelativePath(skillPath)) continue; const skillDir = dirname(join(pluginBase, skillPath)); if (isContainedIn(skillDir, basePath)) { searchDirs.push(skillDir); } } } // Always add conventional skills/ directory for discovery // (deduplication happens via seenNames in discoverSkills) searchDirs.push(join(pluginBase, 'skills')); }; // Try marketplace.json (multi-plugin catalog) try { const content = await readFile(join(basePath, '.claude-plugin/marketplace.json'), 'utf-8'); const manifest: MarketplaceManifest = JSON.parse(content); const pluginRoot = manifest.metadata?.pluginRoot; // Validate pluginRoot starts with './' if provided (per Claude Code convention) const validPluginRoot = pluginRoot === undefined || isValidRelativePath(pluginRoot); if (validPluginRoot) { for (const plugin of manifest.plugins ?? []) { // Skip remote sources (object with source/repo) - only handle local string paths if (typeof plugin.source !== 'string' && plugin.source !== undefined) continue; // Validate source starts with './' if provided (per Claude Code convention) if (plugin.source !== undefined && !isValidRelativePath(plugin.source)) continue; const pluginBase = join(basePath, pluginRoot ?? '', plugin.source ?? ''); addPluginSkillPaths(pluginBase, plugin.skills); } } } catch { // File doesn't exist or invalid JSON } // Try plugin.json (single plugin at root) try { const content = await readFile(join(basePath, '.claude-plugin/plugin.json'), 'utf-8'); const manifest: PluginManifest = JSON.parse(content); addPluginSkillPaths(basePath, manifest.skills); } catch { // File doesn't exist or invalid JSON } return searchDirs; } /** * Get a map of skill directory paths to plugin names from plugin manifests. * This allows grouping skills by their parent plugin. * * Returns Map<AbsolutePath, PluginName> */ export async function getPluginGroupings(basePath: string): Promise<Map<string, string>> { const groupings = new Map<string, string>(); // Try marketplace.json (multi-plugin catalog) try { const content = await readFile(join(basePath, '.claude-plugin/marketplace.json'), 'utf-8'); const manifest: MarketplaceManifest = JSON.parse(content); const pluginRoot = manifest.metadata?.pluginRoot; // Validate pluginRoot starts with './' if provided (per Claude Code convention) const validPluginRoot = pluginRoot === undefined || isValidRelativePath(pluginRoot); if (validPluginRoot) { for (const plugin of manifest.plugins ?? []) { if (!plugin.name) continue; // Skip remote sources (object with source/repo) - only handle local string paths if (typeof plugin.source !== 'string' && plugin.source !== undefined) continue; // Validate source starts with './' if provided (per Claude Code convention) if (plugin.source !== undefined && !isValidRelativePath(plugin.source)) continue; const pluginBase = join(basePath, pluginRoot ?? '', plugin.source ?? ''); // Validate pluginBase itself is contained if (!isContainedIn(pluginBase, basePath)) continue; if (plugin.skills && plugin.skills.length > 0) { for (const skillPath of plugin.skills) { // Validate skill path starts with './' (per Claude Code convention) if (!isValidRelativePath(skillPath)) continue; const skillDir = join(pluginBase, skillPath); if (isContainedIn(skillDir, basePath)) { // Store absolute path as key for reliable matching groupings.set(resolve(skillDir), plugin.name); } } } } } } catch { // File doesn't exist or invalid JSON } // Try plugin.json (single plugin at root) try { const content = await readFile(join(basePath, '.claude-plugin/plugin.json'), 'utf-8'); const manifest: PluginManifest = JSON.parse(content); if (manifest.name && manifest.skills && manifest.skills.length > 0) { for (const skillPath of manifest.skills) { if (!isValidRelativePath(skillPath)) continue; const skillDir = join(basePath, skillPath); if (isContainedIn(skillDir, basePath)) { groupings.set(resolve(skillDir), manifest.name); } } } } catch { // File doesn't exist or invalid JSON } return groupings; } - src/prompts/search-multiselect.test.ts (1159 bytes)
import { describe, it, expect } from 'vitest'; import { toggleSelectAll } from './search-multiselect.ts'; describe('toggleSelectAll', () => { it('selects every filtered item when none are selected', () => { const selected = new Set<string>(); const filtered = [ { value: 'a', label: 'A' }, { value: 'b', label: 'B' }, { value: 'c', label: 'C' }, ]; toggleSelectAll(selected, filtered); expect([...selected]).toEqual(['a', 'b', 'c']); }); it('deselects everything when all filtered items are already selected', () => { const selected = new Set(['a', 'b', 'c']); const filtered = [ { value: 'a', label: 'A' }, { value: 'b', label: 'B' }, { value: 'c', label: 'C' }, ]; toggleSelectAll(selected, filtered); expect(selected.size).toBe(0); }); it('selects only the filtered subset, ignoring items filtered out by search', () => { const selected = new Set(['x']); const filtered = [ { value: 'a', label: 'A' }, { value: 'b', label: 'B' }, ]; toggleSelectAll(selected, filtered); expect([...selected].sort()).toEqual(['a', 'b', 'x']); }); }); - src/prompts/search-multiselect.ts (25945 bytes)
import * as readline from 'readline'; import { stripVTControlCharacters } from 'node:util'; import { Writable } from 'stream'; import { pc } from '../color.ts'; // Silent writable stream to prevent readline from echoing input const silentOutput = new Writable({ write(_chunk, _encoding, callback) { callback(); }, }); export interface SearchItem<T> { value: T; label: string; hint?: string; /** Optional group heading shown before this item. */ group?: string; /** Optional detail rendered in a fixed pane for the highlighted item. */ detail?: string; } export interface LockedSection<T> { title: string; items: SearchItem<T>[]; hiddenCount?: number; } export interface SearchMultiselectOptions<T> { message: string; items: SearchItem<T>[]; maxVisible?: number; initialSelected?: T[]; /** If true, require at least one item to be selected before submitting */ required?: boolean; /** Locked section shown above the searchable list - items are always selected and can't be toggled */ lockedSection?: LockedSection<T>; /** Whether to render a search input and accept text input. Defaults to true. */ searchable?: boolean; /** Whether to render a fixed-height detail pane for the highlighted item. */ showDetail?: boolean; /** Number of rows reserved for the detail pane. Defaults to two. */ detailLines?: number; /** Whether to display the selected-item summary. Defaults to true. */ showSelectedSummary?: boolean; /** Whether group headings are selectable and toggle every item in the group. */ selectGroups?: boolean; /** Whether to show a distinct Select All row above the selectable items. */ selectAll?: boolean; } export type SearchEntry<T> = | { type: 'item'; item: SearchItem<T> } | { type: 'group'; group: string; items: SearchItem<T>[]; collapsed: boolean }; const S_STEP_ACTIVE = pc.green('◆'); const S_STEP_CANCEL = pc.red('■'); const S_STEP_SUBMIT = pc.green('◇'); const S_RADIO_ACTIVE = pc.green('●'); const S_RADIO_INACTIVE = pc.dim('○'); const S_CHECKBOX_LOCKED = pc.green('✓'); const S_BULLET = pc.green('•'); const S_BAR = pc.dim('│'); const S_BAR_H = pc.dim('─'); export const cancelSymbol = Symbol('cancel'); /** * Approximate terminal display width (cells) for a string with no ANSI sequences. * Matches common East Asian / emoji double-width behavior used by modern terminals. */ export function approxStringWidth(plain: string): number { let width = 0; for (const ch of plain) { const code = ch.codePointAt(0)!; if (code === 0) continue; const wide = (code >= 0x1100 && code <= 0x115f) || (code >= 0x231a && code <= 0x231b) || (code >= 0x2329 && code <= 0x232a) || (code >= 0x23e9 && code <= 0x23ec) || code === 0x23f0 || code === 0x23f3 || (code >= 0x25fd && code <= 0x25fe) || (code >= 0x2614 && code <= 0x2615) || (code >= 0x2648 && code <= 0x2653) || (code >= 0x267f && code <= 0x267f) || (code >= 0x2693 && code <= 0x2693) || (code >= 0x26a1 && code <= 0x26a1) || (code >= 0x26aa && code <= 0x26ab) || (code >= 0x26bd && code <= 0x26be) || (code >= 0x26c4 && code <= 0x26c5) || (code >= 0x26ce && code <= 0x26ce) || (code >= 0x26d4 && code <= 0x26d4) || (code >= 0x26ea && code <= 0x26ea) || (code >= 0x26f2 && code <= 0x26f3) || (code >= 0x26f5 && code <= 0x26f5) || (code >= 0x26fa && code <= 0x26fa) || (code >= 0x26fd && code <= 0x26fd) || (code >= 0x2705 && code <= 0x2705) || (code >= 0x270a && code <= 0x270b) || (code >= 0x2728 && code <= 0x2728) || (code >= 0x274c && code <= 0x274c) || (code >= 0x274e && code <= 0x274e) || (code >= 0x2753 && code <= 0x2755) || (code >= 0x2757 && code <= 0x2757) || (code >= 0x2795 && code <= 0x2797) || (code >= 0x27b0 && code <= 0x27b0) || (code >= 0x27bf && code <= 0x27bf) || (code >= 0x2b1b && code <= 0x2b1c) || (code >= 0x2b50 && code <= 0x2b50) || (code >= 0x2b55 && code <= 0x2b55) || (code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) || (code >= 0xa960 && code <= 0xa97c) || (code >= 0xac00 && code <= 0xd7a3) || (code >= 0xf900 && code <= 0xfaff) || (code >= 0xfe10 && code <= 0xfe19) || (code >= 0xfe30 && code <= 0xfe6f) || (code >= 0xff00 && code <= 0xff60) || (code >= 0xffe0 && code <= 0xffe6) || (code >= 0x1f000 && code <= 0x1f9ff); width += wide ? 2 : 1; } return width; } /** * How many physical terminal rows one logical line occupies after soft-wrapping. */ export function visualRowsForLine(line: string, columns: number): number { const plain = stripVTControlCharacters(line); const cols = Math.max(1, columns); const w = approxStringWidth(plain); return Math.max(1, Math.ceil(w / cols)); } /** * Total physical rows for a block of logical lines (used to erase/redraw TUI output). */ export function countVisualRowsForLines(lines: string[], columns: number | undefined): number { const cols = columns !== undefined && columns > 0 ? columns : process.stdout.columns && process.stdout.columns > 0 ? process.stdout.columns : 80; return lines.reduce((sum, line) => sum + visualRowsForLine(line, cols), 0); } function truncateToWidth(text: string, width: number): string { let truncated = ''; for (const char of text) { if (approxStringWidth(truncated + char) > width) break; truncated += char; } return truncated; } /** * Wrap description text into a fixed number of terminal-width-safe lines. * Empty lines are appended so changing the highlighted item never changes the * prompt's logical height. */ export function formatDetailLines( detail: string | undefined, width: number, maxLines: number ): string[] { const safeWidth = Math.max(1, width); const normalized = detail?.replace(/\s+/g, ' ').trim() ?? ''; const lines: string[] = []; let remaining = normalized; while (remaining && lines.length < maxLines) { if (approxStringWidth(remaining) <= safeWidth) { lines.push(remaining); remaining = ''; break; } const candidate = truncateToWidth(remaining, safeWidth); const breakAt = candidate.lastIndexOf(' '); if (breakAt > 0) { lines.push(candidate.slice(0, breakAt).trimEnd()); remaining = remaining.slice(breakAt).trimStart(); } else { lines.push(candidate); remaining = remaining.slice(candidate.length).trimStart(); } } if (remaining && lines.length > 0) { const last = lines.length - 1; lines[last] = `${truncateToWidth(lines[last]!, Math.max(0, safeWidth - 1)).trimEnd()}…`; } while (lines.length < maxLines) lines.push(''); return lines; } /** Build the navigable rows for a prompt, including selectable group headings. */ export function buildSearchEntries<T>( items: SearchItem<T>[], selectGroups: boolean, collapsedGroups: ReadonlySet<string> = new Set() ): SearchEntry<T>[] { if (!selectGroups) return items.map((item) => ({ type: 'item', item })); const entries: SearchEntry<T>[] = []; let index = 0; while (index < items.length) { const item = items[index]!; if (!item.group) { entries.push({ type: 'item', item }); index += 1; continue; } const groupItems: SearchItem<T>[] = []; while (index < items.length && items[index]!.group === item.group) { groupItems.push(items[index]!); index += 1; } const collapsed = collapsedGroups.has(item.group); entries.push({ type: 'group', group: item.group, items: groupItems, collapsed }); if (!collapsed) { entries.push(...groupItems.map((groupItem) => ({ type: 'item' as const, item: groupItem }))); } } return entries; } /** Toggle one item, or every item represented by a selectable group heading. */ export function toggleSearchEntry<T>(selected: Set<T>, entry: SearchEntry<T> | undefined): void { if (entry?.type === 'group') { const allSelected = entry.items.every((item) => selected.has(item.value)); for (const item of entry.items) { if (allSelected) { selected.delete(item.value); } else { selected.add(item.value); } } } else if (entry?.type === 'item') { if (selected.has(entry.item.value)) { selected.delete(entry.item.value); } else { selected.add(entry.item.value); } } } export function toggleSelectAll<T>(selected: Set<T>, filtered: SearchItem<T>[]): void { const allSelected = filtered.every((item) => selected.has(item.value)); for (const item of filtered) { if (allSelected) selected.delete(item.value); else selected.add(item.value); } } export type SelectAllState = 'none' | 'partial' | 'all'; /** Return the aggregate selection state represented by a Select All row. */ export function getSelectAllState<T>( selected: ReadonlySet<T>, items: SearchItem<T>[] ): SelectAllState { const selectedCount = items.filter((item) => selected.has(item.value)).length; if (selectedCount === 0) return 'none'; if (selectedCount === items.length) return 'all'; return 'partial'; } /** Select every item unless they are all selected, in which case clear them all. */ export function toggleAllItems<T>(selected: Set<T>, items: SearchItem<T>[]): void { const shouldClear = getSelectAllState(selected, items) === 'all'; for (const item of items) { if (shouldClear) { selected.delete(item.value); } else { selected.add(item.value); } } } /** * Interactive search multiselect prompt. * Allows users to filter a long list by typing and select multiple items. * Optionally supports a "locked" section that displays always-selected items. */ export async function searchMultiselect<T>( options: SearchMultiselectOptions<T> ): Promise<T[] | symbol> { const { message, items, maxVisible = 8, initialSelected = [], required = false, lockedSection, searchable = true, showDetail = false, detailLines = 2, showSelectedSummary = true, selectGroups = false, selectAll = false, } = options; return new Promise((resolve) => { const rl = readline.createInterface({ input: process.stdin, output: silentOutput, terminal: false, }); // Enable raw mode for keypress detection if (process.stdin.isTTY) { process.stdin.setRawMode(true); } readline.emitKeypressEvents(process.stdin, rl); let query = ''; let cursor = 0; const selected = new Set<T>(initialSelected); const collapsedGroups = new Set<string>(); let lastRenderHeight = 0; // Locked items are always included in the result const lockedValues = lockedSection ? lockedSection.items.map((i) => i.value) : []; const filter = (item: SearchItem<T>, q: string): boolean => { if (!q) return true; const lowerQ = q.toLowerCase(); return ( item.label.toLowerCase().includes(lowerQ) || String(item.value).toLowerCase().includes(lowerQ) ); }; const getFiltered = (): SearchItem<T>[] => { return items.filter((item) => filter(item, query)); }; const render = (state: 'active' | 'submit' | 'cancel' = 'active'): void => { const lines: string[] = []; const filtered = getFiltered(); const entries = buildSearchEntries(filtered, selectGroups, collapsedGroups); const hasSelectAll = selectAll && items.length > 0; const entryCursor = cursor - (hasSelectAll ? 1 : 0); // Header const icon = state === 'active' ? S_STEP_ACTIVE : state === 'cancel' ? S_STEP_CANCEL : S_STEP_SUBMIT; lines.push(`${icon} ${pc.bold(message)}`); if (state === 'active') { // Locked section (universal agents) if (lockedSection && lockedSection.items.length > 0) { lines.push(`${S_BAR}`); const lockedTitle = `${pc.bold(lockedSection.title)} ${pc.dim('── always included')}`; lines.push(`${S_BAR} ${S_BAR_H}${S_BAR_H} ${lockedTitle} ${S_BAR_H.repeat(12)}`); for (const item of lockedSection.items) { lines.push(`${S_BAR} ${S_BULLET} ${pc.bold(item.label)}`); } if (lockedSection.hiddenCount && lockedSection.hiddenCount > 0) { lines.push(`${S_BAR} ${pc.dim(`…and ${lockedSection.hiddenCount} more`)}`); } lines.push(`${S_BAR}`); lines.push( `${S_BAR} ${S_BAR_H}${S_BAR_H} ${pc.bold('Additional agents')} ${S_BAR_H.repeat(29)}` ); } if (searchable) { const searchLine = `${S_BAR} ${pc.dim('Search:')} ${query}${pc.inverse(' ')}`; lines.push(searchLine); lines.push( `${S_BAR} ${pc.dim('↑↓ move, space select, ctrl+a select all, enter confirm')}` ); lines.push(`${S_BAR}`); } if (hasSelectAll) { const selectedCount = items.filter((item) => selected.has(item.value)).length; const selectAllState = getSelectAllState(selected, items); const radio = selectAllState === 'all' ? S_RADIO_ACTIVE : selectAllState === 'partial' ? pc.yellow('◐') : S_RADIO_INACTIVE; const isCursor = cursor === 0; const prefix = isCursor ? pc.cyan('❯') : ' '; const label = isCursor ? pc.underline(pc.bold('Select All')) : pc.bold('Select All'); lines.push( `${S_BAR} ${prefix} ${radio} ${label} ${pc.dim(`(${selectedCount}/${items.length})`)}` ); lines.push(`${S_BAR} ${S_BAR_H.repeat(36)}`); } const columns = process.stdout.columns && process.stdout.columns > 0 ? process.stdout.columns : 80; const buildFooterLines = ( includeDetail: boolean, includeSelectedSummary: boolean ): string[] => { const footerLines: string[] = []; if (includeDetail) { const entry = entries[entryCursor]; const detail = hasSelectAll && cursor === 0 ? `Select or clear all ${items.length} skills.` : entry?.type === 'group' ? `Select all ${entry.items.length} skills in ${entry.group}.` : entry?.item.detail; // Keep a small margin for the left rail and terminal wrapping behavior. const detailWidth = Math.max(1, columns - 5); footerLines.push(`${S_BAR}`); footerLines.push(`${S_BAR} ${pc.dim('Description')}`); for (const line of formatDetailLines(detail, detailWidth, detailLines)) { footerLines.push(`${S_BAR} ${pc.dim(line)}`); } } if (includeSelectedSummary) { // Selected summary (include locked items) footerLines.push(`${S_BAR}`); const allSelectedLabels - src/providers/index.ts (507 bytes)
// Export types export type { HostProvider, ProviderMatch, ProviderRegistry, RemoteSkill } from './types.ts'; // Export registry functions export { registry, registerProvider, findProvider, getProviders } from './registry.ts'; // Export individual providers export { WellKnownProvider, wellKnownProvider, computeWellKnownSkillDigest, type NormalizedWellKnownEntry, type WellKnownIndex, type WellKnownSkillEntry, type WellKnownSkill, type DiscoveredWellKnownSkill, } from './wellknown.ts'; - src/providers/registry.ts (1302 bytes)
import { diagnostics } from '../diagnostics.ts'; import type { HostProvider, ProviderRegistry } from './types.ts'; class ProviderRegistryImpl implements ProviderRegistry { private providers: HostProvider[] = []; register(provider: HostProvider): void { // Check for duplicate IDs if (this.providers.some((p) => p.id === provider.id)) { throw diagnostics.SKILLS_PROVIDER_ALREADY_REGISTERED({ id: provider.id }); } this.providers.push(provider); } findProvider(url: string): HostProvider | null { for (const provider of this.providers) { const match = provider.match(url); if (match.matches) { return provider; } } return null; } getProviders(): HostProvider[] { return [...this.providers]; } } // Singleton registry instance export const registry = new ProviderRegistryImpl(); /** * Register a provider with the global registry. */ export function registerProvider(provider: HostProvider): void { registry.register(provider); } /** * Find a provider that matches the given URL. */ export function findProvider(url: string): HostProvider | null { return registry.findProvider(url); } /** * Get all registered providers. */ export function getProviders(): HostProvider[] { return registry.getProviders(); } - src/providers/types.ts (2813 bytes)
/** * Represents a parsed skill from a remote host. * Different hosts may have different ways of identifying skills. */ export interface RemoteSkill { /** Display name of the skill (from frontmatter) */ name: string; /** Description of the skill (from frontmatter) */ description: string; /** Full markdown content including frontmatter */ content: string; /** The identifier used for installation directory name */ installName: string; /** The original source URL */ sourceUrl: string; /** Any additional metadata from frontmatter */ metadata?: Record<string, unknown>; } /** * Result of attempting to match a URL to a provider. */ export interface ProviderMatch { /** Whether the URL matches this provider */ matches: boolean; /** The source identifier for telemetry/storage (e.g., "mintlify/bun.com", "huggingface/hf-skills/hf-jobs") */ sourceIdentifier?: string; } /** * Interface for remote SKILL.md host providers. * Each provider knows how to: * - Detect if a URL belongs to it * - Fetch and parse SKILL.md files * - Convert URLs to raw content URLs * - Provide source identifiers for telemetry */ export interface HostProvider { /** Unique identifier for this provider (e.g., "mintlify", "huggingface", "github") */ readonly id: string; /** Display name for this provider */ readonly displayName: string; /** * Check if a URL matches this provider. * @param url - The URL to check * @returns Match result with optional source identifier */ match(url: string): ProviderMatch; /** * Fetch and parse a SKILL.md file from the given URL. * @param url - The URL to the SKILL.md file * @returns The parsed skill or null if invalid/not found */ fetchSkill(url: string): Promise<RemoteSkill | null>; /** * Convert a user-facing URL to a raw content URL. * For example, GitHub blob URLs to raw.githubusercontent.com URLs. * @param url - The URL to convert * @returns The raw content URL */ toRawUrl(url: string): string; /** * Get the source identifier for telemetry/storage. * This should be a stable identifier that can be used to group * skills from the same source. * @param url - The original URL * @returns Source identifier (e.g., "mintlify/bun.com", "huggingface/hf-skills/hf-jobs") */ getSourceIdentifier(url: string): string; } /** * Registry for managing host providers. */ export interface ProviderRegistry { /** * Register a new provider. */ register(provider: HostProvider): void; /** * Find a provider that matches the given URL. * @param url - The URL to match * @returns The matching provider or null */ findProvider(url: string): HostProvider | null; /** * Get all registered providers. */ getProviders(): HostProvider[]; } - src/providers/wellknown.ts (28794 bytes)
import { createHash } from 'node:crypto'; import { gunzipSync } from 'node:zlib'; import { readZipArchive } from '../archive.ts'; import { diagnostics } from '../diagnostics.ts'; import { parseFrontmatter } from '../frontmatter.ts'; import { sanitizeMetadata } from '../sanitize.ts'; import { isInternalSkill, shouldInstallInternalSkills } from '../skills.ts'; import type { HostProvider, ProviderMatch, RemoteSkill } from './types.ts'; const DISCOVERY_SCHEMA_V2 = 'https://schemas.agentskills.io/discovery/0.2.0/schema.json'; const MAX_ARCHIVE_UNPACKED_BYTES = 50 * 1024 * 1024; const MAX_ARCHIVE_FILES = 1000; const DISCOVERY_TIMEOUT_MS = 10_000; /** * Legacy index.json structure for well-known skills. * This is the pre-0.2.0 format used by existing publishers. */ export interface WellKnownIndexV1 { skills: WellKnownSkillEntryV1[]; } /** * Represents a legacy skill entry in index.json. */ export interface WellKnownSkillEntryV1 { /** Skill identifier. Must match the directory name. */ name: string; /** Brief description of what the skill does. */ description: string; /** Array of all files in the skill directory. */ files: string[]; } /** * Current v0.2.0 well-known discovery index. */ export interface WellKnownIndexV2 { $schema: typeof DISCOVERY_SCHEMA_V2; skills: WellKnownSkillEntryV2[]; } /** * Represents a v0.2.0 skill artifact entry in index.json. */ export interface WellKnownSkillEntryV2 { name: string; type: 'skill-md' | 'archive'; description: string; url: string; digest: string; } export type WellKnownIndex = WellKnownIndexV1 | WellKnownIndexV2; export type WellKnownSkillEntry = WellKnownSkillEntryV1 | WellKnownSkillEntryV2; export type WellKnownFileContent = string | Uint8Array; export type NormalizedWellKnownEntry = | { version: '0.1.0'; name: string; description: string; files: string[]; baseUrl: string; wellKnownPath: string; indexEntry: WellKnownSkillEntryV1; } | { version: '0.2.0'; name: string; description: string; type: 'skill-md' | 'archive'; artifactUrl: string; digest: string; indexEntry: WellKnownSkillEntryV2; }; /** * Represents a skill with all installable files fetched from a well-known endpoint. */ export interface WellKnownSkill extends RemoteSkill { /** All files in the skill, keyed by relative path */ files: Map<string, WellKnownFileContent>; /** The entry from index.json */ indexEntry: WellKnownSkillEntry; } /** Skill metadata available before downloading legacy supporting files. */ export interface DiscoveredWellKnownSkill extends RemoteSkill { filePaths: string[]; load(): Promise<WellKnownSkill>; } export interface FetchAllSkillsOptions { /** Include skills marked with metadata.internal: true. */ includeInternal?: boolean; } /** * Well-known skills provider using RFC 8615 well-known URIs. * * Supports both: * - v0.2.0: $schema + type/url/digest single-artifact model * - legacy/v0.1.0: name/description/files directory model * * Organizations can publish skills at: * https://example.com/.well-known/agent-skills/ (preferred) * https://example.com/.well-known/skills/ (legacy fallback) * * The provider first checks /.well-known/agent-skills/index.json, * then falls back to /.well-known/skills/index.json. For compatibility with * existing publishers, it also preserves the historical path-relative probing * behavior for URLs such as https://example.com/docs. */ export class WellKnownProvider implements HostProvider { readonly id = 'well-known'; readonly displayName = 'Well-Known Skills'; private readonly WELL_KNOWN_PATHS = ['.well-known/agent-skills', '.well-known/skills'] as const; private readonly INDEX_FILE = 'index.json'; /** * Check if a URL could be a well-known skills endpoint. * This is a fallback provider - it matches any HTTP(S) URL that is not * a recognized pattern (GitHub, GitLab, owner/repo shorthand, etc.) */ match(url: string): ProviderMatch { if (!url.startsWith('http://') && !url.startsWith('https://')) { return { matches: false }; } try { const parsed = new URL(url); const excludedHosts = ['github.com', 'gitlab.com', 'huggingface.co']; if (excludedHosts.includes(parsed.hostname)) { return { matches: false }; } return { matches: true, sourceIdentifier: `wellknown/${parsed.hostname}`, }; } catch { return { matches: false }; } } /** * Fetch the skills index from a well-known endpoint. * Tries /.well-known/agent-skills/index.json first, then falls back to * /.well-known/skills/index.json. For each path, tries path-relative * first, then root .well-known. */ async fetchIndex( baseUrl: string, options?: { updateCheck?: boolean } ): Promise<{ index: WellKnownIndex; entries: NormalizedWellKnownEntry[]; resolvedBaseUrl: string; resolvedWellKnownPath: string; indexUrl: string; } | null> { const candidates = await this.fetchIndexCandidates(baseUrl, options); return candidates[0] ?? null; } private async fetchIndexCandidates( baseUrl: string, options?: { updateCheck?: boolean } ): Promise< Array<{ index: WellKnownIndex; entries: NormalizedWellKnownEntry[]; resolvedBaseUrl: string; resolvedWellKnownPath: string; indexUrl: string; }> > { try { const parsed = new URL(baseUrl); const basePath = parsed.pathname.replace(/\/$/, ''); const signal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS); const urlsToTry: Array<{ indexUrl: string; baseUrl: string; wellKnownPath: string; }> = []; for (const wellKnownPath of this.WELL_KNOWN_PATHS) { urlsToTry.push({ indexUrl: `${parsed.protocol}//${parsed.host}${basePath}/${wellKnownPath}/${this.INDEX_FILE}`, baseUrl: `${parsed.protocol}//${parsed.host}${basePath}`, wellKnownPath, }); if (basePath && basePath !== '') { urlsToTry.push({ indexUrl: `${parsed.protocol}//${parsed.host}/${wellKnownPath}/${this.INDEX_FILE}`, baseUrl: `${parsed.protocol}//${parsed.host}`, wellKnownPath, }); } } const candidates: Array<{ index: WellKnownIndex; entries: NormalizedWellKnownEntry[]; resolvedBaseUrl: string; resolvedWellKnownPath: string; indexUrl: string; }> = []; for (const { indexUrl, baseUrl: resolvedBase, wellKnownPath } of urlsToTry) { try { const response = await fetch(indexUrl, { signal, ...(options?.updateCheck ? { headers: { 'X-Skills-Update-Check': '1' } } : {}), }); if (!response.ok) continue; const rawIndex = (await response.json()) as unknown; const normalized = this.normalizeIndex(rawIndex, indexUrl, wellKnownPath); if (!normalized) continue; candidates.push({ index: normalized.index, entries: normalized.entries, resolvedBaseUrl: resolvedBase, resolvedWellKnownPath: wellKnownPath, indexUrl, }); } catch { continue; } } return candidates; } catch { return []; } } private normalizeIndex( rawIndex: unknown, indexUrl: string, resolvedWellKnownPath: string ): { index: WellKnownIndex; entries: NormalizedWellKnownEntry[] } | null { if (!rawIndex || typeof rawIndex !== 'object') return null; const record = rawIndex as Record<string, unknown>; if (!Array.isArray(record.skills)) return null; const schema = record.$schema; if (schema === DISCOVERY_SCHEMA_V2) { const entries: NormalizedWellKnownEntry[] = []; const v2Entries: WellKnownSkillEntryV2[] = []; for (const entry of record.skills) { if (!this.isValidSkillEntryV2(entry)) continue; const artifactUrl = new URL(entry.url, indexUrl).toString(); entries.push({ version: '0.2.0', name: entry.name, description: entry.description, type: entry.type, artifactUrl, digest: entry.digest, indexEntry: entry, }); v2Entries.push(entry); } if (entries.length === 0) return null; return { index: { $schema: DISCOVERY_SCHEMA_V2, skills: v2Entries }, entries }; } // Per the v0.2.0 draft, an absent $schema means legacy/v0.1.0. // Unknown schemas are not processed because the shape may have changed incompatibly. if (schema !== undefined) return null; const v1Entries: WellKnownSkillEntryV1[] = []; const entries: NormalizedWellKnownEntry[] = []; // Preserve legacy all-or-nothing validation behavior for the old files[] format. for (const entry of record.skills) { if (!this.isValidSkillEntryV1(entry)) return null; v1Entries.push(entry); entries.push({ version: '0.1.0', name: entry.name, description: entry.description, files: entry.files, baseUrl: this.getLegacySkillBaseUrl(indexUrl, resolvedWellKnownPath), wellKnownPath: resolvedWellKnownPath, indexEntry: entry, }); } return { index: { skills: v1Entries }, entries }; } private getLegacySkillBaseUrl(indexUrl: string, wellKnownPath: string): string { const parsed = new URL(indexUrl); const marker = `/${wellKnownPath}/${this.INDEX_FILE}`; return `${parsed.protocol}//${parsed.host}${parsed.pathname.slice(0, -marker.length)}`; } private isValidSkillName(name: unknown): name is string { if (typeof name !== 'string') return false; if (name.length < 1 || name.length > 64) return false; if (!/^[a-z0-9-]+$/.test(name)) return false; if (name.startsWith('-') || name.endsWith('-')) return false; if (name.includes('--')) return false; return true; } private isSafeLegacyFilePath(filePath: unknown): filePath is string { if (typeof filePath !== 'string' || filePath.length === 0) return false; // Preserve existing stricter legacy behavior: reject absolute paths, Windows absolute-ish // paths, and any occurrence of "..". if (filePath.startsWith('/') || filePath.startsWith('\\') || filePath.includes('..')) { return false; } if (filePath.includes('\0')) return false; return true; } /** Validate a legacy skill entry from the index. */ private isValidSkillEntryV1(entry: unknown): entry is WellKnownSkillEntryV1 { if (!entry || typeof entry !== 'object') return false; const e = entry as Record<string, unknown>; if (!this.isValidSkillName(e.name)) return false; if (typeof e.description !== 'string' || !e.description) return false; if (!Array.isArray(e.files) || e.files.length === 0) return false; for (const file of e.files) { if (!this.isSafeLegacyFilePath(file)) return false; } const hasSkillMd = e.files.some((f) => typeof f === 'string' && f.toLowerCase() === 'skill.md'); return hasSkillMd; } /** Validate a v0.2.0 skill entry from the index. */ private isValidSkillEntryV2(entry: unknown): entry is WellKnownSkillEntryV2 { if (!entry || typeof entry !== 'object') return false; const e = entry as Record<string, unknown>; if (!this.isValidSkillName(e.name)) return false; if (typeof e.description !== 'string' || !e.description || e.description.length > 1024) { return false; } if (e.type !== 'skill-md' && e.type !== 'archive') return false; if (typeof e.url !== 'string' || !e.url) return false; if (typeof e.digest !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(e.digest)) return false; try { // Ensure URL is resolvable as either absolute or relative. new URL(e.url, 'https://example.com/.well-known/agent-skills/index.json'); } catch { return false; } return true; } /** Fetch a single skill from a well-known endpoint. */ async fetchSkill(url: string): Promise<RemoteSkill | null> { try { const parsed = new URL(url); const candidates = await this.fetchIndexCandidates(url); for (const result of candidates) { const { entries } = result; let skillName: string | null = null; const pathMatch = parsed.pathname.match( /\/.well-known\/(?:agent-skills|skills)\/([^/]+)\/?$/ ); if (pathMatch && pathMatch[1] && pathMatch[1] !== 'index.json') { skillName = pathMatch[1]; } else if (entries.length === 1) { skillName = entries[0]!.name; } if (!skillName) continue; const skillEntry = entries.find((s) => s.name === skillName); if (!skillEntry) continue; const skill = await this.fetchSkillByEntry(skillEntry); if (skill) return skill; } return null; } catch (error) { if ( diagnostics.SKILLS_WELLKNOWN_DIGEST_MISMATCH.is(error) || diagnostics.SKILLS_WELLKNOWN_FILE_FETCH_FAILED.is(error) ) { throw error; } return null; } } /** * Fetch a skill by its normalized index entry. Kept public for tests and * internal add flow; callers with legacy arguments are also supported. */ async fetchSkillByEntry( baseUrlOrEntry: string | NormalizedWellKnownEntry, legacyEntry?: WellKnownSkillEntryV1, legacyWellKnownPath?: string ): Promise<WellKnownSkill | null> { if (typeof baseUrlOrEntry === 'string') { if (!legacyEntry) return null; return this.fetchLegacySkillByEntry({ version: '0.1.0', name: legacyEntry.name, description: legacyEntry.description, files: legacyEntry.files, baseUrl: baseUrlOrEntry, wellKnownPath: legacyWellKnownPath ?? this.WELL_KNOWN_PATHS[0], indexEntry: legacyEntry, }); } if (baseUrlOrEntry.version === '0.1.0') { return this.fetchLegacySkillByEntry(baseUrlOrEntry); } return this.fetchArtifactSkillByEntry(baseUrlOrEntry); } private async fetchLegacySkillByEntry( entry: Extract<NormalizedWellKnownEntry, { version: '0.1.0' }> ): Promise<WellKnownSkill | null> { const skill = await this.discoverLegacySkillByEntry(entry); return skill ? skill.load() : null; } private async discoverLegacySkillByEntry( entry: Extract<NormalizedWellKnownEntry, { version: '0.1.0' }> ): Promise<DiscoveredWellKnownSkill | null> { try { const skillBaseUrl = `${entry.baseUrl.replace(/\/$/, '')}/${entry.wellKnownPath}/${entry.name}`; const skillMdUrl = `${skillBaseUrl}/SKILL.md`; const response = await fetch(skillMdUrl); if (!response.ok) return null; const content = await response.text(); const { data } = parseFrontmatter(content); if (typeo - src/remove.test.ts (35322 bytes)
import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { existsSync, lstatSync, rmSync, mkdirSync, writeFileSync, readdirSync, readFileSync, symlinkSync, } from 'fs'; import { join } from 'path'; import { tmpdir } from 'os'; import { runCli, runCliWithInput } from './test-utils.js'; describe('remove command', { timeout: 30000 }, () => { let testDir: string; let skillsDir: string; beforeEach(() => { testDir = join(tmpdir(), `skills-remove-test-${Date.now()}`); mkdirSync(testDir, { recursive: true }); // Create .agents/skills directory (canonical location) skillsDir = join(testDir, '.agents', 'skills'); mkdirSync(skillsDir, { recursive: true }); }); afterEach(() => { if (existsSync(testDir)) { rmSync(testDir, { recursive: true, force: true }); } }); function createTestSkill( name: string, description = `A test skill called ${name}`, targetSkillsDir = skillsDir ): string { const skillDir = join(targetSkillsDir, name); mkdirSync(skillDir, { recursive: true }); writeFileSync( join(skillDir, 'SKILL.md'), `--- name: ${name} description: ${description} --- # ${name} This is a test skill. ` ); return skillDir; } function createAgentSkillsDir(agentName: string) { const agentSkillsDir = join(testDir, agentName, 'skills'); mkdirSync(agentSkillsDir, { recursive: true }); return agentSkillsDir; } function writeProjectLock(names: string[]) { const skills = Object.fromEntries( names.map((name) => [ name, { source: `example/${name}`, sourceType: 'github', computedHash: 'somehash' }, ]) ); writeFileSync(join(testDir, 'skills-lock.json'), JSON.stringify({ version: 2, skills })); } function readProjectLockKeys(): string[] { return Object.keys(JSON.parse(readFileSync(join(testDir, 'skills-lock.json'), 'utf-8')).skills); } function createSymlink(skillName: string, targetDir: string) { const skillPath = join(skillsDir, skillName); const linkPath = join(targetDir, skillName); try { // Create relative symlink const relativePath = join('..', '..', '.agents', 'skills', skillName); const { symlinkSync } = require('fs'); symlinkSync(relativePath, linkPath); } catch { // Skip if symlinks aren't supported } } describe('with no skills installed', () => { it('should show message when no skills found', () => { const result = runCli(['remove', '-y'], testDir); expect(result.stdout).toContain('No skills found'); expect(result.stdout).toContain('to remove'); expect(result.exitCode).toBe(0); }); it('should show error for non-existent skill name', () => { const result = runCli(['remove', 'non-existent-skill', '-y'], testDir); expect(result.stdout).toContain('No skills found'); expect(result.exitCode).toBe(0); }); it('should clean stale lock entry even when no skills are installed on disk', () => { const lockPath = join(testDir, 'skills-lock.json'); const lockContent = { version: 2, skills: { 'stale-skill': { source: 'some-source', sourceType: 'github', computedHash: 'somehash', }, }, }; writeFileSync(lockPath, JSON.stringify(lockContent, null, 2)); // No skills exist on disk, but stale-skill lingers in the lock file const result = runCli(['remove', 'stale-skill', '-y'], testDir); expect(result.stdout).toContain('Successfully removed'); expect(result.exitCode).toBe(0); const updatedLock = JSON.parse(readFileSync(lockPath, 'utf-8')); expect(updatedLock.skills['stale-skill']).toBeUndefined(); }); it('should clean all stale lock entries with --all', () => { const lockPath = join(testDir, 'skills-lock.json'); writeFileSync( lockPath, JSON.stringify( { version: 2, skills: { 'stale-skill': { source: 'some-source', sourceType: 'github', computedHash: 'somehash', }, }, }, null, 2 ) ); const result = runCli(['remove', '--all', '-y'], testDir); expect(result.stdout).toContain('Successfully removed'); expect(result.exitCode).toBe(0); const updatedLock = JSON.parse(readFileSync(lockPath, 'utf-8')); expect(updatedLock.skills['stale-skill']).toBeUndefined(); }); }); describe('with skills installed', () => { beforeEach(() => { createTestSkill('skill-one', 'First test skill'); createTestSkill('skill-two', 'Second test skill'); createTestSkill('skill-three', 'Third test skill'); // Create symlinks in agent directories const claudeSkillsDir = createAgentSkillsDir('.claude'); createSymlink('skill-one', claudeSkillsDir); createSymlink('skill-two', claudeSkillsDir); const clineSkillsDir = createAgentSkillsDir('.cline'); createSymlink('skill-one', clineSkillsDir); createSymlink('skill-three', clineSkillsDir); }); it('should remove specific skill by name with -y flag', () => { const result = runCli(['remove', 'skill-one', '-y'], testDir); expect(result.stdout).toContain('Successfully removed'); expect(result.stdout).toContain('1 skill'); // Verify skill was removed from canonical location expect(existsSync(join(skillsDir, 'skill-one'))).toBe(false); // Verify other skills still exist expect(existsSync(join(skillsDir, 'skill-two'))).toBe(true); expect(existsSync(join(skillsDir, 'skill-three'))).toBe(true); }); it('should remove multiple skills by name', () => { const result = runCli(['remove', 'skill-one', 'skill-two', '-y'], testDir); expect(result.stdout).toContain('Successfully removed'); expect(result.stdout).toContain('2 skill'); expect(existsSync(join(skillsDir, 'skill-one'))).toBe(false); expect(existsSync(join(skillsDir, 'skill-two'))).toBe(false); expect(existsSync(join(skillsDir, 'skill-three'))).toBe(true); }); it('should remove all skills with --all flag', () => { writeProjectLock(['skill-one', 'skill-two', 'skill-three']); const result = runCli(['remove', '--all', '-y'], testDir); expect(result.stdout).toContain('Successfully removed'); expect(result.stdout).toContain('3 skill'); // All skills removed expect(existsSync(join(skillsDir, 'skill-one'))).toBe(false); expect(existsSync(join(skillsDir, 'skill-two'))).toBe(false); expect(existsSync(join(skillsDir, 'skill-three'))).toBe(false); }); it('should refuse --all combined with a named skill (mass-delete footgun)', () => { const result = runCli(['remove', '--skill', 'skill-one', '--all', '-y'], testDir); expect(result.stdout + result.stderr).toContain( 'Cannot combine --all with specific skill names' ); expect(result.exitCode).toBe(1); // Named skill and siblings must still be present expect(existsSync(join(skillsDir, 'skill-one'))).toBe(true); expect(existsSync(join(skillsDir, 'skill-two'))).toBe(true); expect(existsSync(join(skillsDir, 'skill-three'))).toBe(true); }); it('should remove a skill specified with --skill', () => { const result = runCli(['remove', '--skill', 'skill-two', '-y'], testDir); expect(result.stdout).toContain('Successfully removed'); expect(existsSync(join(skillsDir, 'skill-one'))).toBe(true); expect(existsSync(join(skillsDir, 'skill-two'))).toBe(false); expect(existsSync(join(skillsDir, 'skill-three'))).toBe(true); }); // 'junction' needs no privileges on Windows and is ignored elsewhere; targets are absolute. it('should remove a skill directory that is a symlinked directory (#2679)', () => { const sourceDir = createTestSkill('linked-pet', undefined, join(testDir, 'linked-source')); const skillLink = join(skillsDir, 'linked-pet'); symlinkSync(sourceDir, skillLink, 'junction'); const claudeLink = join(createAgentSkillsDir('.claude'), 'linked-pet'); symlinkSync(skillLink, claudeLink, 'junction'); expect(runCli(['list', '--json'], testDir).stdout).toContain('linked-pet'); const result = runCli(['remove', 'linked-pet', '-y'], testDir); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Successfully removed 1 skill(s)'); expect(lstatSync(skillLink, { throwIfNoEntry: false })).toBeUndefined(); expect(lstatSync(claudeLink, { throwIfNoEntry: false })).toBeUndefined(); // Only the links go; the directory they pointed at is left untouched. expect(readFileSync(join(sourceDir, 'SKILL.md'), 'utf-8')).toContain('name: linked-pet'); expect(runCli(['list', '--json'], testDir).stdout).not.toContain('linked-pet'); }); it('should unlink, not delete, a symlinked skill that only exists in an agent dir on --all', () => { const sourceDir = createTestSkill('agent-linked', undefined, join(testDir, 'linked-source')); const claudeLink = join(createAgentSkillsDir('.claude'), 'agent-linked'); symlinkSync(sourceDir, claudeLink, 'junction'); writeProjectLock(['skill-one', 'skill-two', 'skill-three', 'agent-linked']); const result = runCli(['remove', '--all', '-y'], testDir); expect(result.exitCode).toBe(0); // skill-one..three from beforeEach plus the linked one. expect(result.stdout).toContain('Successfully removed 4 skill(s)'); expect(lstatSync(claudeLink, { throwIfNoEntry: false })).toBeUndefined(); expect(existsSync(join(sourceDir, 'SKILL.md'))).toBe(true); }); it('should ignore a symlink to a directory without SKILL.md', () => { const targetDir = join(testDir, 'not-a-skill'); mkdirSync(targetDir, { recursive: true }); writeFileSync(join(targetDir, 'README.md'), 'not a skill'); symlinkSync(targetDir, join(skillsDir, 'not-a-skill'), 'junction'); const result = runCli(['remove', 'not-a-skill', '-y'], testDir); expect(result.stdout).toContain('No matching skills'); expect(lstatSync(join(skillsDir, 'not-a-skill')).isSymbolicLink()).toBe(true); }); it('should show error for non-existent skill name when skills exist', () => { const result = runCli(['remove', 'non-existent', '-y'], testDir); expect(result.stdout).toContain('No matching skills'); expect(result.exitCode).toBe(0); }); it('should remove skill that is missing from disk but exists in local lock file', () => { const lockPath = join(testDir, 'skills-lock.json'); const lockContent = { version: 2, skills: { 'stale-skill': { source: 'some-source', sourceType: 'github', computedHash: 'somehash', }, }, }; writeFileSync(lockPath, JSON.stringify(lockContent, null, 2)); // stale-skill is missing from disk, but exists in lock file const result = runCli(['remove', 'stale-skill', '-y'], testDir); expect(result.stdout).toContain('Successfully removed'); expect(result.stdout).toContain('1 skill'); expect(result.exitCode).toBe(0); // Verify lock file has been updated to remove the skill const updatedLock = JSON.parse(readFileSync(lockPath, 'utf-8')); expect(updatedLock.skills['stale-skill']).toBeUndefined(); }); it('should remove a sanitized folder using its exact local lock key', () => { createTestSkill('ce-review'); const lockPath = join(testDir, 'skills-lock.json'); writeFileSync( lockPath, JSON.stringify( { version: 2, skills: { 'ce:review': { source: 'everyinc/compound-engineering-plugin', sourceType: 'github', computedHash: 'somehash', }, }, }, null, 2 ) ); const result = runCli(['remove', 'ce:review', '-y'], testDir); expect(result.stdout).toContain('Successfully removed'); expect(existsSync(join(skillsDir, 'ce-review'))).toBe(false); const updatedLock = JSON.parse(readFileSync(lockPath, 'utf-8')); expect(updatedLock.skills['ce:review']).toBeUndefined(); }); it('should be case-insensitive when matching skill names', () => { const result = runCli(['remove', 'SKILL-ONE', '-y'], testDir); expect(result.stdout).toContain('Successfully removed'); expect(existsSync(join(skillsDir, 'skill-one'))).toBe(false); }); it('should remove all skills from an exact lock source', () => { const lockPath = join(testDir, 'skills-lock.json'); writeFileSync( lockPath, JSON.stringify({ version: 2, skills: { 'skill-one': { source: 'mattpocock/skills', sourceType: 'github', computedHash: 'one', }, 'skill-two': { source: 'mattpocock/skills', ref: 'dev', sourceType: 'github', computedHash: 'two', }, 'skill-three': { source: 'other/source', sourceType: 'github', computedHash: 'three', }, }, }) ); const result = runCli(['remove', 'mattpocock/skills', '-y'], testDir); expect(result.stdout).toContain('2 skill'); expect(existsSync(join(skillsDir, 'skill-one'))).toBe(false); expect(existsSync(join(skillsDir, 'skill-two'))).toBe(false); expect(existsSync(join(skillsDir, 'skill-three'))).toBe(true); const updatedLock = JSON.parse(readFileSync(lockPath, 'utf-8')); expect(Object.keys(updatedLock.skills)).toEqual(['skill-three']); }); it('should remove only the specified skill and leave others', () => { runCli(['remove', 'skill-two', '-y'], testDir); // skill-two removed expect(existsSync(join(skillsDir, 'skill-two'))).toBe(false); // Others still exist expect(existsSync(join(skillsDir, 'skill-one'))).toBe(true); expect(existsSync(join(skillsDir, 'skill-three'))).toBe(true); }); it('should list skills to remove before confirmation', () => { // Answer 'n' to cancel the confirmation prompt const result = runCliWithInput(['remove', 'skill-one', 'skill-two'], 'n', testDir); // Should show the skills that will be removed expect(result.stdout).toContain('Skills to remove'); expect(result.stdout).toContain('skill-one'); expect(result.stdout).toContain('skill-two'); expect(result.stdout).toContain('uninstall'); // Skills should NOT be removed since we c - src/remove.ts (21304 bytes)
import * as p from '@clack/prompts'; import { pc } from './color.ts'; import { realpathSync } from 'fs'; import { readdir, rm, lstat } from 'fs/promises'; import { join, relative, sep } from 'path'; import { agents, detectInstalledAgents, getEveSubagents } from './agents.ts'; import { diagnostics, formatError } from './diagnostics.ts'; import { parseCliArgs, throwFirstError } from './cli-args.ts'; import { track } from './telemetry.ts'; import { warn } from './warnings.ts'; import { detectAgent } from './detect-agent.ts'; import { removeSkillFromLock, getSkillFromLock, readSkillLock } from './skill-lock.ts'; import { computeSkillFolderHash, readLocalLock, removeSkillFromLocalLock, type LocalSkillLockEntry, } from './local-lock.ts'; import { hasSkillMd } from './skills.ts'; import type { AgentType } from './types.ts'; import { getInstallPath, getCanonicalPath, getCanonicalSkillsDir, getEveSubagentSkillsDir, isDirEntryOrSymlinkToDir, pathsOverlap, sanitizeName, } from './installer.ts'; export interface RemoveOptions { global?: boolean; agent?: string[]; yes?: boolean; all?: boolean; } /** * Resolve requested skill names to canonical removal targets. * * On-disk folder names are the result of sanitizeName() at install time, but * lock-file keys keep the original name, which may contain characters * sanitizeName() rewrites — e.g. the ':' in plugin skills such as "ce:review" * maps to the folder "ce-review". Matching purely on folder names therefore * misses lock-only or name-mismatched skills (and stale lock entries whose * folder is already gone). Every candidate is canonicalized by its sanitized * name, preferring the lock key, so downstream disk cleanup (which * re-sanitizes) and lock removal (which needs the exact key) both target the * right thing. */ export function resolveSkillsToRemove( requested: string[], folderNames: string[], lockKeys: string[] = [], sourceByKey: Record<string, string | undefined> = {} ): string[] { const identityBySanitized = new Map<string, string>(); for (const folder of folderNames) { identityBySanitized.set(sanitizeName(folder), folder); } // Lock keys win: they carry the exact key needed for lock removal. for (const key of lockKeys) { identityBySanitized.set(sanitizeName(key), key); } const matched = new Set<string>(); for (const name of requested) { const hit = identityBySanitized.get(sanitizeName(name)); if (hit) { matched.add(hit); continue; } // Not a skill name: treat it as an exact lock source and take every skill from it. for (const key of lockKeys) { if (sourceByKey[key] === name) matched.add(key); } } return Array.from(matched); } /** * Installed skill folders no lock key maps to. `remove --all` only removes what * the lock tracks; these are user-authored and are reported as skipped (#604). */ export function findUntrackedSkills(folderNames: string[], lockKeys: string[]): string[] { const tracked = new Set(lockKeys.map(sanitizeName)); return folderNames.filter((folder) => !tracked.has(sanitizeName(folder))); } function isSameDir(a: string, b: string): boolean { try { return realpathSync(a) === realpathSync(b); } catch { return false; } } export async function removeCommand(skillNames: string[], options: RemoveOptions) { // Auto-enable non-interactive mode when running inside an AI agent const agentResult = await detectAgent(); if (agentResult.isAgent) { options.yes = true; p.log.info( pc.bgCyan(pc.black(pc.bold(` ${agentResult.agent.name} `))) + ' ' + 'Agent detected — removing non-interactively' ); } // `--skill '*'` is the documented synonym for selecting every skill. if (skillNames.includes('*')) { options.all = true; skillNames = skillNames.filter((name) => name !== '*'); } // Footgun: `remove --skill foo --all` used to ignore `foo` and wipe everything, // because `--all` replaced the requested list with every installed skill. // Refuse the combination so agents/scripts cannot accidentally mass-delete. const namedSkills = skillNames.filter((name) => name !== '*'); if (options.all && namedSkills.length > 0) { p.log.error( formatError(diagnostics.SKILLS_REMOVE_ALL_WITH_NAMES({ example: namedSkills[0]! })) ); process.exit(1); } const isGlobal = options.global ?? false; const cwd = process.cwd(); const spinner = p.spinner(); spinner.start('Scanning for installed skills…'); const installedSkills = await scanInstalledSkillNames(isGlobal, cwd, (message) => p.log.warn(message) ); spinner.stop(`Found ${installedSkills.length} unique installed skill(s)`); // Read lock file keys up front. These are needed both to decide whether there is // anything to remove (a skill may be missing from disk but still leave a stale lock // entry) and to clean up those stale entries below. const lockEntries = isGlobal ? (await readSkillLock()).skills : (await readLocalLock(cwd)).skills; const lockSkillsKeys = Object.keys(lockEntries); const sourceByKey = Object.fromEntries( lockSkillsKeys.map((key) => [key, lockEntries[key]?.source]) ); // `--all` only removes skills this tool manages (tracked in the lock); skills // dirs may also hold user-authored skills, which must survive (#604). const requestedSkills = options.all ? lockSkillsKeys : skillNames; const resolvedRequestedSkills = options.all || skillNames.length > 0 ? resolveSkillsToRemove(requestedSkills, installedSkills, lockSkillsKeys, sourceByKey) : []; if (installedSkills.length === 0 && resolvedRequestedSkills.length === 0) { p.outro(pc.yellow('No skills found to remove.')); return; } // Validate agent options BEFORE prompting for skill selection if (options.agent && options.agent.length > 0) { const validAgents = Object.keys(agents); const invalidAgents = options.agent.filter((a) => !validAgents.includes(a)); if (invalidAgents.length > 0) { p.log.error( formatError( diagnostics.SKILLS_INVALID_AGENTS({ invalid: invalidAgents, valid: validAgents }) ) ); process.exit(1); } } let selectedSkills: string[] = []; if (options.all) { selectedSkills = resolvedRequestedSkills; const untracked = findUntrackedSkills(installedSkills, lockSkillsKeys); if (untracked.length > 0) { p.log.warn(formatError(diagnostics.SKILLS_REMOVE_UNTRACKED_SKIPPED({ skills: untracked }))); } } else if (skillNames.length > 0) { selectedSkills = resolvedRequestedSkills; if (selectedSkills.length === 0) { p.log.error( formatError( diagnostics.SKILLS_NO_MATCHING_SKILLS({ requested: skillNames, available: [], }) ) ); return; } } else { const choices = installedSkills.map((s) => ({ value: s, label: s, })); const selected = await p.multiselect({ message: `Select skills to remove ${pc.dim('(space to toggle)')}`, options: choices, required: true, }); if (p.isCancel(selected)) { p.cancel('Removal cancelled'); process.exit(0); } selectedSkills = resolveSkillsToRemove(selected as string[], installedSkills, lockSkillsKeys); } // When the project skills dir is the global one (cwd is home), a project-scoped // remove would delete a globally tracked skill and leave its global lock entry (#2469). if (!isGlobal) { const globallyTracked = await findGloballyTrackedSkills(selectedSkills, cwd); if (globallyTracked.length > 0) { p.log.error( formatError(diagnostics.SKILLS_REMOVE_GLOBALLY_TRACKED({ skills: globallyTracked })) ); process.exit(1); } } if (selectedSkills.length === 0) { if (options.all) { p.outro( pc.yellow(`No ${isGlobal ? 'globally managed' : 'lock-tracked'} skills found to remove.`) ); } else { p.outro(pc.yellow('No skills found to remove.')); } return; } let targetAgents: AgentType[]; if (options.agent && options.agent.length > 0) { targetAgents = options.agent as AgentType[]; } else { // When removing, we should target all known agents to ensure // ghost symlinks are cleaned up, even if the agent is not detected. targetAgents = Object.keys(agents) as AgentType[]; spinner.stop(`Targeting ${targetAgents.length} potential agent(s)`); } if (!options.yes) { console.log(); p.log.info('Skills to remove:'); for (const skill of selectedSkills) { p.log.message(` ${pc.red('•')} ${skill}`); } console.log(); const confirmed = await p.confirm({ message: `Are you sure you want to uninstall ${selectedSkills.length} skill(s)?`, }); if (p.isCancel(confirmed) || !confirmed) { p.cancel('Removal cancelled'); process.exit(0); } } spinner.start('Removing skills…'); const results = await removeInstalledSkills(selectedSkills, { global: isGlobal, cwd, targetAgents, onWarn: (message) => p.log.warn(message), }); spinner.stop('Removal process complete'); const successful = results.filter((r) => r.success); const failed = results.filter((r) => !r.success); trackRemovals(results, targetAgents, isGlobal); if (successful.length > 0) { p.log.success(pc.green(`Successfully removed ${successful.length} skill(s)`)); } if (failed.length > 0) { p.log.error(pc.red(`Failed to remove ${failed.length} skill(s)`)); for (const r of failed) { p.log.message(` ${pc.red('✗')} ${r.skill}: ${r.error}`); } } console.log(); p.outro(pc.green('Done!')); } /** Names of skill folders (holding a SKILL.md) installed in `cwd` or globally. */ export async function scanInstalledSkillNames( isGlobal: boolean, cwd: string, onWarn?: (message: string) => void ): Promise<string[]> { const skillNamesSet = new Set<string>(); const scanDir = async (dir: string) => { try { const entries = await readdir(dir, { withFileTypes: true }); for (const entry of entries) { // Dot-directories belong to the agent, not to us: sanitizeName() strips // leading dots, so a skill can never be installed under such a name and // removal could never address one either. Offering Codex's bundled // `$CODEX_HOME/skills/.system` was always a dead entry. if (entry.name.startsWith('.')) continue; // A skill dir may be a symlink to a real directory, e.g. a skill linked // into .agents/skills by hand. listInstalledSkills() follows those, so // removal must scan them the same way or the two commands disagree. if (!(await isDirEntryOrSymlinkToDir(entry, join(dir, entry.name)))) continue; // A directory is only a skill if it holds a SKILL.md, which is what // listInstalledSkills() already requires. Without this, any directory // in a scanned path counted as installed — including the contents of a // source repo's `skills/` folder, which is also OpenClaw's project // install dir and so is always scanned. if (!(await hasSkillMd(join(dir, entry.name)))) continue; skillNamesSet.add(entry.name); } } catch (err) { if (err instanceof Error && (err as { code?: string }).code !== 'ENOENT') { onWarn?.(`Could not scan directory ${dir}: ${err.message}`); } } }; if (isGlobal) { await scanDir(getCanonicalSkillsDir(true, cwd)); for (const agent of Object.values(agents)) { if (agent.globalSkillsDir !== undefined) { await scanDir(agent.globalSkillsDir); } } } else { await scanDir(getCanonicalSkillsDir(false, cwd)); for (const agent of Object.values(agents)) { await scanDir(join(cwd, agent.skillsDir)); } // Eve subagents keep their skills under agent/subagents/<name>/skills. for (const subagent of getEveSubagents(cwd)) { await scanDir(getEveSubagentSkillsDir(subagent, cwd)); } } return Array.from(skillNamesSet).sort(); } /** * Skills in `selected` a project-scoped remove must refuse: when the project * skills dir is the global one (cwd is home), removing would delete a globally * tracked skill and leave its global lock entry (#2469). */ export async function findGloballyTrackedSkills( selected: string[], cwd: string ): Promise<string[]> { if (!isSameDir(getCanonicalSkillsDir(false, cwd), getCanonicalSkillsDir(true))) return []; const lockEntries = (await readLocalLock(cwd)).skills; const globalNames = new Set(Object.keys((await readSkillLock()).skills).map(sanitizeName)); return selected.filter((s) => !lockEntries[s] && globalNames.has(sanitizeName(s))); } /** * Whether the real (non-symlink) directory `path` must survive a project-scoped * remove. Agent dirs outside a dot-directory (OpenClaw's `skills`, `data/skills`, * `agent/skills`) are also ordinary repo folders, often holding the very sources * a skill was installed from, so a matching name proves nothing (#1771). Only an * unmodified copy of a lock-tracked skill, from outside its own source, goes. */ async function isUnmanagedProjectDir( path: string, cwd: string, entry: LocalSkillLockEntry | undefined ): Promise<boolean> { const firstSegment = relative(cwd, path).split(sep)[0] ?? ''; if (firstSegment.startsWith('.')) return false; if (!entry) return true; if (entry.sourceType === 'local' && pathsOverlap(entry.source, path)) return true; const hash = await computeSkillFolderHash(path).catch(() => undefined); return hash !== entry.computedHash; } export interface RemoveSkillResult { skill: string; success: boolean; source?: string; sourceType?: string; /** Name of the skill in its source, when it was installed with `--rename`. */ skillName?: string; error?: string; } /** * Remove `skills` from `targetAgents` without prompting or exiting. The * canonical copy and lock entry go only when no other installed agent uses them. */ export async function removeInstalledSkills( skills: string[], options: { global: boolean; cwd: string; targetAgents: AgentType[]; /** Update the lock file; defaults to true. */ lockfile?: boolean; onWarn?: (message: string) => void; } ): Promise<RemoveSkillResult[]> { const { global: isGlobal, cwd, targetAgents } = options; const results: RemoveSkillResult[] = []; const projectLock = isGlobal ? undefined : (await readLocalLock(cwd)).skills; for (const skillName of skills) { try { const canonicalPath = getCanonicalPath(skillName, { global: isGlobal, cwd }); for (const agentKey of targetAgents) { const agent = agents[agentKey]; const skillPath = getInstallPath(skillName, agentKey, { global: isGlobal, cwd }); // Determine potential paths to cleanup. For universal agents, getInstallPath - src/sanitize.ts (3758 bytes)
/** * Sanitize untrusted strings before terminal output. * * Strips ALL terminal escape sequences from a string, including: * - CSI sequences (ESC [ ... final_byte) — cursor movement, screen clear, SGR colors * - OSC sequences (ESC ] ... BEL/ST) — window title, hyperlinks * - Simple escapes (ESC followed by one char) — e.g. ESC 7 (save cursor) * - C1 control codes (0x80–0x9F) * - Raw control characters (BEL, BS, etc.) — except \t and \n which are safe * * This defends against CWE-150 (terminal escape injection) where * untrusted data (e.g., skill name/description from SKILL.md frontmatter * or remote APIs) could clear the screen, move the cursor, change the * window title, or render attacker-controlled text that looks like * legitimate CLI output. */ // CSI sequences: ESC[ followed by parameter bytes (0x30-0x3F), intermediate bytes (0x20-0x2F), and a final byte (0x40-0x7E) const CSI_RE = /\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]/g; // OSC sequences: ESC] ... terminated by BEL (\x07) or ST (ESC\) const OSC_RE = /\x1b\][\s\S]*?(?:\x07|\x1b\\)/g; // DCS, PM, APC sequences: ESC P|^|_ ... terminated by ST (ESC\) const DCS_PM_APC_RE = /\x1b[P^_][\s\S]*?(?:\x1b\\)/g; // Simple two-byte escape sequences: ESC followed by a single char in 0x20-0x7E range // Includes ESC 7 (DECSC), ESC 8 (DECRC), ESC c (RIS), ESC M (RI), etc. const SIMPLE_ESC_RE = /\x1b[\x20-\x7e]/g; // C1 control codes (0x80-0x9F) — used as 8-bit equivalents of ESC sequences const C1_RE = /[\x80-\x9f]/g; // Raw control characters except tab (\x09) and newline (\x0a) // Includes BEL (\x07), BS (\x08), CR (\x0d), and others const CONTROL_RE = /[\x00-\x06\x07\x08\x0b\x0c\x0d-\x1a\x1c-\x1f\x7f]/g; /** * Strip all terminal escape sequences and dangerous control characters * from a string. * * Safe for use on untrusted input before printing to the terminal. */ export function stripTerminalEscapes(str: string): string { return str .replace(OSC_RE, '') // OSC first (longest match) .replace(DCS_PM_APC_RE, '') // DCS/PM/APC .replace(CSI_RE, '') // CSI sequences .replace(SIMPLE_ESC_RE, '') // Simple ESC+char .replace(C1_RE, '') // C1 control codes .replace(CONTROL_RE, ''); // Raw control chars (keep \t \n) } /** * Sanitize a skill metadata string (name, description, etc.) for safe terminal display. * * In addition to stripping escape sequences, this also trims whitespace and * collapses internal newlines into spaces (skill names/descriptions should * be single-line when displayed). */ export function sanitizeMetadata(str: string): string { return stripTerminalEscapes(str) .replace(/[\r\n]+/g, ' ') .trim(); } /** * Sanitizes a filename/directory name to prevent path traversal attacks * and ensures it follows kebab-case convention * @param name - The name to sanitize * @returns Sanitized name safe for use as a directory name */ export function sanitizeName(name: string): string { const sanitized = name .toLowerCase() // Replace any sequence of characters that are NOT lowercase letters (a-z), // digits (0-9), dots (.), or underscores (_) with a single hyphen. // This converts spaces, special chars, and path traversal attempts (../) into hyphens. .replace(/[^a-z0-9._]+/g, '-') // Remove leading/trailing dots and hyphens to prevent hidden files (.) and // ensure clean directory names. The pattern matches: // - ^[.\-]+ : one or more dots or hyphens at the start // - [.\-]+$ : one or more dots or hyphens at the end .replace(/^[.\-]+|[.\-]+$/g, ''); // Limit to 255 chars (common filesystem limit), fallback to 'unnamed-skill' if empty return sanitized.substring(0, 255) || 'unnamed-skill'; } - ThirdPartyNoticeText.txt (6686 bytes)
/*!----------------- Skills CLI ThirdPartyNotices ------------------------------------------------------- The Skills CLI incorporates third party material from the projects listed below. The original copyright notice and the license under which this material was received are set forth below. These licenses and notices are provided for informational purposes only. --------------------------------------------- Third Party Code Components -------------------------------------------- ================================================================================ Package: @clack/[email protected] License: MIT Repository: https://github.com/bombshell-dev/clack -------------------------------------------------------------------------------- MIT License MIT License Copyright (c) 2025-Present [Bombshell contributors](https://bomb.sh/team) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ Package: [email protected] License: ISC Repository: https://github.com/alexeyraspopov/picocolors -------------------------------------------------------------------------------- ISC License Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ================================================================================ Package: [email protected] License: MIT Repository: https://github.com/steveukx/git-js -------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2025 Steve King Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ Package: [email protected] License: MIT Repository: https://github.com/sindresorhus/xdg-basedir -------------------------------------------------------------------------------- MIT License Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================================================ Package: [email protected] License: ISC Repository: https://github.com/eemeli/yaml -------------------------------------------------------------------------------- Copyright Eemeli Aro <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ================================================================================ */
- tsconfig.json (797 bytes)
{ "compilerOptions": { // Environment setup & latest features "lib": ["ESNext"], "target": "ESNext", "module": "ESNext", "moduleDetection": "force", "jsx": "react-jsx", "allowJs": true, // Bundler mode "moduleResolution": "bundler", "allowImportingTsExtensions": true, "verbatimModuleSyntax": true, "noEmit": true, "esModuleInterop": true, "types": ["node"], // Best practices "strict": true, "skipLibCheck": true, "noFallthroughCasesInSwitch": true, "noUncheckedIndexedAccess": true, // Some stricter flags (disabled by default) "noUnusedLocals": false, "noUnusedParameters": false, "noPropertyAccessFromIndexSignature": false }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] } - vitest.config.ts (478 bytes)
import { defineConfig } from 'vitest/config'; // Windows CI runners are much slower at process spawns and filesystem work (git clones, // symlinks, temp dirs), so tests that finish in ~1s on Linux regularly brush the default // 5s limit there. Give them more headroom instead of flaking. const isWindows = process.platform === 'win32'; export default defineConfig({ test: { testTimeout: isWindows ? 30_000 : 5_000, hookTimeout: isWindows ? 60_000 : 10_000, }, });