Context7 Platform -- Up-to-date docs for AI agents
CTX7-3190: Remove deprecated Skill Hub commands from ctx7 CLI (#3425)
Enes Gules94cdfb125167
diff --git a/.changeset/remove-skill-commands.md b/.changeset/remove-skill-commands.mdnew file mode 100644index 00000000..27dd2532--- /dev/null+++ b/.changeset/remove-skill-commands.md@@ -0,0 +1,5 @@+---+"ctx7": minor+---++Remove the deprecated `skills` and `generate` commands from `ctx7`; `ctx7 setup` still installs the find-docs and context7-mcp skills.diff --git a/docs/clients/cli.mdx b/docs/clients/cli.mdxindex 179da4db..53255c5f 100644--- a/docs/clients/cli.mdx+++ b/docs/clients/cli.mdx@@ -173,7 +173,7 @@ CONTEXT7_API_KEY=ctx7op-... ctx7 setup --mcp --yes \--codex```-The CLI checks `/api/auth/mcp` before writing configuration. It either configures anonymous access or writes `Authorization: Bearer <personal-key>`. When authentication is enabled and no key was provided, interactive setup requests the key with masked input. Use `--api-key` or `CONTEXT7_API_KEY` for non-interactive automation. On-premise setup uses Streamable HTTP and bundled rule/skill content, so the target does not need to serve Context7 Cloud skill endpoints.+The CLI checks `/api/auth/mcp` before writing configuration. It either configures anonymous access or writes `Authorization: Bearer <personal-key>`. When authentication is enabled and no key was provided, interactive setup requests the key with masked input. Use `--api-key` or `CONTEXT7_API_KEY` for non-interactive automation. On-premise setup uses Streamable HTTP and bundled rule/skill content.When `--base-url` targets a custom deployment, setup skips the npm update check and telemetry and does not fetch rules or skills from GitHub or Context7 Cloud. After the CLI package is installed, the only network request made by setup is to the configured deployment. In a restricted environment, mirror `ctx7` and its dependencies in an internal npm registry and run the installed `ctx7` binary instead of `npx ctx7@latest`.diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex e1a19f13..7c4beec5 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -22,7 +22,6 @@"test:watch": "vitest"},"dependencies": {- "@inquirer/core": "^12.0.3","@inquirer/prompts": "^8.7.2","boxen": "^9.0.0","commander": "^15.0.0",diff --git a/packages/cli/src/__tests__/command-auth-wiring.test.ts b/packages/cli/src/__tests__/command-auth-wiring.test.tsindex b9ea2228..3b54c09b 100644--- a/packages/cli/src/__tests__/command-auth-wiring.test.ts+++ b/packages/cli/src/__tests__/command-auth-wiring.test.ts@@ -12,28 +12,14 @@ vi.mock("../utils/auth.js", () => ({const mockResolveLibrary = vi.fn();const mockGetLibraryContext = vi.fn();-const mockSuggestSkills = vi.fn();vi.mock("../utils/api.js", () => ({resolveLibrary: (...args: unknown[]) => mockResolveLibrary(...args),getLibraryContext: (...args: unknown[]) => mockGetLibraryContext(...args),- suggestSkills: (...args: unknown[]) => mockSuggestSkills(...args),getBaseUrl: () => "https://test.context7.com",- listProjectSkills: vi.fn(),- searchSkills: vi.fn(),- downloadSkill: vi.fn(),- getSkill: vi.fn(),- getSkillQuota: vi.fn(),- getSkillQuestions: vi.fn(),- generateSkillStructured: vi.fn(),- searchLibraries: vi.fn(),}));vi.mock("../utils/tracking.js", () => ({ trackEvent: vi.fn() }));-vi.mock("../utils/deps.js", () => ({- detectProjectDependencies: () => ["react"],-}));-const mockSpinner = {start: vi.fn().mockReturnThis(),stop: vi.fn().mockReturnThis(),@@ -45,7 +31,6 @@ const mockSpinner = {vi.mock("ora", () => ({ default: () => mockSpinner }));import { registerDocsCommands } from "../commands/docs.js";-import { registerSkillCommands } from "../commands/skill.js";const REFRESHED = "refreshed-token";@@ -92,15 +77,6 @@ describe("commands pass a refreshed token to the API", () => {REFRESHED);});-- test("ctx7 skills suggest", async () => {- mockSuggestSkills.mockResolvedValue({ skills: [] });-- await run(registerSkillCommands, "skills", "suggest");-- expect(mockGetValidAccessToken).toHaveBeenCalled();- expect(mockSuggestSkills).toHaveBeenCalledWith(["react"], REFRESHED);- });});describe("commands stay anonymous when no token is available", () => {diff --git a/packages/cli/src/__tests__/github.test.ts b/packages/cli/src/__tests__/github.test.tsdeleted file mode 100644index d6417881..00000000--- a/packages/cli/src/__tests__/github.test.ts+++ /dev/null@@ -1,166 +0,0 @@-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";--const execFileSync = vi.hoisted(() => vi.fn());--vi.mock("node:child_process", () => ({ execFileSync }));--import { downloadSkillFromGitHub, listSkillsFromGitHub } from "../utils/github.js";--const SKILL = {- name: "context7-mcp",- description: "desc",- project: "/upstash/context7",- url: "https://raw.githubusercontent.com/upstash/context7/refs/heads/master/plugins/codex/context7/skills/context7-mcp/SKILL.md",-};--beforeEach(() => {- // resetAllMocks, not clearAllMocks: the latter keeps implementations, so a- // mockImplementation set by one test would leak into the next.- vi.resetAllMocks();- vi.stubEnv("GITHUB_TOKEN", undefined);- vi.stubEnv("GH_TOKEN", undefined);- vi.stubGlobal(- "fetch",- vi- .fn()- .mockResolvedValueOnce({- ok: true,- json: () => Promise.resolve({ default_branch: "main" }),- })- .mockResolvedValueOnce({- ok: true,- json: () => Promise.resolve({ sha: "tree-sha", tree: [], truncated: false }),- })- );-});--afterEach(() => {- vi.unstubAllGlobals();- vi.unstubAllEnvs();-});--describe("GitHub authentication", () => {- test("reads the GitHub CLI token without invoking a shell", async () => {- execFileSync.mockReturnValue("cli-token\n");-- const result = await listSkillsFromGitHub("upstash/context7");-- // No shell string and no `shell` option: the whole point of #2918.- expect(execFileSync).toHaveBeenCalledWith("gh", ["auth", "token"], {- encoding: "utf8",- stdio: ["pipe", "pipe", "ignore"],- });- expect(result).toEqual({ status: "ok", skills: [] });- expect(vi.mocked(fetch).mock.calls[0][1]).toMatchObject({- headers: expect.objectContaining({ Authorization: "token cli-token" }),- });- });-- test("prefers an environment token over invoking the GitHub CLI", async () => {- vi.stubEnv("GITHUB_TOKEN", "env-token");-- const result = await listSkillsFromGitHub("upstash/context7");-- expect(execFileSync).not.toHaveBeenCalled();- expect(result).toEqual({ status: "ok", skills: [] });- expect(vi.mocked(fetch).mock.calls[0][1]).toMatchObject({- headers: expect.objectContaining({ Authorization: "token env-token" }),- });- });-- test("falls back to GH_TOKEN when GITHUB_TOKEN is unset", async () => {- vi.stubEnv("GH_TOKEN", "gh-env-token");-- const result = await listSkillsFromGitHub("upstash/context7");-- expect(execFileSync).not.toHaveBeenCalled();- expect(result).toEqual({ status: "ok", skills: [] });- expect(vi.mocked(fetch).mock.calls[0][1]).toMatchObject({- headers: expect.objectContaining({ Authorization: "token gh-env-token" }),- });- });-- test("continues without authentication when the GitHub CLI is unavailable", async () => {- execFileSync.mockImplementation(() => {- throw Object.assign(new Error("spawnSync gh ENOENT"), { code: "ENOENT" });- });-- const result = await listSkillsFromGitHub("upstash/context7");-- // A missing or unresolvable gh degrades to unauthenticated requests, it does not throw.- expect(result).toEqual({ status: "ok", skills: [] });- const headers = vi.mocked(fetch).mock.calls[0][1]?.headers as Record<string, string>;- expect(headers).not.toHaveProperty("Authorization");- });-});--describe("downloadSkillFromGitHub", () => {- test("downloads every file in the skill directory when the tree API works", async () => {- vi.stubGlobal(- "fetch",- vi.fn((url: string) => {- if (url.includes("api.github.com")) {- return Promise.resolve({- ok: true,- json: () =>- Promise.resolve({- sha: "s",- truncated: false,- tree: [- { type: "tree", path: "plugins/codex/context7/skills/context7-mcp" },- {- type: "blob",- path: "plugins/codex/context7/skills/context7-mcp/SKILL.md",- },- {- type: "blob",- path: "plugins/codex/context7/skills/context7-mcp/references/guide.md",- },- ],- }),- });- }- return Promise.resolve({ ok: true, text: () => Promise.resolve(`raw:${url}`) });- })- );-- const result = await downloadSkillFromGitHub(SKILL);-- expect(result.error).toBeUndefined();- expect(result.files.map((f) => f.path).sort()).toEqual(["SKILL.md", "references/guide.md"]);- });-- test("falls back to the single SKILL.md when the tree API is unreachable (#2936)", async () => {- vi.stubGlobal(- "fetch",- vi.fn((url: string) => {- if (url.includes("api.github.com")) {- return Promise.reject(new TypeError("fetch failed"));- }- return Promise.resolve({ ok: true, text: () => Promise.resolve("# Context7 skill") });- })- );-- const result = await downloadSkillFromGitHub(SKILL);-- expect(result.error).toBeUndefined();- expect(result.files).toEqual([{ path: "SKILL.md", content: "# Context7 skill" }]);- });-- test("surfaces the tree error when both the tree API and the direct fetch fail", async () => {- vi.stubGlobal(- "fetch",- vi.fn((url: string) => {- if (url.includes("api.github.com")) {- return Promise.reject(new TypeError("fetch failed"));- }- return Promise.resolve({ ok: false, status: 404 });- })- );-- const result = await downloadSkillFromGitHub(SKILL);-- expect(result.files).toEqual([]);- expect(result.error).toBe("fetch failed");- });-});diff --git a/packages/cli/src/__tests__/installer.test.ts b/packages/cli/src/__tests__/installer.test.tsindex daf79d67..5ed66499 100644--- a/packages/cli/src/__tests__/installer.test.ts+++ b/packages/cli/src/__tests__/installer.test.ts@@ -1,9 +1,9 @@import { afterEach, beforeEach, describe, expect, test } from "vitest";-import { mkdir, readFile, writeFile, rm, access } from "fs/promises";+import { mkdir, readFile, rm, access } from "fs/promises";import { join } from "path";import { tmpdir } from "os";-import { installSkillFiles, symlinkSkill } from "../utils/installer.js";+import { installSkillFiles } from "../utils/installer.js";import { isSafeSkillName, assertSkillNameInRoot } from "../utils/skill-name.js";let tempDir: string;@@ -125,35 +125,3 @@ describe("installSkillFiles", () => {).rejects.toThrow(/outside/);});});--describe("symlinkSkill", () => {- test("creates symlink under skills root for safe name", async () => {- const skillsRoot = join(tempDir, "linked");- await mkdir(skillsRoot, { recursive: true });-- const source = join(tempDir, "source");- await mkdir(source, { recursive: true });- await writeFile(join(source, "marker"), "ok");-- await symlinkSkill("good", source, skillsRoot);-- const linkedMarker = await readFile(join(skillsRoot, "good", "marker"), "utf8");- expect(linkedMarker).toBe("ok");- });-- test("does not rm parent when skill name is '..'", async () => {- const skillsRoot = join(tempDir, ".cursor", "skills");- await mkdir(skillsRoot, { recursive: true });-- const sentinel = join(tempDir, ".cursor", "keep.txt");- await writeFile(sentinel, "sentinel");-- const source = join(tempDir, "source");- await mkdir(source, { recursive: true });-- await expect(symlinkSkill("..", source, skillsRoot)).rejects.toThrow();-- expect(await exists(sentinel)).toBe(true);- expect(await exists(join(tempDir, ".cursor"))).toBe(true);- });-});diff --git a/packages/cli/src/__tests__/skill-list.test.ts b/packages/cli/src/__tests__/skill-list.test.tsdeleted file mode 100644index c622141a..00000000--- a/packages/cli/src/__tests__/skill-list.test.ts+++ /dev/null@@ -1,75 +0,0 @@-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";-import { Command } from "commander";-import { mkdir, rm, realpath } from "fs/promises";-import { join } from "path";-import { tmpdir } from "os";--const trackEvent = vi.fn();-let logOutput: string[];--vi.mock("../utils/tracking.js", () => ({- trackEvent: (...args: unknown[]) => trackEvent(...args),-}));--import { registerSkillCommands } from "../commands/skill.js";--let tempDir: string;-let originalCwd: string;--async function runCommand(...args: string[]): Promise<void> {- const program = new Command();- program.exitOverride();- registerSkillCommands(program);- await program.parseAsync(["node", "test", ...args]);-}--beforeEach(async () => {- vi.clearAllMocks();- logOutput = [];- vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => {- logOutput.push(args.join(" "));- });- vi.spyOn(console, "error").mockImplementation(() => {});- originalCwd = process.cwd();- const rawTempDir = join(tmpdir(), `ctx7-skills-list-${Date.now()}`);- await mkdir(rawTempDir, { recursive: true });- tempDir = await realpath(rawTempDir);- process.chdir(tempDir);-});--afterEach(async () => {- process.chdir(originalCwd);- await rm(tempDir, { recursive: true, force: true });- vi.restoreAllMocks();-});--describe("skills list command", () => {- test("outputs installed skills as JSON", async () => {- await mkdir(join(tempDir, ".agents", "skills", "find-docs"), { recursive: true });- await mkdir(join(tempDir, ".cursor", "skills", "cursor-helper"), { recursive: true });-- await runCommand("skills", "list", "--json");-- expect(JSON.parse(logOutput.join("\n"))).toEqual({- skills: [- {- name: "find-docs",- path: join(tempDir, ".agents", "skills", "find-docs"),- source: "universal",- },- {- name: "cursor-helper",- path: join(tempDir, ".cursor", "skills", "cursor-helper"),- source: "cursor",- },- ],- });- expect(trackEvent).toHaveBeenCalledWith("command", { name: "list" });- });-- test("outputs an empty JSON list when no skills are installed", async () => {- await runCommand("skills", "list", "--json");-- expect(JSON.parse(logOutput.join("\n"))).toEqual({ skills: [] });- });-});diff --git a/packages/cli/src/__tests__/update-check.test.ts b/packages/cli/src/__tests__/update-check.test.tsindex 4f18b62b..f7c3052a 100644--- a/packages/cli/src/__tests__/update-check.test.ts+++ b/packages/cli/src/__tests__/update-check.test.ts@@ -284,6 +284,6 @@ describe("update notifications", () => {expect(shouldSkipUpdateNotifier(["node", "ctx7", "--base-url=https://context7.internal"])).toBe(true);- expect(shouldSkipUpdateNotifier(["node", "ctx7", "skills", "list"])).toBe(false);+ expect(shouldSkipUpdateNotifier(["node", "ctx7", "docs", "/a/b", "q"])).toBe(false);});});diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.tsdeleted file mode 100644index 9e60f0a5..00000000--- a/packages/cli/src/commands/generate.ts+++ /dev/null@@ -1,561 +0,0 @@-import { Command } from "commander";-import pc from "picocolors";-import ora from "ora";-import { mkdir, writeFile, readFile, unlink } from "fs/promises";-import { join } from "path";-import { homedir } from "os";-import { spawn } from "child_process";-import { input, select } from "@inquirer/prompts";--import {- searchLibraries,- getSkillQuestions,- generateSkillStructured,- getSkillQuota,-} from "../utils/api.js";-import { getValidAccessToken } from "../utils/auth.js";-import { performLogin } from "./auth.js";-import { log } from "../utils/logger.js";-import { promptForInstallTargets, getTargetDirs } from "../utils/ide.js";-import selectOrInput from "../utils/selectOrInput.js";-import { checkboxWithHover, terminalLink } from "../utils/prompts.js";-import { trackEvent } from "../utils/tracking.js";-import { getPreviewsDir } from "../utils/storage-paths.js";-import type {- GenerateOptions,- LibrarySearchResult,- SkillAnswer,- StructuredGenerateInput,- GenerateStreamEvent,- ToolResultSnippet,-} from "../types.js";--interface QueryLogEntry {- query: string;- libraryId?: string;- results: ToolResultSnippet[];-}--// TODO(deprecate-skills-phase-2): Remove this deprecated Skill Hub generation-// subcommand after legacy `ctx7 skills generate` support is dropped.-export function registerGenerateCommand(skillCommand: Command): void {- skillCommand- .command("generate")- .alias("gen")- .alias("g")- .option("-o, --output <dir>", "Output directory (default: current directory)")- .option("--all", "Generate for all detected IDEs")- .option("--global", "Generate in global skills directory")- .option("--claude", "Claude Code (.claude/skills/)")- .option("--cursor", "Cursor (.cursor/skills/)")- .option("--universal", "Universal (.agents/skills/)")- .option("--antigravity", "Antigravity (.agent/skills/)")- .description("Generate a skill for a library using AI")- .action(async (options: GenerateOptions) => {- await generateCommand(options);- });-}--async function generateCommand(options: GenerateOptions): Promise<void> {- trackEvent("command", { name: "generate" });- log.blank();-- let accessToken = await getValidAccessToken({ recoverExpiredSession: false });- if (!accessToken) {- log.info("Authentication required. Logging in...");- log.blank();- const token = await performLogin();- if (!token) {- log.error("Login failed. Please try again.");- return;- }- accessToken = token;- log.blank();- }-- const initSpinner = ora().start();- const quota = await getSkillQuota(accessToken);-- if (quota.error) {- initSpinner.fail(pc.red("Failed to initialize"));- return;- }-- if (quota.tier !== "unlimited" && quota.remaining < 1) {- initSpinner.fail(pc.red("Weekly skill generation limit reached"));- log.blank();- console.log(- ` You've used ${pc.bold(pc.white(quota.used.toString()))}/${pc.bold(pc.white(quota.limit.toString()))} skill generations this week.`- );- console.log(- ` Your quota resets on ${pc.yellow(new Date(quota.resetDate!).toLocaleDateString())}.`- );- log.blank();- if (quota.tier === "free") {- console.log(- ` ${pc.yellow("Tip:")} Upgrade to Pro for ${pc.bold("10")} generations per week.`- );- console.log(` Visit ${pc.green("https://context7.com/dashboard")} to upgrade.`);- }- return;- }-- initSpinner.stop();- initSpinner.clear();-- console.log(pc.bold("What should your agent become an expert at?\n"));- console.log(- pc.dim(- "Skills should encode best practices, constraints, and decision-making —\nnot step-by-step tutorials or one-off tasks.\n"- )- );- console.log(pc.yellow("Examples:"));- // prettier-ignore- {- console.log(pc.red(' ✕ "Deploy a Next.js app to Vercel"'));- console.log(pc.green(' ✓ "Best practices and constraints for deploying Next.js apps to Vercel"'));- log.blank();- console.log(pc.red(' ✕ "Use Tailwind for responsive design"'));- console.log(pc.green(' ✓ "Responsive layout decision-making with Tailwind CSS"'));- log.blank();- console.log(pc.red(' ✕ "Build OAuth with NextAuth"'));- console.log(pc.green(' ✓ "OAuth authentication patterns and pitfalls with NextAuth.js"'));- }- log.blank();-- let motivation: string;- try {- motivation = await input({- message: "Describe the expertise:",- });-- if (!motivation.trim()) {- log.warn("Expertise description is required");- return;- }- motivation = motivation.trim();- } catch {- log.warn("Generation cancelled");- return;- }-- log.blank();- console.log(- pc.dim(- "To generate this skill, we will read relevant documentation and examples\nfrom Context7.\n"- )- );- console.log(- pc.dim(- "These sources are used to:\n• extract best practices and constraints\n• compare patterns across official docs and examples\n• avoid outdated or incorrect guidance\n"- )- );- console.log(pc.dim("You can adjust which sources the skill is based on.\n"));-- const searchSpinner = ora("Finding relevant sources...").start();- const searchResult = await searchLibraries(motivation, accessToken);-- if (searchResult.error || !searchResult.results?.length) {- searchSpinner.fail(pc.red("No sources found"));- log.warn(searchResult.message || "Try a different description");- return;- }-- searchSpinner.succeed(pc.green(`Found ${searchResult.results.length} relevant sources`));- log.blank();-- if (searchResult.searchFilterApplied) {- log.warn(- "Your results only include libraries matching your teamspace's library filters. To adjust quality thresholds or blocked libraries, update your filters at https://context7.com/dashboard?tab=policies"- );- log.blank();- }-- let selectedLibraries: LibrarySearchResult[];- try {- const formatProjectId = (id: string) => {- return id.startsWith("/") ? id.slice(1) : id;- };-- const isGitHubRepo = (id: string): boolean => {- const cleanId = id.startsWith("/") ? id.slice(1) : id;- const parts = cleanId.split("/");- if (parts.length !== 2) return false;- const nonGitHubPrefixes = ["websites", "packages", "npm", "docs", "libraries", "llmstxt"];- return !nonGitHubPrefixes.includes(parts[0].toLowerCase());- };-- const libraries = searchResult.results.slice(0, 5);- const indexWidth = libraries.length.toString().length;- const maxNameLen = Math.max(...libraries.map((lib) => lib.title.length));-- const libraryChoices = libraries.map((lib, index) => {- const projectId = formatProjectId(lib.id);- const isGitHub = isGitHubRepo(lib.id);- const indexStr = pc.dim(`${(index + 1).toString().padStart(indexWidth)}.`);- const paddedName = lib.title.padEnd(maxNameLen);-- const libUrl = `https://context7.com${lib.id}`;- const libLink = terminalLink(lib.title, libUrl, pc.white);- const sourceUrl = isGitHub- ? `https://github.com/${projectId}`- : `https://context7.com${lib.id}`;- const repoLink = terminalLink(projectId, sourceUrl, pc.white);-- const starsLine =- lib.stars && isGitHub ? [`${pc.yellow("Stars:")} ${lib.stars.toLocaleString()}`] : [];-- const metadataLines = [- pc.dim("─".repeat(50)),- "",- `${pc.yellow("Library:")} ${libLink}`,- `${pc.yellow("Source:")} ${repoLink}`,- `${pc.yellow("Snippets:")} ${lib.totalSnippets.toLocaleString()}`,- ...starsLine,- `${pc.yellow("Description:")}`,- pc.white(lib.description || "No description"),- ];-- return {- name: `${indexStr} ${paddedName} ${pc.dim(`(${projectId})`)}`,- value: lib,- description: metadataLines.join("\n"),- };- });-- selectedLibraries = await checkboxWithHover(- {- message: "Select sources:",- choices: libraryChoices,- pageSize: 10,- loop: false,- },- { getName: (lib) => `${lib.title} (${formatProjectId(lib.id)})` }- );-- if (!selectedLibraries || selectedLibraries.length === 0) {- log.info("No sources selected. Try running the command again.");- return;- }- } catch {- log.warn("Generation cancelled");- return;- }-- log.blank();-- const questionsSpinner = ora(- "Preparing follow-up questions to clarify scope and constraints..."- ).start();- const librariesInput = selectedLibraries.map((lib) => ({ id: lib.id, name: lib.title }));- const questionsResult = await getSkillQuestions(librariesInput, motivation, accessToken);-- if (questionsResult.error || !questionsResult.questions?.length) {- questionsSpinner.fail(pc.red("Failed to generate questions"));- log.warn(questionsResult.message || "Please try again");- return;- }-- questionsSpinner.succeed(pc.green("Questions prepared"));- log.blank();-- const answers: SkillAnswer[] = [];- try {- for (let i = 0; i < questionsResult.questions.length; i++) {- const q = questionsResult.questions[i];- const questionNum = i + 1;- const totalQuestions = questionsResult.questions.length;-- const answer = await selectOrInput({- message: `${pc.dim(`[${questionNum}/${totalQuestions}]`)} ${q.question}`,- options: q.options,- recommendedIndex: q.recommendedIndex,- });-- answers.push({- question: q.question,- answer,- });-- const linesToClear = 3 + q.options.length;- process.stdout.write(`\x1b[${linesToClear}A\x1b[J`);-- const truncatedAnswer = answer.length > 50 ? answer.slice(0, 47) + "..." : answer;- console.log(`${pc.green("✓")} ${pc.dim(`[${questionNum}/${totalQuestions}]`)} ${q.question}`);- console.log(` ${pc.cyan(truncatedAnswer)}`);- log.blank();- }- } catch {- log.warn("Generation cancelled");- return;- }-- let generatedContent: string | null = null;- let skillName: string = "";- let feedback: string | undefined;- let previewFile: string | null = null;- let previewFileWritten = false;-- const cleanupPreviewFile = async () => {- if (previewFile) {- await unlink(previewFile).catch(() => {});- }- };-- const queryLog: QueryLogEntry[] = [];- let genSpinner: ReturnType<typeof ora> | null = null;-- const formatQueryLogText = (): string => {- if (queryLog.length === 0) return "";-- const lines: string[] = [];- const latestEntry = queryLog[queryLog.length - 1];-- lines.push("");-- for (const result of latestEntry.results.slice(0, 3)) {- const cleanContent = result.content.replace(/Source:\s*https?:\/\/[^\s]+/gi, "").trim();- if (cleanContent) {- lines.push(` ${pc.yellow("•")} ${pc.white(result.title)}`);- const maxLen = 400;- const content =- cleanContent.length > maxLen ? cleanContent.slice(0, maxLen - 3) + "..." : cleanContent;- const words = content.split(" ");- let currentLine = " ";- for (const word of words) {- if (currentLine.length + word.length > 84) {- lines.push(pc.dim(currentLine));- currentLine = " " + word + " ";- } else {- currentLine += word + " ";- }- }- if (currentLine.trim()) {- lines.push(pc.dim(currentLine));- }- lines.push("");- }- }-- return "\n" + lines.join("\n");- };-- let isGeneratingContent = false;- let initialStatus = "Reading selected Context7 sources to generate the skill...";-- const handleStreamEvent = (event: GenerateStreamEvent) => {- if (event.type === "progress") {- if (genSpinner) {- if (event.message.startsWith("Generating skill content...") && !isGeneratingContent) {- isGeneratingContent = true;- if (queryLog.length > 0) {- genSpinner.succeed(pc.green(`Read Context7 sources`));- } else {- genSpinner.succeed(pc.green(`Ready to generate`));- }- genSpinner = ora("Generating skill content...").start();- } else if (!isGeneratingContent) {- genSpinner.text = initialStatus + formatQueryLogText();- }- }- } else if (event.type === "tool_result") {- queryLog.push({- query: event.query,- libraryId: event.libraryId,- results: event.results,- });- if (genSpinner && !isGeneratingContent) {- genSpinner.text = genSpinner.text.split("\n")[0] + formatQueryLogText();- }- }- };-- while (true) {- const generateInput: StructuredGenerateInput = {- motivation,- libraries: librariesInput,- answers,- feedback,- previousContent: feedback && generatedContent ? generatedContent : undefined,- };-- queryLog.length = 0;- isGeneratingContent = false;- previewFileWritten = false;- initialStatus = feedback- ? "Regenerating skill with your feedback..."- : "Reading selected Context7 sources to generate the skill...";-- genSpinner = ora(initialStatus).start();-- const result = await generateSkillStructured(generateInput, handleStreamEvent, accessToken);-- if (result.error) {- genSpinner.fail(pc.red(`Error: ${result.error}`));- return;- }-- if (!result.content) {- genSpinner.fail(pc.red("No content generated"));- return;- }-- genSpinner.succeed(pc.green(`Generated skill for "${result.libraryName}"`));- generatedContent = result.content;- skillName = result.libraryName.toLowerCase().replace(/[^a-z0-9-]/g, "-");-- const contentLines = generatedContent.split("\n");- const previewLineCount = 20;- const hasMoreLines = contentLines.length > previewLineCount;- const previewContent = contentLines.slice(0, previewLineCount).join("\n");- const remainingLines = contentLines.length - previewLineCount;-- const showPreview = () => {- log.blank();- console.log(pc.dim("━".repeat(70)));- console.log(pc.bold(`Generated Skill: `) + pc.green(pc.bold(skillName)));- console.log(pc.dim("━".repeat(70)));- log.blank();- console.log(previewContent);- if (hasMoreLines) {- log.blank();- console.log(pc.dim(`... ${remainingLines} more lines`));- }- log.blank();- console.log(pc.dim("━".repeat(70)));- log.blank();- };-- const openInEditor = async () => {- const previewDir = getPreviewsDir();- await mkdir(previewDir, { recursive: true });- previewFile = join(previewDir, `${skillName}.md`);- if (!previewFileWritten) {- await writeFile(previewFile, generatedContent!, "utf-8");- previewFileWritten = true;- }- const editor = process.env.EDITOR || "open";- await new Promise<void>((resolve) => {- const child = spawn(editor, [previewFile!], {- stdio: "inherit",- });- child.on("close", () => resolve());- });- };-- const syncFromPreviewFile = async () => {- if (previewFile) {- generatedContent = await readFile(previewFile, "utf-8");- }- };-- showPreview();-- await new Promise((resolve) => setTimeout(resolve, 100));-- try {- let action: string;- while (true) {- const choices = [- { name: `${pc.green("✓")} Install skill (save locally)`, value: "install" },- { name: `${pc.blue("⤢")} Edit skill in editor`, value: "view" },- { name: `${pc.yellow("✎")} Request changes`, value: "feedback" },- { name: `${pc.red("✕")} Cancel`, value: "cancel" },- ];-- action = await select({- message: "What would you like to do?",- choices,- });-- if (action === "view") {- await openInEditor();- continue;- }- await syncFromPreviewFile();- break;- }-- if (action === "install") {- break;- } else if (action === "cancel") {- await cleanupPreviewFile();- log.warn("Generation cancelled");- return;- } else if (action === "feedback") {- trackEvent("gen_feedback");- feedback = await input({- message: "What changes would you like? (press Enter to skip)",- });-- if (!feedback.trim()) {- feedback = undefined;- }- log.blank();- }- } catch {- await cleanupPreviewFile();- log.warn("Generation cancelled");- return;- }- }-- const targets = await promptForInstallTargets(options);- if (!targets) {- log.warn("Generation cancelled");- return;- }-- const targetDirs = getTargetDirs(targets);-- const writeSpinner = ora("Writing skill files...").start();-- let permissionError = false;- const failedDirs: Set<string> = new Set();-- for (const targetDir of targetDirs) {- let finalDir = targetDir;- if (options.output && !targetDir.includes("/.config/") && !targetDir.startsWith(homedir())) {- finalDir = targetDir.replace(process.cwd(), options.output);- }- const skillDir = join(finalDir, skillName);- const skillPath = join(skillDir, "SKILL.md");-- try {- await mkdir(skillDir, { recursive: true });- await writeFile(skillPath, generatedContent!, "utf-8");- } catch (err) {- const error = err as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- permissionError = true;- failedDirs.add(skillDir);- } else {- log.warn(`Failed to write to ${skillPath}: ${error.message}`);- }- }- }-- if (permissionError) {- writeSpinner.fail(pc.red("Permission denied"));- log.blank();- console.log(pc.yellow("Fix permissions with:"));- for (const dir of failedDirs) {- const parentDir = join(dir, "..");- console.log(pc.dim(` sudo chown -R $(whoami) "${parentDir}"`));- }- log.blank();- return;- }-- writeSpinner.succeed(pc.green(`Created skill in ${targetDirs.length} location(s)`));- trackEvent("gen_install");-- log.blank();- console.log(pc.green("Skill saved successfully"));- for (const targetDir of targetDirs) {- console.log(pc.dim(` ${targetDir}/`) + pc.green(skillName));- }- log.blank();-- await cleanupPreviewFile();-}diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.tsindex e3436ae5..42ba06b5 100644--- a/packages/cli/src/commands/setup.ts+++ b/packages/cli/src/commands/setup.ts@@ -510,7 +510,6 @@ async function setupMcp(log.blank();trackEvent("setup", { agents, scope, authMode: auth.mode });- trackEvent("install", { skills: ["/upstash/context7/context7-mcp"], ides: agents });}async function setupCliAgent(@@ -596,7 +595,6 @@ async function setupCli(options: SetupOptions): Promise<void> {log.blank();trackEvent("setup", { mode: "cli" });- trackEvent("install", { skills: ["/upstash/context7/find-docs"], ides: agents });}async function setupCommand(options: SetupOptions): Promise<void> {diff --git a/packages/cli/src/commands/skill.ts b/packages/cli/src/commands/skill.tsdeleted file mode 100644index 66526eb6..00000000--- a/packages/cli/src/commands/skill.ts+++ /dev/null@@ -1,1025 +0,0 @@-import { Command } from "commander";-import pc from "picocolors";-import ora from "ora";-import { readdir, rm } from "fs/promises";-import { join } from "path";--import { parseSkillInput } from "../utils/parse-input.js";-import {- listProjectSkills,- searchSkills,- suggestSkills,- downloadSkill,- getSkill,-} from "../utils/api.js";-import { log } from "../utils/logger.js";-import {- promptForInstallTargets,- promptForSingleTarget,- getTargetDirs,- getTargetDirFromSelection,- getSelectedIdes,- hasExplicitIdeOption,-} from "../utils/ide.js";-import {- checkboxWithHover,- terminalLink,- formatPopularity,- formatTrust,- formatInstallRange,- getTrustLabel,-} from "../utils/prompts.js";-import { installSkillFiles, symlinkSkill } from "../utils/installer.js";-import { assertSkillNameInRoot } from "../utils/skill-name.js";-import { listSkillsFromGitHub, getSkillFromGitHub } from "../utils/github.js";-import { trackEvent } from "../utils/tracking.js";-import { registerGenerateCommand } from "./generate.js";-import type {- Skill,- SkillSearchResult,- AddOptions,- ListOptions,- RemoveOptions,- SuggestOptions,- InstallTargets,- Scope,-} from "../types.js";-import {- IDE_NAMES,- IDE_PATHS,- IDE_GLOBAL_PATHS,- UNIVERSAL_SKILLS_PATH,- UNIVERSAL_SKILLS_GLOBAL_PATH,- UNIVERSAL_AGENTS_LABEL,- VENDOR_SPECIFIC_AGENTS,-} from "../types.js";-import { homedir } from "os";-import { detectProjectDependencies } from "../utils/deps.js";-import { getValidAccessToken } from "../utils/auth.js";--const SKILL_HUB_DEPRECATION_WARNING =- "Warning: Skill commands are deprecated and will stop working in the next major release.";--// TODO(deprecate-skills-phase-2): Delete this Skill Hub command tree once the-// deprecated `ctx7 skills ...` compatibility window closes. Do not remove the-// setup-installed Context7 skills with it.-function warnSkillHubDeprecated(): void {- console.error(pc.yellow(SKILL_HUB_DEPRECATION_WARNING));- console.error("");-}--function logInstallSummary(- targets: InstallTargets,- targetDirs: string[],- skillNames: string[]-): void {- log.blank();- const hasUniversal = targets.ides.some((ide) => ide === "universal");- const vendorIdes = targets.ides.filter((ide) => ide !== "universal");-- let dirIndex = 0;- if (hasUniversal && dirIndex < targetDirs.length) {- log.plain(`${pc.bold("Universal")} ${pc.dim(targetDirs[dirIndex])}`);- for (const name of skillNames) {- log.itemAdd(name);- }- dirIndex++;- }-- for (const ide of vendorIdes) {- if (dirIndex >= targetDirs.length) break;- log.plain(`${pc.bold(IDE_NAMES[ide])} ${pc.dim(targetDirs[dirIndex])}`);- for (const name of skillNames) {- log.itemAdd(name);- }- dirIndex++;- }-- log.blank();-}--export function registerSkillCommands(program: Command): void {- const skill = program- .command("skills", { hidden: true })- .alias("skill")- .description("Manage AI coding skills")- .hook("preAction", () => {- warnSkillHubDeprecated();- });-- // Register generate subcommand- registerGenerateCommand(skill);-- skill- .command("install")- .alias("i")- .alias("add")- .argument("<repository>", "GitHub repository (/owner/repo)")- .argument("[skill]", "Specific skill name to install")- .option("--all", "Install all skills without prompting")- .option("--all-agents", "Install to all supported agent locations")- .option("-y, --yes", "Skip confirmation prompts")- .option("--global", "Install globally instead of current directory")- .option("--claude", "Claude Code (.claude/skills/)")- .option("--cursor", "Cursor (.cursor/skills/)")- .option("--universal", "Universal (.agents/skills/)")- .option("--antigravity", "Antigravity (.agent/skills/)")- .description("Install skills from a repository")- .action(async (project: string, skillName: string | undefined, options: AddOptions) => {- await installCommand(project, skillName, options);- });-- skill- .command("search")- .alias("s")- .argument("<keywords...>", "Search keywords")- .description("Search for skills across all indexed repositories")- .action(async (keywords: string[]) => {- await searchCommand(keywords.join(" "));- });-- skill- .command("list")- .alias("ls")- .option("--json", "Output as JSON")- .option("--global", "List global skills")- .option("--claude", "Claude Code (.claude/skills/)")- .option("--cursor", "Cursor (.cursor/skills/)")- .option("--universal", "Universal (.agents/skills/)")- .option("--antigravity", "Antigravity (.agent/skills/)")- .description("List installed skills")- .action(async (options: ListOptions) => {- await listCommand(options);- });-- skill- .command("remove")- .alias("rm")- .alias("delete")- .argument("<name>", "Skill name to remove")- .option("--global", "Remove from global skills")- .option("--claude", "Claude Code (.claude/skills/)")- .option("--cursor", "Cursor (.cursor/skills/)")- .option("--universal", "Universal (.agents/skills/)")- .option("--antigravity", "Antigravity (.agent/skills/)")- .description("Remove an installed skill")- .action(async (name: string, options: RemoveOptions) => {- await removeCommand(name, options);- });-- skill- .command("info")- .argument("<repository>", "GitHub repository (/owner/repo)")- .description("Show skills in a repository")- .action(async (project: string) => {- await infoCommand(project);- });-- skill- .command("suggest")- .option("--global", "Install globally instead of current directory")- .option("--claude", "Claude Code (.claude/skills/)")- .option("--cursor", "Cursor (.cursor/skills/)")- .option("--universal", "Universal (.agents/skills/)")- .option("--antigravity", "Antigravity (.agent/skills/)")- .description("Suggest skills based on your project dependencies")- .action(async (options: SuggestOptions) => {- await suggestCommand(options);- });-}--export function registerSkillAliases(program: Command): void {- program- .command("si", { hidden: true })- .argument("<repository>", "GitHub repository (/owner/repo)")- .argument("[skill]", "Specific skill name to install")- .option("--all", "Install all skills without prompting")- .option("--all-agents", "Install to all supported agent locations")- .option("-y, --yes", "Skip confirmation prompts")- .option("--global", "Install globally instead of current directory")- .option("--claude", "Claude Code (.claude/skills/)")- .option("--cursor", "Cursor (.cursor/skills/)")- .option("--universal", "Universal (.agents/skills/)")- .option("--antigravity", "Antigravity (.agent/skills/)")- .description("Install skills (alias for: skills install)")- .action(async (project: string, skillName: string | undefined, options: AddOptions) => {- warnSkillHubDeprecated();- await installCommand(project, skillName, options);- });-- program- .command("ss", { hidden: true })- .argument("<keywords...>", "Search keywords")- .description("Search for skills (alias for: skills search)")- .action(async (keywords: string[]) => {- warnSkillHubDeprecated();- await searchCommand(keywords.join(" "));- });-- program- .command("ssg", { hidden: true })- .option("--global", "Install globally instead of current directory")- .option("--claude", "Claude Code (.claude/skills/)")- .option("--cursor", "Cursor (.cursor/skills/)")- .option("--universal", "Universal (.agents/skills/)")- .option("--antigravity", "Antigravity (.agent/skills/)")- .description("Suggest skills (alias for: skills suggest)")- .action(async (options: SuggestOptions) => {- warnSkillHubDeprecated();- await suggestCommand(options);- });-}--async function installCommand(- input: string,- skillName: string | undefined,- options: AddOptions-): Promise<void> {- trackEvent("command", { name: "install" });- const parsed = parseSkillInput(input);- if (!parsed) {- log.error(`Invalid input format: ${input}`);- log.info(`Expected: /owner/repo or full GitHub URL`);- log.info(`Example: ctx7 skills install /anthropics/skills pdf`);- log.blank();- return;- }- const repo = `/${parsed.owner}/${parsed.repo}`;-- log.blank();- const spinner = ora(`Fetching skills from ${repo}...`).start();-- let selectedSkills: (Skill & { project: string })[];-- // When a specific skill name is provided, fetch only that skill- if (skillName) {- spinner.text = `Fetching skill: ${skillName}...`;- const skillData = await getSkill(repo, skillName);-- if (skillData.error || !skillData.name) {- if (skillData.error === "prompt_injection_detected") {- spinner.fail(pc.red(`Prompt injection detected in skill: ${skillName}`));- log.warn("This skill contains potentially malicious content and cannot be installed.");- return;- }-- spinner.text = `Fetching skill from GitHub: ${skillName}...`;- const ghResult = await getSkillFromGitHub(repo, skillName);- if (ghResult.status === "repo_not_found") {- spinner.fail(pc.red(`Repository not found: ${repo}`));- return;- }- if (ghResult.status !== "ok" || !ghResult.skill) {- spinner.fail(pc.red(`Skill not found: ${skillName}`));- return;- }-- spinner.succeed(`Found skill: ${skillName}`);- selectedSkills = [ghResult.skill];- } else {- spinner.succeed(`Found skill: ${skillName}`);- selectedSkills = [- {- name: skillData.name,- description: skillData.description,- url: skillData.url,- project: repo,- },- ];- }- } else {- // Fetch all skills when no specific names provided- let data = await listProjectSkills(repo);-- if ((data.error || !data.skills || data.skills.length === 0) && !data.blockedSkillsCount) {- spinner.text = `Fetching skills from GitHub...`;- const ghResult = await listSkillsFromGitHub(repo);- if (ghResult.status === "repo_not_found") {- spinner.fail(pc.red(`Repository not found: ${repo}`));- return;- }- if (ghResult.status === "ok" && ghResult.skills.length > 0) {- data = { project: repo, skills: ghResult.skills };- }- }-- if (data.error && (!data.skills || data.skills.length === 0)) {- spinner.fail(pc.red(`Error: ${data.message || data.error}`));- return;- }-- if (!data.skills || data.skills.length === 0) {- spinner.warn(pc.yellow(`No skills found in ${repo}`));- return;- }-- const skillsWithRepo = data.skills- .map((s) => ({ ...s, project: repo }))- .sort((a, b) => (b.installCount ?? 0) - (a.installCount ?? 0));-- spinner.succeed(`Found ${data.skills.length} skill(s)`);-- if (data.blockedSkillsCount && data.blockedSkillsCount > 0) {- log.blank();- log.error(- `${data.blockedSkillsCount} skill(s) blocked due to prompt injection and not shown.`- );- log.warn("Review other skills from this repository carefully before installing.");- }-- if (options.all || data.skills.length === 1) {- selectedSkills = skillsWithRepo;- } else {- const indexWidth = data.skills.length.toString().length;- const maxNameLen = Math.max(...data.skills.map((s) => s.name.length));- const popularityColWidth = 13;- const choices = skillsWithRepo.map((s, index) => {- const indexStr = pc.dim(`${(index + 1).toString().padStart(indexWidth)}.`);- const paddedName = s.name.padEnd(maxNameLen);- const popularity = formatPopularity(s.installCount) + " ".repeat(popularityColWidth - 4);- const trust = formatTrust(s.trustScore);-- const skillUrl = s.url || `https://github.com${s.project}`;- const skillLink = terminalLink(s.name, skillUrl, pc.white);- const repoLink = terminalLink(s.project, `https://github.com${s.project}`, pc.white);- const metadataLines = [- pc.dim("─".repeat(50)),- "",- `${pc.yellow("Skill:")} ${skillLink}`,- `${pc.yellow("Repo:")} ${repoLink}`,- `${pc.yellow("Installs:")} ${pc.white(formatInstallRange(s.installCount))}`,- `${pc.yellow("Trust:")} ${s.trustScore !== undefined && s.trustScore >= 0 ? pc.white(s.trustScore.toFixed(1)) : pc.dim("-")}`,- `${pc.yellow("Description:")}`,- pc.white(s.description || "No description"),- ];-- return {- name: `${indexStr} ${paddedName} ${popularity}${trust}`,- value: s,- description: metadataLines.join("\n"),- };- });-- log.blank();-- const checkboxPrefixWidth = 3;- const headerPad = " ".repeat(checkboxPrefixWidth + indexWidth + 1 + 1 + maxNameLen + 1);- const headerLine =- headerPad + pc.dim("Popularity".padEnd(popularityColWidth)) + pc.dim("Trust");-- try {- selectedSkills = await checkboxWithHover({- message: `Select skills to install:\n${headerLine}`,- choices,- pageSize: 15,- loop: false,- theme: {- style: {- message: (text: string, status: string) => {- if (status === "done") return pc.dim(text.split("\n")[0]);- return pc.bold(text);- },- },- },- });- } catch {- log.warn("Installation cancelled");- return;- }- }- }-- if (selectedSkills.length === 0) {- log.warn("No skills selected");- return;- }-- const targets = await promptForInstallTargets(options);- if (!targets) {- log.warn("Installation cancelled");- return;- }-- const targetDirs = getTargetDirs(targets);-- const installSpinner = ora("Installing skills...").start();-- let permissionError = false;- const failedDirs: Set<string> = new Set();- const installedSkills: string[] = [];-- for (const skill of selectedSkills) {- try {- installSpinner.text = `Downloading ${skill.name}...`;- const downloadData = await downloadSkill(skill.project, skill.name);-- if (downloadData.error) {- log.warn(`Failed to download ${skill.name}: ${downloadData.error}`);- continue;- }-- installSpinner.text = `Installing ${skill.name}...`;-- const [primaryDir, ...symlinkDirs] = targetDirs;-- try {- await installSkillFiles(skill.name, downloadData.files, primaryDir);- } catch (dirErr) {- const error = dirErr as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- permissionError = true;- failedDirs.add(primaryDir);- }- throw dirErr;- }-- const primarySkillDir = join(primaryDir, skill.name);- for (const targetDir of symlinkDirs) {- try {- await symlinkSkill(skill.name, primarySkillDir, targetDir);- } catch (dirErr) {- const error = dirErr as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- permissionError = true;- failedDirs.add(targetDir);- }- throw dirErr;- }- }-- installedSkills.push(`${skill.project}/${skill.name}`);- } catch (err) {- const error = err as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- continue;- }- const errMsg = err instanceof Error ? err.message : String(err);- log.warn(`Failed to install ${skill.name}: ${errMsg}`);- }- }-- if (permissionError) {- installSpinner.fail("Permission denied");- log.blank();- log.warn("Fix permissions with:");- for (const dir of failedDirs) {- const parentDir = join(dir, "..");- log.dim(` sudo chown -R $(whoami) "${parentDir}"`);- }- log.blank();- return;- }-- installSpinner.succeed(`Installed ${installedSkills.length} skill(s)`);- trackEvent("install", { skills: installedSkills, ides: targets.ides });-- const installedNames = selectedSkills.map((s) => s.name);- logInstallSummary(targets, targetDirs, installedNames);-}--async function searchCommand(query: string): Promise<void> {- trackEvent("command", { name: "search" });- log.blank();- const spinner = ora(`Searching for "${query}"...`).start();-- let data;- try {- data = await searchSkills(query);- } catch (err) {- spinner.fail(pc.red(`Error: ${err instanceof Error ? err.message : String(err)}`));- return;- }-- if (data.error) {- spinner.fail(pc.red(`Error: ${data.message || data.error}`));- return;- }-- if (!data.results || data.results.length === 0) {- spinner.warn(pc.yellow(`No skills found matching "${query}"`));- return;- }-- spinner.succeed(`Found ${data.results.length} skill(s)`);- trackEvent("search_query", { query, resultCount: data.results.length });- log.blank();-- const indexWidth = data.results.length.toString().length;- const nameWithRepo = (s: SkillSearchResult) => `${s.name} ${pc.dim(`(${s.project})`)}`;- const nameWithRepoLen = (s: SkillSearchResult) => `${s.name} (${s.project})`.length;- const maxNameLen = Math.max(...data.results.map(nameWithRepoLen));- const popularityColWidth = 13;- const choices = data.results.map((s, index) => {- const indexStr = pc.dim(`${(index + 1).toString().padStart(indexWidth)}.`);- const rawLen = nameWithRepoLen(s);- const displayName = nameWithRepo(s) + " ".repeat(maxNameLen - rawLen);- const popularity = formatPopularity(s.installCount) + " ".repeat(popularityColWidth - 4);- const trust = formatTrust(s.trustScore);-- const skillLink = terminalLink(s.name, s.url || `https://github.com${s.project}`, pc.white);- const repoLink = terminalLink(s.project, `https://github.com${s.project}`, pc.white);- const metadataLines = [- pc.dim("─".repeat(50)),- "",- `${pc.yellow("Skill:")} ${skillLink}`,- `${pc.yellow("Repo:")} ${repoLink}`,- `${pc.yellow("Installs:")} ${pc.white(formatInstallRange(s.installCount))}`,- `${pc.yellow("Trust:")} ${s.trustScore !== undefined && s.trustScore >= 0 ? pc.white(s.trustScore.toFixed(1)) : pc.dim("-")}`,- `${pc.yellow("Description:")}`,- pc.white(s.description || "No description"),- ];-- return {- name: `${indexStr} ${displayName} ${popularity}${trust}`,- value: s,- description: metadataLines.join("\n"),- };- });-- const checkboxPrefixWidth = 3; // "❯◯ " or " ◯ "- const headerPad = " ".repeat(checkboxPrefixWidth + indexWidth + 1 + 1 + maxNameLen + 1);- const headerLine = headerPad + pc.dim("Popularity".padEnd(popularityColWidth)) + pc.dim("Trust");-- let selectedSkills: SkillSearchResult[];- try {- selectedSkills = await checkboxWithHover({- message: `Select skills to install:\n${headerLine}`,- choices,- pageSize: 15,- loop: false,- theme: {- style: {- message: (text: string, status: string) => {- if (status === "done") return pc.dim(text.split("\n")[0]);- return pc.bold(text);- },- },- },- });- } catch {- log.warn("Installation cancelled");- return;- }-- const uniqueSkills = selectedSkills;-- if (uniqueSkills.length === 0) {- log.warn("No skills selected");- return;- }-- const targets = await promptForInstallTargets({});- if (!targets) {- log.warn("Installation cancelled");- return;- }-- const targetDirs = getTargetDirs(targets);-- const installSpinner = ora("Installing skills...").start();-- let permissionError = false;- const failedDirs: Set<string> = new Set();- const installedSkills: string[] = [];-- for (const skill of uniqueSkills) {- try {- installSpinner.text = `Downloading ${skill.name}...`;- const downloadData = await downloadSkill(skill.project, skill.name);-- if (downloadData.error) {- log.warn(`Failed to download ${skill.name}: ${downloadData.error}`);- continue;- }-- installSpinner.text = `Installing ${skill.name}...`;-- const [primaryDir, ...symlinkDirs] = targetDirs;-- try {- await installSkillFiles(skill.name, downloadData.files, primaryDir);- } catch (dirErr) {- const error = dirErr as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- permissionError = true;- failedDirs.add(primaryDir);- }- throw dirErr;- }-- const primarySkillDir = join(primaryDir, skill.name);- for (const targetDir of symlinkDirs) {- try {- await symlinkSkill(skill.name, primarySkillDir, targetDir);- } catch (dirErr) {- const error = dirErr as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- permissionError = true;- failedDirs.add(targetDir);- }- throw dirErr;- }- }-- installedSkills.push(`${skill.project}/${skill.name}`);- } catch (err) {- const error = err as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- continue;- }- const errMsg = err instanceof Error ? err.message : String(err);- log.warn(`Failed to install ${skill.name}: ${errMsg}`);- }- }-- if (permissionError) {- installSpinner.fail("Permission denied");- log.blank();- log.warn("Fix permissions with:");- for (const dir of failedDirs) {- const parentDir = join(dir, "..");- log.dim(` sudo chown -R $(whoami) "${parentDir}"`);- }- log.blank();- return;- }-- installSpinner.succeed(`Installed ${installedSkills.length} skill(s)`);- trackEvent("install", { skills: installedSkills, ides: targets.ides });-- const installedNames = uniqueSkills.map((s) => s.name);- logInstallSummary(targets, targetDirs, installedNames);-}--async function listCommand(options: ListOptions): Promise<void> {- trackEvent("command", { name: "list" });- const scope: Scope = options.global ? "global" : "project";- const baseDir = scope === "global" ? homedir() : process.cwd();-- const results: {- label: string;- displayPath: string;- dir: string;- source: string;- skills: string[];- }[] = [];-- // Helper to scan a skills directory- async function scanDir(dir: string): Promise<string[]> {- try {- const entries = await readdir(dir, { withFileTypes: true });- return entries.filter((e) => e.isDirectory() || e.isSymbolicLink()).map((e) => e.name);- } catch {- return [];- }- }-- if (hasExplicitIdeOption(options)) {- // Explicit flag mode — check the specific IDE paths- const ides = getSelectedIdes(options);- for (const ide of ides) {- const dir =- ide === "universal"- ? join(baseDir, scope === "global" ? UNIVERSAL_SKILLS_GLOBAL_PATH : UNIVERSAL_SKILLS_PATH)- : join(baseDir, (scope === "global" ? IDE_GLOBAL_PATHS : IDE_PATHS)[ide]);- const label = ide === "universal" ? UNIVERSAL_AGENTS_LABEL : IDE_NAMES[ide];- const skills = await scanDir(dir);- if (skills.length > 0) {- results.push({ label, displayPath: dir, dir, source: ide, skills });- }- }- } else {- // Default: check universal + vendor-specific- const universalPath = scope === "global" ? UNIVERSAL_SKILLS_GLOBAL_PATH : UNIVERSAL_SKILLS_PATH;- const universalDir = join(baseDir, universalPath);- const universalSkills = await scanDir(universalDir);- if (universalSkills.length > 0) {- results.push({- label: UNIVERSAL_AGENTS_LABEL,- displayPath: universalPath,- dir: universalDir,- source: "universal",- skills: universalSkills,- });- }-- for (const ide of VENDOR_SPECIFIC_AGENTS) {- const pathMap = scope === "global" ? IDE_GLOBAL_PATHS : IDE_PATHS;- const dir = join(baseDir, pathMap[ide]);- const skills = await scanDir(dir);- if (skills.length > 0) {- results.push({- label: IDE_NAMES[ide],- displayPath: pathMap[ide],- dir,- source: ide,- skills,- });- }- }- }-- if (options.json) {- const skills = results.flatMap((result) =>- result.skills.map((name) => ({- name,- path: join(result.dir, name),- source: result.source,- }))- );-- console.log(JSON.stringify({ skills }, null, 2));- return;- }-- if (results.length === 0) {- log.warn("No skills installed");- return;- }-- log.blank();-- for (const { label, displayPath, skills } of results) {- log.plain(`${pc.bold(label)} ${pc.dim(displayPath)}`);- for (const skill of skills) {- log.plain(` ${pc.green(skill)}`);- }- log.blank();- }-}--async function removeCommand(name: string, options: RemoveOptions): Promise<void> {- trackEvent("command", { name: "remove" });- const target = await promptForSingleTarget(options);- if (!target) {- log.warn("Cancelled");- return;- }-- const skillsDir = getTargetDirFromSelection(target.ide, target.scope);- let skillPath: string;- try {- skillPath = assertSkillNameInRoot(skillsDir, name);- } catch {- log.error(`Invalid skill name: ${name}`);- return;- }-- try {- await rm(skillPath, { recursive: true });- log.success(`Removed skill: ${name}`);- } catch (err) {- const error = err as NodeJS.ErrnoException;- if (error.code === "ENOENT") {- log.error(`Skill not found: ${name}`);- } else if (error.code === "EACCES" || error.code === "EPERM") {- log.error(`Permission denied. Try: sudo rm -rf "${skillPath}"`);- } else {- log.error(`Failed to remove skill: ${error.message}`);- }- }-}--async function infoCommand(input: string): Promise<void> {- trackEvent("command", { name: "info" });- const parsed = parseSkillInput(input);- if (!parsed) {- log.blank();- log.error(`Invalid input format: ${input}`);- log.info(`Expected: /owner/repo or full GitHub URL`);- log.blank();- return;- }- const repo = `/${parsed.owner}/${parsed.repo}`;-- log.blank();- const spinner = ora(`Fetching skills from ${repo}...`).start();-- const data = await listProjectSkills(repo);-- if (data.error) {- spinner.fail(pc.red(`Error: ${data.message || data.error}`));- return;- }-- if (!data.skills || data.skills.length === 0) {- spinner.warn(pc.yellow(`No skills found in ${repo}`));- return;- }-- spinner.succeed(`Found ${data.skills.length} skill(s)`);-- log.blank();- for (const skill of data.skills) {- log.item(skill.name);- log.dim(` ${skill.description || "No description"}`);- log.dim(` URL: ${skill.url}`);- log.blank();- }-- log.plain(- `${pc.bold("Quick commands:")}\n` +- ` Install all: ${pc.cyan(`ctx7 skills install ${repo} --all`)}\n` +- ` Install one: ${pc.cyan(`ctx7 skills install ${repo} ${data.skills[0]?.name}`)}\n`- );-}--async function suggestCommand(options: SuggestOptions): Promise<void> {- trackEvent("command", { name: "suggest" });- log.blank();-- // Step 1: Detect dependencies- const scanSpinner = ora("Scanning project dependencies...").start();- const deps = await detectProjectDependencies(process.cwd());-- if (deps.length === 0) {- scanSpinner.warn(pc.yellow("No dependencies detected"));- log.info(`Try ${pc.cyan("ctx7 skills search <keyword>")} to search manually`);- return;- }-- scanSpinner.succeed(`Found ${deps.length} dependencies`);-- // Step 2: Single API call to backend- // Resolve the token before the spinner starts: an expired session may prompt.- const accessToken = await getValidAccessToken();- const searchSpinner = ora("Finding matching skills...").start();-- let data;- try {- data = await suggestSkills(deps, accessToken);- } catch {- searchSpinner.fail(pc.red("Failed to connect to Context7"));- return;- }-- if (data.error) {- searchSpinner.fail(pc.red(`Error: ${data.message || data.error}`));- return;- }-- const skills = data.skills;-- if (skills.length === 0) {- searchSpinner.warn(pc.yellow("No matching skills found for your dependencies"));- return;- }-- searchSpinner.succeed(`Found ${skills.length} relevant skill(s)`);- trackEvent("suggest_results", { depCount: deps.length, skillCount: skills.length });- log.blank();-- const nameWithRepo = (s: SkillSearchResult) => `${s.name} ${pc.dim(`(${s.project})`)}`;- const nameWithRepoLen = (s: SkillSearchResult) => `${s.name} (${s.project})`.length;- const maxNameLen = Math.max(...skills.map(nameWithRepoLen));- const popularityColWidth = 13;- const trustColWidth = 8;- const maxMatchedLen = Math.max(...skills.map((s) => s.matchedDep.length));- const indexWidth = skills.length.toString().length;-- const choices = skills.map((s, index) => {- const indexStr = pc.dim(`${(index + 1).toString().padStart(indexWidth)}.`);- const rawLen = nameWithRepoLen(s);- const displayName = nameWithRepo(s) + " ".repeat(maxNameLen - rawLen);- const popularity = formatPopularity(s.installCount) + " ".repeat(popularityColWidth - 4);- const trustLabel = getTrustLabel(s.trustScore);- const trust = formatTrust(s.trustScore) + " ".repeat(trustColWidth - trustLabel.length);- const matched = pc.yellow(s.matchedDep.padEnd(maxMatchedLen));-- const skillLink = terminalLink(s.name, s.url || `https://github.com${s.project}`, pc.white);- const repoLink = terminalLink(s.project, `https://github.com${s.project}`, pc.white);- const metadataLines = [- pc.dim("─".repeat(50)),- "",- `${pc.yellow("Skill:")} ${skillLink}`,- `${pc.yellow("Repo:")} ${repoLink}`,- `${pc.yellow("Installs:")} ${pc.white(formatInstallRange(s.installCount))}`,- `${pc.yellow("Trust:")} ${s.trustScore !== undefined && s.trustScore >= 0 ? pc.white(s.trustScore.toFixed(1)) : pc.dim("-")}`,- `${pc.yellow("Relevant:")} ${pc.white(s.matchedDep)}`,- `${pc.yellow("Description:")}`,- pc.white(s.description || "No description"),- ];-- return {- name: `${indexStr} ${displayName} ${popularity}${trust}${matched}`,- value: s,- description: metadataLines.join("\n"),- };- });-- const checkboxPrefixWidth = 3; // "❯◯ " or " ◯ "- const headerPad = " ".repeat(checkboxPrefixWidth + indexWidth + 1 + 1 + maxNameLen + 1);- const headerLine =- headerPad +- pc.dim("Popularity".padEnd(popularityColWidth)) +- pc.dim("Trust".padEnd(trustColWidth)) +- pc.dim("Relevant");-- let selectedSkills: SkillSearchResult[];- try {- selectedSkills = await checkboxWithHover({- message: `Select skills to install:\n${headerLine}`,- choices,- pageSize: 15,- loop: false,- theme: {- style: {- message: (text: string, status: string) => {- if (status === "done") return pc.dim(text.split("\n")[0]);- return pc.bold(text);- },- },- },- });- } catch {- log.warn("Installation cancelled");- return;- }-- if (selectedSkills.length === 0) {- log.warn("No skills selected");- return;- }-- // Step 4: Install (same pattern as searchCommand)- const targets = await promptForInstallTargets(options);- if (!targets) {- log.warn("Installation cancelled");- return;- }-- const targetDirs = getTargetDirs(targets);- const installSpinner = ora("Installing skills...").start();-- let permissionError = false;- const failedDirs: Set<string> = new Set();- const installedSkills: string[] = [];-- for (const skill of selectedSkills) {- try {- installSpinner.text = `Downloading ${skill.name}...`;- const downloadData = await downloadSkill(skill.project, skill.name);-- if (downloadData.error) {- log.warn(`Failed to download ${skill.name}: ${downloadData.error}`);- continue;- }-- installSpinner.text = `Installing ${skill.name}...`;-- const [primaryDir, ...symlinkDirs] = targetDirs;-- try {- await installSkillFiles(skill.name, downloadData.files, primaryDir);- } catch (dirErr) {- const error = dirErr as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- permissionError = true;- failedDirs.add(primaryDir);- }- throw dirErr;- }-- const primarySkillDir = join(primaryDir, skill.name);- for (const targetDir of symlinkDirs) {- try {- await symlinkSkill(skill.name, primarySkillDir, targetDir);- } catch (dirErr) {- const error = dirErr as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- permissionError = true;- failedDirs.add(targetDir);- }- throw dirErr;- }- }-- installedSkills.push(`${skill.project}/${skill.name}`);- } catch (err) {- const error = err as NodeJS.ErrnoException;- if (error.code === "EACCES" || error.code === "EPERM") {- continue;- }- const errMsg = err instanceof Error ? err.message : String(err);- log.warn(`Failed to install ${skill.name}: ${errMsg}`);- }- }-- if (permissionError) {- installSpinner.fail("Permission denied");- log.blank();- log.warn("Fix permissions with:");- for (const dir of failedDirs) {- const parentDir = join(dir, "..");- log.dim(` sudo chown -R $(whoami) "${parentDir}"`);- }- log.blank();- return;- }-- installSpinner.succeed(`Installed ${installedSkills.length} skill(s)`);- trackEvent("suggest_install", { skills: installedSkills, ides: targets.ides });-- const installedNames = selectedSkills.map((s) => s.name);- logInstallSummary(targets, targetDirs, installedNames);-}diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 77604871..806a50bb 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -1,7 +1,6 @@import { Command } from "commander";import pc from "picocolors";import figlet from "figlet";-import { registerSkillCommands, registerSkillAliases } from "./commands/skill.js";import { registerAuthCommands } from "./commands/auth.js";import { registerSetupCommand } from "./commands/setup.js";import { registerRemoveCommand } from "./commands/remove.js";@@ -56,8 +55,6 @@ Examples:`);-registerSkillCommands(program);-registerSkillAliases(program);registerAuthCommands(program);registerSetupCommand(program);registerRemoveCommand(program);diff --git a/packages/cli/src/types.ts b/packages/cli/src/types.tsindex 0c74e099..1064dbf1 100644--- a/packages/cli/src/types.ts+++ b/packages/cli/src/types.ts@@ -3,48 +3,6 @@ export interface SkillFile {content: string;}-// TODO(deprecate-skills-phase-2): Remove Skill Hub response types when-// deprecated `ctx7 skills ...` commands are deleted. Keep setup skill directory-// types below.-export interface Skill {- name: string;- description: string;- url: string;- installCount?: number;- trustScore?: number;-}--export interface SkillSearchResult extends Skill {- project: string;-}--export interface ListSkillsResponse {- project: string;- skills: Skill[];- blockedSkillsCount?: number;- error?: string;- message?: string;-}--export interface SingleSkillResponse extends Skill {- project: string;- error?: string;- message?: string;-}--export interface SearchResponse {- results: SkillSearchResult[];- error?: string;- message?: string;-}--export interface DownloadResponse {- skill: Skill & { project: string };- files: SkillFile[];- error?: string;-}--// Library search typesexport interface LibrarySearchResult {id: string;title: string;@@ -65,162 +23,6 @@ export interface LibrarySearchResponse {message?: string;}-// Skill generation types-export interface SkillQuestion {- question: string;- options: string[];- recommendedIndex: number;-}--export interface SkillQuestionsResponse {- questions: SkillQuestion[];- error?: string;- message?: string;-}--export interface SkillAnswer {- question: string;- answer: string;-}--export interface LibraryInput {- id: string;- name: string;-}--export interface StructuredGenerateInput {- motivation: string;- libraries: LibraryInput[];- answers: SkillAnswer[];- feedback?: string;- previousContent?: string;-}--export interface ToolResultSnippet {- title: string;- content: string;-}--export interface ProgressEvent {- type: "progress";- message: string;-}--export interface ToolResultEvent {- type: "tool_result";- toolName: string;- query: string;- libraryId?: string;- results: ToolResultSnippet[];-}--export interface CompleteEvent {- type: "complete";- content: string;- libraryName: string;-}--export interface ErrorEvent {- type: "error";- message: string;-}--export type GenerateStreamEvent = ProgressEvent | ToolResultEvent | CompleteEvent | ErrorEvent;--export type IDE = "claude" | "cursor" | "antigravity" | "universal";--export type Scope = "project" | "global";--export interface IDEOptions {- allAgents?: boolean;- claude?: boolean;- cursor?: boolean;- universal?: boolean;- antigravity?: boolean;-}--export interface ScopeOptions {- global?: boolean;-}--export type AddOptions = IDEOptions & ScopeOptions & { all?: boolean; yes?: boolean };-export type SuggestOptions = IDEOptions & ScopeOptions;-export type ListOptions = IDEOptions & ScopeOptions & { json?: boolean };-export type RemoveOptions = IDEOptions & ScopeOptions;-export type GenerateOptions = IDEOptions &- ScopeOptions & {- output?: string;- all?: boolean;- };--export interface InstallTargets {- ides: IDE[];- scopes: Scope[];-}--export const IDE_PATHS: Record<IDE, string> = {- claude: ".claude/skills",- cursor: ".cursor/skills",- antigravity: ".agent/skills",- universal: ".agents/skills",-};--export const IDE_GLOBAL_PATHS: Record<IDE, string> = {- claude: ".claude/skills",- cursor: ".cursor/skills",- antigravity: ".agent/skills",- universal: ".agents/skills",-};--export const IDE_NAMES: Record<IDE, string> = {- claude: "Claude Code",- cursor: "Cursor",- antigravity: "Antigravity",- universal: "Universal",-};--// Universal .agents/skills standard-// These agents read from .agents/skills/ natively — one install covers all of them.-export const UNIVERSAL_SKILLS_PATH = ".agents/skills";-export const UNIVERSAL_SKILLS_GLOBAL_PATH = ".agents/skills";--// Display label for agents that read .agents/skills/ (includes agents beyond our IDE type)-export const UNIVERSAL_AGENTS_LABEL = "Amp, Codex, Gemini CLI, GitHub Copilot, OpenCode + more";--// Agents that still require their own vendor-specific skill directory.-export const VENDOR_SPECIFIC_AGENTS: IDE[] = ["claude", "cursor", "antigravity"];--export interface C7Config {- defaultIde: IDE;- defaultScope: "project" | "global";-}--export const DEFAULT_CONFIG: C7Config = {- defaultIde: "universal",- defaultScope: "project",-};--// Suggest endpoint types-export interface SuggestSkill extends SkillSearchResult {- matchedDep: string;-}--export interface SuggestResponse {- skills: SuggestSkill[];- error?: string;- message?: string;-}--export interface SkillQuotaResponse {- used: number;- limit: number;- remaining: number;- tier: "free" | "pro" | "unlimited";- resetDate: string | null;- message?: string;- error?: string;-}-export interface CodeExample {language: string;code: string;diff --git a/packages/cli/src/utils/api.ts b/packages/cli/src/utils/api.tsindex b5327bdd..9581a848 100644--- a/packages/cli/src/utils/api.ts+++ b/packages/cli/src/utils/api.ts@@ -1,17 +1,4 @@-import type {- ListSkillsResponse,- SingleSkillResponse,- SearchResponse,- SuggestResponse,- DownloadResponse,- LibrarySearchResponse,- SkillQuestionsResponse,- StructuredGenerateInput,- GenerateStreamEvent,- SkillQuotaResponse,- ContextResponse,-} from "../types.js";-import { downloadSkillFromGitHub, getSkillFromGitHub } from "./github.js";+import type { LibrarySearchResponse, ContextResponse } from "../types.js";import { VERSION } from "../constants.js";export const DEFAULT_CONTEXT7_BASE_URL = "https://context7.com";@@ -26,246 +13,6 @@ export function setBaseUrl(url: string): void {baseUrl = url;}-// TODO(deprecate-skills-phase-2): Remove the Skill Hub API helpers in this file-// when deprecated `ctx7 skills ...` commands are deleted.-export async function listProjectSkills(project: string): Promise<ListSkillsResponse> {- const params = new URLSearchParams({ project });- const response = await fetch(`${baseUrl}/api/v2/skills?${params}`);- return (await response.json()) as ListSkillsResponse;-}--export async function getSkill(project: string, skillName: string): Promise<SingleSkillResponse> {- const params = new URLSearchParams({ project, skill: skillName });- const response = await fetch(`${baseUrl}/api/v2/skills?${params}`);- return (await response.json()) as SingleSkillResponse;-}--export async function searchSkills(query: string): Promise<SearchResponse> {- const params = new URLSearchParams({ query });- const response = await fetch(`${baseUrl}/api/v2/skills?${params}`);- return (await response.json()) as SearchResponse;-}--export async function suggestSkills(- dependencies: string[],- accessToken?: string-): Promise<SuggestResponse> {- const headers: Record<string, string> = { "Content-Type": "application/json" };- if (accessToken) {- headers["Authorization"] = `Bearer ${accessToken}`;- }- const response = await fetch(`${baseUrl}/api/v2/skills/suggest`, {- method: "POST",- headers,- body: JSON.stringify({ dependencies }),- });- return (await response.json()) as SuggestResponse;-}--export async function downloadSkill(project: string, skillName: string): Promise<DownloadResponse> {- const skillData = await getSkill(project, skillName);-- if (skillData.error) {- // handle private repo skills with env var- const ghResult = await getSkillFromGitHub(project, skillName);- if (ghResult.status !== "ok" || !ghResult.skill) {- return {- skill: { name: skillName, description: "", url: "", project },- files: [],- error: skillData.message || skillData.error,- };- }-- const { files, error } = await downloadSkillFromGitHub(ghResult.skill);- if (error) {- return { skill: ghResult.skill, files: [], error };- }- return { skill: ghResult.skill, files };- }-- const skill = {- name: skillData.name,- description: skillData.description,- url: skillData.url,- project: skillData.project,- };-- const { files, error } = await downloadSkillFromGitHub(skill);-- if (error) {- return { skill, files: [], error };- }-- return { skill, files };-}--export interface GenerateSkillResponse {- content: string;- libraryName: string;- error?: string;-}--export async function searchLibraries(- query: string,- accessToken?: string-): Promise<LibrarySearchResponse> {- const params = new URLSearchParams({ query });- const headers: Record<string, string> = {};- if (accessToken) {- headers["Authorization"] = `Bearer ${accessToken}`;- }- const response = await fetch(`${baseUrl}/api/v2/libs/search?${params}`, { headers });- return (await response.json()) as LibrarySearchResponse;-}--export async function getSkillQuota(accessToken: string): Promise<SkillQuotaResponse> {- const response = await fetch(`${baseUrl}/api/v2/skills/quota`, {- headers: { Authorization: `Bearer ${accessToken}` },- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- return {- used: 0,- limit: 0,- remaining: 0,- tier: "free",- resetDate: null,- error: (errorData as { message?: string }).message || `HTTP error ${response.status}`,- };- }-- return (await response.json()) as SkillQuotaResponse;-}--export async function getSkillQuestions(- libraries: Array<{ id: string; name: string }>,- motivation: string,- accessToken?: string-): Promise<SkillQuestionsResponse> {- const headers: Record<string, string> = { "Content-Type": "application/json" };- if (accessToken) {- headers["Authorization"] = `Bearer ${accessToken}`;- }-- const response = await fetch(`${baseUrl}/api/v2/skills/questions`, {- method: "POST",- headers,- body: JSON.stringify({ libraries, motivation }),- });-- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- return {- questions: [],- error: (errorData as { message?: string }).message || `HTTP error ${response.status}`,- };- }-- return (await response.json()) as SkillQuestionsResponse;-}--export async function generateSkillStructured(- input: StructuredGenerateInput,- onEvent?: (event: GenerateStreamEvent) => void,- accessToken?: string-): Promise<GenerateSkillResponse> {- const headers: Record<string, string> = { "Content-Type": "application/json" };- if (accessToken) {- headers["Authorization"] = `Bearer ${accessToken}`;- }-- const response = await fetch(`${baseUrl}/api/v2/skills/generate`, {- method: "POST",- headers,- body: JSON.stringify(input),- });-- const libraryName = input.libraries[0]?.name || "skill";- return handleGenerateResponse(response, libraryName, onEvent);-}--async function handleGenerateResponse(- response: Response,- libraryName: string,- onEvent?: (event: GenerateStreamEvent) => void-): Promise<GenerateSkillResponse> {- if (!response.ok) {- const errorData = await response.json().catch(() => ({}));- return {- content: "",- libraryName,- error: (errorData as { message?: string }).message || `HTTP error ${response.status}`,- };- }-- const reader = response.body?.getReader();- if (!reader) {- return { content: "", libraryName, error: "No response body" };- }-- const decoder = new TextDecoder();- let content = "";- let finalLibraryName = libraryName;- let error: string | undefined;- let buffer = ""; // Buffer for incomplete lines across chunks-- while (true) {- const { done, value } = await reader.read();- if (done) break;-- const chunk = decoder.decode(value, { stream: true });- buffer += chunk;-- // Split by newline but keep track of incomplete lines- const lines = buffer.split("\n");- // Keep the last element (may be incomplete) in the buffer- buffer = lines.pop() || "";-- for (const line of lines) {- const trimmedLine = line.trim();- if (!trimmedLine) continue;-- try {- const data = JSON.parse(trimmedLine) as GenerateStreamEvent;-- if (onEvent) {- onEvent(data);- }-- if (data.type === "complete") {- content = data.content || "";- finalLibraryName = data.libraryName || libraryName;- } else if (data.type === "error") {- error = data.message;- }- } catch {- // Ignore malformed JSON lines- }- }- }-- // Process any remaining data in the buffer- if (buffer.trim()) {- try {- const data = JSON.parse(buffer.trim()) as GenerateStreamEvent;- if (onEvent) {- onEvent(data);- }- if (data.type === "complete") {- content = data.content || "";- finalLibraryName = data.libraryName || libraryName;- } else if (data.type === "error") {- error = data.message;- }- } catch {- // Ignore malformed JSON- }- }-- return { content, libraryName: finalLibraryName, error };-}-function getAuthHeaders(accessToken?: string): Record<string, string> {const headers: Record<string, string> = {"X-Context7-Source": "cli",diff --git a/packages/cli/src/utils/deps.ts b/packages/cli/src/utils/deps.tsdeleted file mode 100644index 18d48e50..00000000--- a/packages/cli/src/utils/deps.ts+++ /dev/null@@ -1,102 +0,0 @@-import { readFile } from "fs/promises";-import { join } from "path";--async function readFileOrNull(path: string): Promise<string | null> {- try {- return await readFile(path, "utf-8");- } catch {- return null;- }-}--/** Basic client-side filter. The real SKIP_SET lives on the backend. */-function isSkippedLocally(name: string): boolean {- return name.startsWith("@types/");-}--async function parsePackageJson(cwd: string): Promise<string[]> {- const content = await readFileOrNull(join(cwd, "package.json"));- if (!content) return [];-- try {- const pkg = JSON.parse(content);- const names = new Set<string>();-- for (const key of Object.keys(pkg.dependencies || {})) {- if (!isSkippedLocally(key)) names.add(key);- }- for (const key of Object.keys(pkg.devDependencies || {})) {- if (!isSkippedLocally(key)) names.add(key);- }-- return [...names];- } catch {- return [];- }-}--async function parseRequirementsTxt(cwd: string): Promise<string[]> {- const content = await readFileOrNull(join(cwd, "requirements.txt"));- if (!content) return [];-- const deps: string[] = [];- for (const line of content.split("\n")) {- const trimmed = line.trim();- if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith("-")) continue;- const name = trimmed.split(/[=<>!~;@\s\[]/)[0].trim();- if (name && !isSkippedLocally(name)) {- deps.push(name);- }- }- return deps;-}--async function parsePyprojectToml(cwd: string): Promise<string[]> {- const content = await readFileOrNull(join(cwd, "pyproject.toml"));- if (!content) return [];-- const deps: string[] = [];- const seen = new Set<string>();-- const projectDepsMatch = content.match(/\[project\]\s[\s\S]*?dependencies\s*=\s*\[([\s\S]*?)\]/);- if (projectDepsMatch) {- const entries = projectDepsMatch[1].match(/"([^"]+)"/g) || [];- for (const entry of entries) {- const name = entry- .replace(/"/g, "")- .split(/[=<>!~;@\s\[]/)[0]- .trim();- if (name && !isSkippedLocally(name) && !seen.has(name)) {- seen.add(name);- deps.push(name);- }- }- }-- const poetryMatch = content.match(/\[tool\.poetry\.dependencies\]([\s\S]*?)(?:\n\[|$)/);- if (poetryMatch) {- const lines = poetryMatch[1].split("\n");- for (const line of lines) {- const match = line.match(/^(\S+)\s*=/);- if (match) {- const name = match[1].trim();- if (name && !isSkippedLocally(name) && name !== "python" && !seen.has(name)) {- seen.add(name);- deps.push(name);- }- }- }- }-- return deps;-}--export async function detectProjectDependencies(cwd: string): Promise<string[]> {- const results = await Promise.all([- parsePackageJson(cwd),- parseRequirementsTxt(cwd),- parsePyprojectToml(cwd),- ]);-- return [...new Set(results.flat())];-}diff --git a/packages/cli/src/utils/github.ts b/packages/cli/src/utils/github.tsdeleted file mode 100644index 8242f9a7..00000000--- a/packages/cli/src/utils/github.ts+++ /dev/null@@ -1,354 +0,0 @@-import { execFileSync } from "node:child_process";-import type { SkillFile, Skill } from "../types.js";-import { isSafeSkillName } from "./skill-name.js";--const GITHUB_API = "https://api.github.com";-const GITHUB_RAW = "https://raw.githubusercontent.com";--interface GitHubTreeItem {- path: string;- mode: string;- type: "blob" | "tree";- sha: string;- size?: number;- url: string;-}--interface GitHubTreeResponse {- sha: string;- url: string;- tree: GitHubTreeItem[];- truncated: boolean;-}--function parseGitHubUrl(url: string): {- owner: string;- repo: string;- branch: string;- path: string;-} | null {- try {- const urlObj = new URL(url);- const parts = urlObj.pathname.split("/").filter(Boolean);-- // Handle raw.githubusercontent.com URLs- // Format: https://raw.githubusercontent.com/owner/repo/refs/heads/branch/path/SKILL.md- if (urlObj.hostname === "raw.githubusercontent.com") {- if (parts.length < 5) return null;-- const owner = parts[0];- const repo = parts[1];-- // Handle refs/heads/branch format- if (parts[2] === "refs" && parts[3] === "heads") {- const branch = parts[4];- // Get directory path (exclude the filename like SKILL.md)- const pathParts = parts.slice(5);- // Remove the last part if it looks like a file (has extension)- if (pathParts.length > 0 && pathParts[pathParts.length - 1].includes(".")) {- pathParts.pop();- }- const path = pathParts.join("/");- return { owner, repo, branch, path };- }-- // Handle direct branch format: owner/repo/branch/path- const branch = parts[2];- const pathParts = parts.slice(3);- if (pathParts.length > 0 && pathParts[pathParts.length - 1].includes(".")) {- pathParts.pop();- }- const path = pathParts.join("/");- return { owner, repo, branch, path };- }-- // Handle github.com tree URLs- // Format: https://github.com/owner/repo/tree/branch/path- if (urlObj.hostname === "github.com") {- if (parts.length < 4 || parts[2] !== "tree") return null;-- const owner = parts[0];- const repo = parts[1];- const branch = parts[3];- const path = parts.slice(4).join("/");-- return { owner, repo, branch, path };- }-- return null;- } catch {- return null;- }-}--function getGitHubToken(): string | undefined {- const envToken = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;- if (envToken) return envToken;- try {- // Deliberately shell-free: execSync would wrap this in `cmd.exe /d /s /c` on Windows,- // which EDR tooling reports as suspicious Node behavior (#2918). Do not add `shell`- // to make a .cmd/.bat `gh` shim resolve; that reintroduces the flagged process for- // everyone. Such shims are rare (mainstream Windows installs ship gh.exe) and only- // cost the fallback to unauthenticated requests.- return execFileSync("gh", ["auth", "token"], {- encoding: "utf8",- stdio: ["pipe", "pipe", "ignore"],- }).trim();- } catch {- return undefined;- }-}--function parseSkillFrontmatter(content: string): { name: string; description: string } | null {- const frontmatterMatch = content.match(/^---\s*\n([\s\S]*?)\n---/);- if (!frontmatterMatch) return null;-- const frontmatter = frontmatterMatch[1];-- const nameMatch = frontmatter.match(/^name:\s*(.+)$/m);- if (!nameMatch) return null;- const name = nameMatch[1].trim().replace(/^["']|["']$/g, "");- if (!isSafeSkillName(name)) return null;-- let description = "";- const multiLineMatch = frontmatter.match(/^description:\s*([|>])-?\s*$/m);-- if (multiLineMatch) {- const descLineIndex = frontmatter.indexOf("description:");- const lines = frontmatter.slice(descLineIndex).split("\n").slice(1);- const indentedLines: string[] = [];- for (const line of lines) {- if (line.trim() === "") {- indentedLines.push("");- continue;- }- if (/^\s+/.test(line)) {- indentedLines.push(line);- } else {- break;- }- }- const firstNonEmpty = indentedLines.find((l) => l.trim().length > 0);- const indent = firstNonEmpty?.match(/^(\s+)/)?.[1].length ?? 0;- description = indentedLines- .map((line) => line.slice(indent))- .join(" ")- .replace(/\s+/g, " ")- .trim();- } else {- const singleMatch = frontmatter.match(/^description:\s*(.+)$/m);- if (singleMatch) {- const value = singleMatch[1].trim();- if (!["|", ">", "|-", ">-"].includes(value)) {- description = value.replace(/^["']|["']$/g, "");- }- }- }-- if (!description) return null;- return { name, description };-}--function getGitHubHeaders(): Record<string, string> {- const ghToken = getGitHubToken();- return {- Accept: "application/vnd.github.v3+json",- "User-Agent": "context7-cli",- ...(ghToken && { Authorization: `token ${ghToken}` }),- };-}--async function extractGitHubError(response: Response): Promise<string> {- let detail = `HTTP ${response.status}`;- try {- const body = (await response.json()) as { message?: string };- if (body.message) detail += `: ${body.message}`;- } catch {}- return detail;-}--async function fetchRepoTree(- owner: string,- repo: string,- branch: string,- headers: Record<string, string>-): Promise<GitHubTreeResponse | { error: string }> {- const treeUrl = `${GITHUB_API}/repos/${owner}/${repo}/git/trees/${branch}?recursive=1`;- const response = await fetch(treeUrl, { headers });- if (!response.ok) return { error: await extractGitHubError(response) };- return (await response.json()) as GitHubTreeResponse;-}--async function fetchDefaultBranch(- owner: string,- repo: string,- headers: Record<string, string>-): Promise<{ branch: string } | { error: string; status: number }> {- const response = await fetch(`${GITHUB_API}/repos/${owner}/${repo}`, { headers });- if (!response.ok) return { error: await extractGitHubError(response), status: response.status };- const data = (await response.json()) as { default_branch: string };- return { branch: data.default_branch };-}--type GitHubSkillsResult =- | { status: "ok"; skills: (Skill & { project: string })[] }- | { status: "repo_not_found" }- | { status: "error"; error: string };--// TODO(deprecate-skills-phase-2): Remove direct GitHub Skill Hub fallback when-// deprecated `ctx7 skills install/info` commands are deleted.-export async function listSkillsFromGitHub(project: string): Promise<GitHubSkillsResult> {- try {- const parts = project.split("/").filter(Boolean);- if (parts.length < 2) return { status: "error", error: "Invalid project format" };- const [owner, repo] = parts;-- const headers = getGitHubHeaders();- const branchResult = await fetchDefaultBranch(owner, repo, headers);- if ("error" in branchResult) {- if (branchResult.status === 404) return { status: "repo_not_found" };- return { status: "error", error: branchResult.error };- }-- const treeData = await fetchRepoTree(owner, repo, branchResult.branch, headers);- if ("error" in treeData) return { status: "error", error: treeData.error };-- const skillMdFiles = treeData.tree.filter(- (item) => item.type === "blob" && item.path.toLowerCase().endsWith("skill.md")- );-- const skills: (Skill & { project: string })[] = [];- for (const item of skillMdFiles) {- const rawUrl = `${GITHUB_RAW}/${owner}/${repo}/${branchResult.branch}/${item.path}`;- const response = await fetch(rawUrl, { headers });- if (!response.ok) continue;-- const content = await response.text();- const meta = parseSkillFrontmatter(content);- if (!meta) continue;-- const skillDir = item.path.split("/").slice(0, -1).join("/");- skills.push({- name: meta.name,- description: meta.description,- url: `https://github.com/${owner}/${repo}/tree/${branchResult.branch}/${skillDir}`,- project,- });- }-- return { status: "ok", skills };- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- return { status: "error", error: message };- }-}--export async function getSkillFromGitHub(- project: string,- skillName: string-): Promise<GitHubSkillsResult & { skill?: Skill & { project: string } }> {- const result = await listSkillsFromGitHub(project);- if (result.status !== "ok") return result;- const skill = result.skills.find((s) => s.name.toLowerCase() === skillName.toLowerCase());- return { ...result, skill };-}--async function downloadSkillTree(- owner: string,- repo: string,- branch: string,- skillPath: string,- ghHeaders: Record<string, string>-): Promise<{ files: SkillFile[]; error?: string }> {- const treeData = await fetchRepoTree(owner, repo, branch, ghHeaders);- if ("error" in treeData) {- const hint =- !ghHeaders["Authorization"] && /403|429|rate/.test(treeData.error)- ? " — run `gh auth login` or set the GITHUB_TOKEN env var to increase rate limits"- : "";- return { files: [], error: `GitHub API error: ${treeData.error}${hint}` };- }-- const skillFiles = treeData.tree.filter(- (item) => item.type === "blob" && item.path.startsWith(skillPath + "/")- );-- if (skillFiles.length === 0) {- return { files: [], error: `No files found in ${skillPath}` };- }-- const files: SkillFile[] = [];- for (const item of skillFiles) {- const rawUrl = `${GITHUB_RAW}/${owner}/${repo}/${branch}/${item.path}`;- const fileResponse = await fetch(rawUrl, { headers: ghHeaders });-- if (!fileResponse.ok) {- console.warn(`Failed to fetch ${item.path}: ${fileResponse.status}`);- continue;- }-- const content = await fileResponse.text();- const relativePath = item.path.slice(skillPath.length + 1);-- // Reject paths that attempt directory traversal- if (relativePath.includes("..")) {- console.warn(`Skipping file with unsafe path: ${item.path}`);- continue;- }-- files.push({- path: relativePath,- content,- });- }-- return { files };-}--async function downloadSingleSkillFile(- skillUrl: string,- ghHeaders: Record<string, string>-): Promise<SkillFile[] | null> {- let fileName: string;- try {- const url = new URL(skillUrl);- const last = url.pathname.split("/").filter(Boolean).pop();- if (url.hostname !== "raw.githubusercontent.com" || !last || !last.includes(".")) {- return null;- }- fileName = last;- } catch {- return null;- }-- const response = await fetch(skillUrl, { headers: ghHeaders });- if (!response.ok) return null;- const content = await response.text();- return [{ path: fileName, content }];-}--export async function downloadSkillFromGitHub(- skill: Skill & { project: string }-): Promise<{ files: SkillFile[]; error?: string }> {- const parsed = parseGitHubUrl(skill.url);- if (!parsed) {- return { files: [], error: `Invalid GitHub URL: ${skill.url}` };- }-- const { owner, repo, branch, path: skillPath } = parsed;- const ghHeaders = getGitHubHeaders();-- let treeError: string | undefined;- try {- const result = await downloadSkillTree(owner, repo, branch, skillPath, ghHeaders);- if (result.files.length > 0) return { files: result.files };- treeError = result.error;- } catch (err) {- treeError = err instanceof Error ? err.message : String(err);- }-- const single = await downloadSingleSkillFile(skill.url, ghHeaders).catch(() => null);- if (single) return { files: single };-- return { files: [], error: treeError ?? `No files found in ${skillPath}` };-}diff --git a/packages/cli/src/utils/ide.ts b/packages/cli/src/utils/ide.tsdeleted file mode 100644index ce0e5185..00000000--- a/packages/cli/src/utils/ide.ts+++ /dev/null@@ -1,289 +0,0 @@-import pc from "picocolors";-import { select, confirm } from "@inquirer/prompts";-import { access } from "fs/promises";-import { join, dirname } from "path";-import { homedir } from "os";--import { log } from "./logger.js";-import { checkboxWithHover } from "./prompts.js";-import type {- IDE,- IDEOptions,- Scope,- AddOptions,- ListOptions,- RemoveOptions,- InstallTargets,-} from "../types.js";-import {- IDE_PATHS,- IDE_GLOBAL_PATHS,- IDE_NAMES,- UNIVERSAL_SKILLS_PATH,- UNIVERSAL_SKILLS_GLOBAL_PATH,- UNIVERSAL_AGENTS_LABEL,- VENDOR_SPECIFIC_AGENTS,- DEFAULT_CONFIG,-} from "../types.js";--export function getSelectedIdes(options: IDEOptions): IDE[] {- if (options.allAgents) {- return ["universal", ...VENDOR_SPECIFIC_AGENTS];- }-- const ides: IDE[] = [];- if (options.claude) ides.push("claude");- if (options.cursor) ides.push("cursor");- if (options.universal) ides.push("universal");- if (options.antigravity) ides.push("antigravity");- return ides;-}--export function hasExplicitIdeOption(options: IDEOptions): boolean {- return !!(- options.allAgents ||- options.claude ||- options.cursor ||- options.universal ||- options.antigravity- );-}--/** Detect vendor-specific agents whose parent directory exists. */-async function detectVendorSpecificAgents(scope: Scope): Promise<IDE[]> {- const baseDir = scope === "global" ? homedir() : process.cwd();- const pathMap = scope === "global" ? IDE_GLOBAL_PATHS : IDE_PATHS;- const detected: IDE[] = [];-- for (const ide of VENDOR_SPECIFIC_AGENTS) {- const parentDir = dirname(pathMap[ide]);- try {- await access(join(baseDir, parentDir));- detected.push(ide);- } catch {}- }-- return detected;-}--export function getUniversalDir(scope: Scope): string {- if (scope === "global") {- return join(homedir(), UNIVERSAL_SKILLS_GLOBAL_PATH);- }- return join(process.cwd(), UNIVERSAL_SKILLS_PATH);-}--export async function promptForInstallTargets(- options: AddOptions,- forceUniversal = true-): Promise<InstallTargets | null> {- if (hasExplicitIdeOption(options)) {- const ides = getSelectedIdes(options);- const scope: Scope = options.global ? "global" : "project";- return {- ides: ides.length > 0 ? ides : [DEFAULT_CONFIG.defaultIde],- scopes: [scope],- };- }-- const scope: Scope = options.global ? "global" : "project";- const baseDir = scope === "global" ? homedir() : process.cwd();- const pathMap = scope === "global" ? IDE_GLOBAL_PATHS : IDE_PATHS;- const universalPath = scope === "global" ? UNIVERSAL_SKILLS_GLOBAL_PATH : UNIVERSAL_SKILLS_PATH;-- // Detect universal (.agents/) and vendor-specific agent directories- const detectedVendor = await detectVendorSpecificAgents(scope);- let hasUniversalDir = false;- try {- await access(join(baseDir, dirname(universalPath)));- hasUniversalDir = true;- } catch {}-- const detectedIdes: IDE[] = [- ...(hasUniversalDir ? (["universal"] as IDE[]) : []),- ...detectedVendor,- ];-- if (detectedIdes.length > 0) {- // Detected — just confirm- const pathLines: string[] = [];- if (hasUniversalDir) {- pathLines.push(join(baseDir, universalPath));- }- for (const ide of detectedVendor) {- pathLines.push(join(baseDir, pathMap[ide]));- }-- log.blank();-- let confirmed: boolean;- if (options.yes) {- confirmed = true;- } else {- try {- confirmed = await confirm({- message: `Install to detected location(s)?\n${pc.dim(pathLines.join("\n"))}`,- default: true,- });- } catch {- return null;- }- }-- if (!confirmed) {- log.warn("Installation cancelled");- return null;- }-- return { ides: detectedIdes, scopes: [scope] };- }-- // Nothing detected — show checkbox to pick- const universalLabel = `Universal \u2014 ${UNIVERSAL_AGENTS_LABEL} ${pc.dim(`(${universalPath})`)}`;- const choices: { name: string; value: IDE; checked: boolean }[] = [- {- name: `${IDE_NAMES["claude"]} ${pc.dim(`(${pathMap["claude"]})`)}`,- value: "claude" as IDE,- checked: false,- },- { name: universalLabel, value: "universal", checked: false },- ];-- for (const ide of VENDOR_SPECIFIC_AGENTS.filter((ide) => ide !== "claude")) {- choices.push({- name: `${IDE_NAMES[ide]} ${pc.dim(`(${pathMap[ide]})`)}`,- value: ide,- checked: false,- });- }-- log.blank();-- let selectedIdes: IDE[];- try {- selectedIdes = await checkboxWithHover(- {- message: `Which agents do you want to install to?\n${pc.dim(` ${baseDir}`)}`,- choices,- loop: false,- theme: {- style: {- highlight: (text: string) => pc.green(text),- message: (text: string, status: string) => {- if (status === "done") return text.split("\n")[0];- return pc.bold(text);- },- },- },- },- { getName: (ide: IDE) => IDE_NAMES[ide] }- );- } catch {- return null;- }-- const ides: IDE[] = forceUniversal- ? ["universal", ...selectedIdes.filter((ide) => ide !== "universal")]- : selectedIdes;-- return { ides, scopes: [scope] };-}--export async function promptForSingleTarget(- options: ListOptions | RemoveOptions-): Promise<{ ide: IDE; scope: Scope } | null> {- if (hasExplicitIdeOption(options)) {- const ides = getSelectedIdes(options);- const ide = ides[0] || DEFAULT_CONFIG.defaultIde;- const scope: Scope = options.global ? "global" : "project";- return { ide, scope };- }-- log.blank();-- const universalLabel = `Universal ${pc.dim(`(${UNIVERSAL_SKILLS_PATH})`)}`;- const choices: { name: string; value: IDE }[] = [- { name: `${IDE_NAMES["claude"]} ${pc.dim(`(${IDE_PATHS["claude"]})`)}`, value: "claude" },- { name: universalLabel, value: "universal" },- ];-- for (const ide of VENDOR_SPECIFIC_AGENTS.filter((ide) => ide !== "claude")) {- choices.push({- name: `${IDE_NAMES[ide]} ${pc.dim(`(${IDE_PATHS[ide]})`)}`,- value: ide,- });- }-- let selectedIde: IDE;- try {- selectedIde = await select({- message: "Which location?",- choices,- default: DEFAULT_CONFIG.defaultIde,- loop: false,- theme: { style: { highlight: (text: string) => pc.green(text) } },- });- } catch {- return null;- }-- let selectedScope: Scope;- if (options.global !== undefined) {- selectedScope = options.global ? "global" : "project";- } else {- try {- selectedScope = await select({- message: "Which scope?",- choices: [- {- name: `Project ${pc.dim("(current directory)")}`,- value: "project" as Scope,- },- {- name: `Global ${pc.dim("(home directory)")}`,- value: "global" as Scope,- },- ],- default: DEFAULT_CONFIG.defaultScope,- loop: false,- theme: { style: { highlight: (text: string) => pc.green(text) } },- });- } catch {- return null;- }- }-- return { ide: selectedIde, scope: selectedScope };-}--export function getTargetDirs(targets: InstallTargets): string[] {- const hasUniversal = targets.ides.some((ide) => ide === "universal");- const dirs: string[] = [];-- for (const scope of targets.scopes) {- const baseDir = scope === "global" ? homedir() : process.cwd();-- if (hasUniversal) {- const uniPath = scope === "global" ? UNIVERSAL_SKILLS_GLOBAL_PATH : UNIVERSAL_SKILLS_PATH;- dirs.push(join(baseDir, uniPath));- }-- for (const ide of targets.ides) {- if (ide === "universal") continue;- const pathMap = scope === "global" ? IDE_GLOBAL_PATHS : IDE_PATHS;- dirs.push(join(baseDir, pathMap[ide]));- }- }-- return dirs;-}--export function getTargetDirFromSelection(ide: IDE, scope: Scope): string {- if (ide === "universal") {- return getUniversalDir(scope);- }- if (scope === "global") {- return join(homedir(), IDE_GLOBAL_PATHS[ide]);- }- return join(process.cwd(), IDE_PATHS[ide]);-}diff --git a/packages/cli/src/utils/installer.ts b/packages/cli/src/utils/installer.tsindex 83837b87..f3bf8824 100644--- a/packages/cli/src/utils/installer.ts+++ b/packages/cli/src/utils/installer.ts@@ -1,4 +1,4 @@-import { mkdir, writeFile, rm, symlink, lstat } from "fs/promises";+import { mkdir, writeFile } from "fs/promises";import { resolve, dirname } from "path";import type { SkillFile } from "../types.js";@@ -29,21 +29,3 @@ export async function installSkillFiles(await writeFile(filePath, file.content);}}--export async function symlinkSkill(- skillName: string,- sourcePath: string,- skillsRoot: string-): Promise<void> {- const targetPath = assertSkillNameInRoot(skillsRoot, skillName);-- try {- const stats = await lstat(targetPath);- if (stats.isSymbolicLink() || stats.isDirectory()) {- await rm(targetPath, { recursive: true });- }- } catch {}-- await mkdir(skillsRoot, { recursive: true });- await symlink(sourcePath, targetPath);-}diff --git a/packages/cli/src/utils/parse-input.ts b/packages/cli/src/utils/parse-input.tsdeleted file mode 100644index 942b6915..00000000--- a/packages/cli/src/utils/parse-input.ts+++ /dev/null@@ -1,25 +0,0 @@-export interface ParsedSkillInput {- type: "repo" | "url";- owner: string;- repo: string;- branch?: string;- path?: string;-}--export function parseSkillInput(input: string): ParsedSkillInput | null {- const urlMatch = input.match(- /(?:https?:\/\/)?github\.com\/([^\/]+)\/([^\/]+)\/tree\/([^\/]+)\/(.+)/- );- if (urlMatch) {- const [, owner, repo, branch, path] = urlMatch;- return { type: "url", owner, repo, branch, path };- }-- const shortMatch = input.match(/^\/?([^\/]+)\/([^\/]+)$/);- if (shortMatch) {- const [, owner, repo] = shortMatch;- return { type: "repo", owner, repo };- }-- return null;-}diff --git a/packages/cli/src/utils/selectOrInput.ts b/packages/cli/src/utils/selectOrInput.tsdeleted file mode 100644index 78fb6301..00000000--- a/packages/cli/src/utils/selectOrInput.ts+++ /dev/null@@ -1,111 +0,0 @@-import {- createPrompt,- useState,- useKeypress,- usePrefix,- isEnterKey,- isUpKey,- isDownKey,-} from "@inquirer/core";-import type { KeypressEvent } from "@inquirer/core";-import pc from "picocolors";--export interface SelectOrInputConfig {- message: string;- options: string[];- recommendedIndex?: number;-}--function reorderOptions(options: string[], recommendedIndex: number): string[] {- if (recommendedIndex === 0) return options;- const reordered = [options[recommendedIndex]];- for (let i = 0; i < options.length; i++) {- if (i !== recommendedIndex) reordered.push(options[i]);- }- return reordered;-}--const selectOrInput: (config: SelectOrInputConfig) => Promise<string> = createPrompt<- string,- SelectOrInputConfig->((config, done): string => {- const { message, options: rawOptions, recommendedIndex = 0 } = config;- const options = reorderOptions(rawOptions, recommendedIndex);- const [cursor, setCursor] = useState(0);- const [inputValue, setInputValue] = useState("");-- const prefix = usePrefix({});-- useKeypress((key: KeypressEvent, rl) => {- if (isUpKey(key)) {- setCursor(Math.max(0, cursor - 1));- return;- }-- if (isDownKey(key)) {- setCursor(Math.min(options.length, cursor + 1));- return;- }-- if (isEnterKey(key)) {- if (cursor === options.length) {- const finalValue = inputValue.trim();- done(finalValue || options[0]);- } else {- done(options[cursor]);- }- return;- }-- // Text input handling (only when on custom input line)- if (cursor === options.length && key.name !== "return") {- if ((key.name === "w" && key.ctrl) || key.name === "backspace") {- if (key.name === "w" && key.ctrl) {- const words = inputValue.trimEnd().split(/\s+/);- if (words.length > 0) {- words.pop();- setInputValue(- words.join(" ") + (inputValue.endsWith(" ") && words.length > 0 ? " " : "")- );- }- } else {- setInputValue(inputValue.slice(0, -1));- }- } else if (key.name === "u" && key.ctrl) {- setInputValue("");- } else if (key.name === "space") {- setInputValue(inputValue + " ");- } else if (key.name && key.name.length === 1 && !key.ctrl) {- setInputValue(inputValue + key.name);- }- } else if (rl.line) {- rl.line = "";- }- });-- let output = `${prefix} ${pc.bold(message)}\n\n`;-- options.forEach((opt: string, idx: number) => {- const isRecommended = idx === 0;- const isCursor = idx === cursor;- const number = pc.cyan(`${idx + 1}.`);- const text = isRecommended ? `${opt} ${pc.green("✓ Recommended")}` : opt;-- if (isCursor) {- output += pc.cyan(`❯ ${number} ${text}\n`);- } else {- output += ` ${number} ${text}\n`;- }- });-- const isCustomCursor = cursor === options.length;- if (isCustomCursor) {- output += pc.cyan(`❯ ${pc.yellow("✎")} ${inputValue || pc.dim("Type your own...")}`);- } else {- output += ` ${pc.yellow("✎")} ${pc.dim("Type your own...")}`;- }-- return output;-});--export default selectOrInput;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 387a2c3e..efc0e654 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -84,9 +84,6 @@ importers:packages/cli:dependencies:- '@inquirer/core':- specifier: ^12.0.3- version: 12.0.3(@types/[email protected])'@inquirer/prompts':specifier: ^8.7.2version: 8.7.2(@types/[email protected])