Context7 Platform -- Up-to-date docs for AI agents
feat(cli): add interactive skill generation wizard (#1572)
Fahreddin Özcan8ba484cdc8ef
diff --git a/.changeset/clever-pandas-glow.md b/.changeset/clever-pandas-glow.mdnew file mode 100644index 00000000..c099619e--- /dev/null+++ b/.changeset/clever-pandas-glow.md@@ -0,0 +1,5 @@+---+"ctx7": minor+---++Add AI-powered skill generation with `skills generate` command, including library search, clarifying questions, real-time query progress, feedback loop, and weekly quota management.diff --git a/package.json b/package.jsonindex 8e2f2acc..98d2321d 100644--- a/package.json+++ b/package.json@@ -53,5 +53,9 @@"prettier": "^3.6.2","typescript": "^5.8.2","typescript-eslint": "^8.28.0"+ },+ "dependencies": {+ "@inquirer/core": "^11.1.1",+ "@inquirer/type": "^4.0.3"}}diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 4b0a1294..b63939f1 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -23,12 +23,62 @@ ctx7 skills search pdf# Install a skillctx7 skills install /anthropics/skills pdf+# Generate a custom skill with AI+ctx7 skills generate+# List installed skillsctx7 skills list --claude```## Usage+### Generate skills++Generate custom skills tailored to your use case using AI. Requires authentication.++```bash+# Log in first+ctx7 login++# Generate a skill (interactive)+ctx7 skills generate++# Short aliases+ctx7 skills gen+ctx7 skills g++# Generate and install to a specific client+ctx7 skills generate --cursor+ctx7 skills generate --claude++# Generate globally+ctx7 skills generate --global+```++The generate flow:++1. Describe the expertise you want (e.g., "OAuth authentication with NextAuth.js")+2. Select relevant libraries from search results+3. Answer 3 clarifying questions to focus the skill+4. Review the generated skill, request changes if needed, then install++Weekly generation limits apply: free accounts get 6 generations/week, Pro accounts get 10.++### Authentication++Log in to access skill generation and other authenticated features.++```bash+# Log in (opens browser for OAuth)+ctx7 login++# Check login status+ctx7 whoami++# Log out+ctx7 logout+```+### Install skillsInstall skills from a project repository to your AI coding assistant's skills directory.@@ -110,6 +160,8 @@ For faster usage, the CLI provides short aliases:```bashctx7 si /anthropics/skills pdf # skills installctx7 ss pdf # skills search+ctx7 skills gen # skills generate+ctx7 skills g # skills generate```## Learn Morediff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.tsnew file mode 100644index 00000000..5946297a--- /dev/null+++ b/packages/cli/src/commands/generate.ts@@ -0,0 +1,499 @@+import { Command } from "commander";+import pc from "picocolors";+import ora from "ora";+import { mkdir, writeFile } from "fs/promises";+import { join } from "path";+import { homedir } from "os";+import { input, select } from "@inquirer/prompts";++import {+ searchLibraries,+ getSkillQuestions,+ generateSkillStructured,+ getSkillQuota,+} from "../utils/api.js";+import { loadTokens, isTokenExpired } from "../utils/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 type {+ GenerateOptions,+ LibrarySearchResult,+ SkillAnswer,+ StructuredGenerateInput,+ GenerateStreamEvent,+ ToolResultSnippet,+} from "../types.js";++interface QueryLogEntry {+ query: string;+ libraryId?: string;+ results: ToolResultSnippet[];+}++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("--codex", "Codex (.codex/skills/)")+ .option("--opencode", "OpenCode (.opencode/skills/)")+ .option("--amp", "Amp (.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> {+ log.blank();++ // Check authentication+ const tokens = loadTokens();+ if (!tokens) {+ log.error("Authentication required. Please run 'ctx7 login' first.");+ return;+ }++ if (isTokenExpired(tokens)) {+ log.error("Session expired. Please run 'ctx7 login' to refresh.");+ return;+ }++ const accessToken = tokens.access_token;++ 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 teach agents best practices, design patterns, and domain expertise.\n")+ );+ console.log(pc.yellow("Examples:"));+ console.log(pc.dim(' "React component optimization and performance best practices"'));+ console.log(pc.dim(' "Responsive web design with Tailwind CSS"'));+ console.log(pc.dim(' "Writing effective landing page copy"'));+ console.log(pc.dim(' "Deploying Next.js apps to Vercel"'));+ console.log(pc.dim(' "OAuth authentication with NextAuth.js"\n'));++ 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;+ }++ const searchSpinner = ora("Finding relevant libraries...").start();+ const searchResult = await searchLibraries(motivation, accessToken);++ if (searchResult.error || !searchResult.results?.length) {+ searchSpinner.fail(pc.red("No libraries found"));+ log.warn(searchResult.message || "Try a different description");+ return;+ }++ searchSpinner.succeed(pc.green(`Found ${searchResult.results.length} relevant libraries`));+ 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 repoLink = isGitHub+ ? terminalLink(projectId, `https://github.com/${projectId}`, pc.white)+ : pc.white(projectId);++ 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 libraries:",+ choices: libraryChoices,+ pageSize: 10,+ loop: false,+ },+ { getName: (lib) => `${lib.title} (${formatProjectId(lib.id)})` }+ );++ if (!selectedLibraries || selectedLibraries.length === 0) {+ log.info("No libraries selected. Try running the command again.");+ return;+ }+ } catch {+ log.warn("Generation cancelled");+ return;+ }++ log.blank();++ const questionsSpinner = ora("Preparing questions...").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;++ const libraryNames = selectedLibraries.map((lib) => lib.title).join(", ");+ 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(pc.dim(`(${queryLog.length} ${queryLog.length === 1 ? "query" : "queries"})`));+ 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;++ 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(`Queried documentation`));+ } else {+ genSpinner.succeed(pc.green(`Ready to generate`));+ }+ genSpinner = ora("Generating skill content...").start();+ } else if (!isGeneratingContent) {+ genSpinner.text = event.message + 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;+ const initialStatus = feedback+ ? "Regenerating skill with your feedback..."+ : `Generating skill for "${libraryNames}"...`;++ 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 showFullContent = () => {+ 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(generatedContent);+ log.blank();+ console.log(pc.dim("━".repeat(70)));+ log.blank();+ };++ showPreview();++ await new Promise((resolve) => setTimeout(resolve, 100));++ try {+ let action: string;+ while (true) {+ const choices = [+ { name: `${pc.green("✓")} Install skill`, value: "install" },+ ...(hasMoreLines ? [{ name: `${pc.blue("⤢")} View full skill`, value: "expand" }] : []),+ { 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 === "expand") {+ showFullContent();+ continue;+ }+ break;+ }++ if (action === "install") {+ break;+ } else if (action === "cancel") {+ log.warn("Generation cancelled");+ return;+ } else if (action === "feedback") {+ feedback = await input({+ message: "What changes would you like? (press Enter to skip)",+ });++ if (!feedback.trim()) {+ feedback = undefined;+ }+ log.blank();+ }+ } catch {+ 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)`));++ log.blank();+ console.log(pc.green(pc.bold("Skill saved successfully")));+ for (const targetDir of targetDirs) {+ console.log(pc.dim(` ${targetDir}/`) + pc.green(skillName));+ }+ log.blank();+}diff --git a/packages/cli/src/commands/skill.ts b/packages/cli/src/commands/skill.tsindex 04f46111..4e106bc9 100644--- a/packages/cli/src/commands/skill.ts+++ b/packages/cli/src/commands/skill.ts@@ -23,6 +23,7 @@ import {} from "../utils/ide.js";import { checkboxWithHover, terminalLink, formatInstallCount } from "../utils/prompts.js";import { installSkillFiles, symlinkSkill } from "../utils/installer.js";+import { registerGenerateCommand } from "./generate.js";import type {Skill,SkillSearchResult,@@ -57,6 +58,9 @@ function logInstallSummary(export function registerSkillCommands(program: Command): void {const skill = program.command("skills").alias("skill").description("Manage AI coding skills");+ // Register generate subcommand+ registerGenerateCommand(skill);+skill.command("install").alias("i")diff --git a/packages/cli/src/types.ts b/packages/cli/src/types.tsindex db91ea43..54ebb628 100644--- a/packages/cli/src/types.ts+++ b/packages/cli/src/types.ts@@ -41,6 +41,89 @@ export interface DownloadResponse {error?: string;}+// Library search types+export interface LibrarySearchResult {+ id: string;+ title: string;+ description: string;+ branch: string;+ totalSnippets: number;+ totalTokens?: number;+ stars?: number;+ trustScore?: number;+ benchmarkScore?: number;+ versions?: string[];+ vip?: boolean;+}++export interface LibrarySearchResponse {+ results: LibrarySearchResult[];+ error?: string;+ 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" | "codex" | "opencode" | "amp" | "antigravity";export type Scope = "project" | "global";@@ -61,6 +144,11 @@ export interface ScopeOptions {export type AddOptions = IDEOptions & ScopeOptions & { all?: boolean };export type ListOptions = IDEOptions & ScopeOptions;export type RemoveOptions = IDEOptions & ScopeOptions;+export type GenerateOptions = IDEOptions &+ ScopeOptions & {+ output?: string;+ all?: boolean;+ };export interface InstallTargets {ides: IDE[];@@ -103,3 +191,13 @@ export const DEFAULT_CONFIG: C7Config = {defaultIde: "claude",defaultScope: "project",};++export interface SkillQuotaResponse {+ used: number;+ limit: number;+ remaining: number;+ tier: "free" | "pro" | "unlimited";+ resetDate: string | null;+ message?: string;+ error?: string;+}diff --git a/packages/cli/src/utils/api.ts b/packages/cli/src/utils/api.tsindex a9d6c788..501772e1 100644--- a/packages/cli/src/utils/api.ts+++ b/packages/cli/src/utils/api.ts@@ -3,6 +3,11 @@ import type {SingleSkillResponse,SearchResponse,DownloadResponse,+ LibrarySearchResponse,+ SkillQuestionsResponse,+ StructuredGenerateInput,+ GenerateStreamEvent,+ SkillQuotaResponse,} from "../types.js";import { downloadSkillFromGitHub } from "./github.js";@@ -65,3 +70,170 @@ export async function downloadSkill(project: string, skillName: string): Promisereturn { 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 };+}diff --git a/packages/cli/src/utils/prompts.ts b/packages/cli/src/utils/prompts.tsindex 9ace3ac6..4a0f29ba 100644--- a/packages/cli/src/utils/prompts.ts+++ b/packages/cli/src/utils/prompts.ts@@ -35,8 +35,14 @@ export function formatInstallCount(count: number | undefined): string {return `\x1b[38;5;214m↓${display}\x1b[0m`;}-export async function checkboxWithHover<T extends { name: string }>(- config: CheckboxConfig<T>+export interface CheckboxWithHoverOptions<T> {+ /** Function to extract display name from value. Defaults to (v) => v.name */+ getName?: (value: T) => string;+}++export async function checkboxWithHover<T>(+ config: CheckboxConfig<T>,+ options?: CheckboxWithHoverOptions<T>): Promise<T[]> {const choices = config.choices.filter((c): c is CheckboxChoice<T> =>@@ -46,6 +52,9 @@ export async function checkboxWithHover<T extends { name: string }>(const totalItems = values.length;let cursorPosition = 0;+ // Default getName assumes object has 'name' property+ const getName = options?.getName ?? ((v: T) => (v as { name: string }).name);+const keypressHandler = (_str: string | undefined, key: readline.Key) => {if (key.name === "up" && cursorPosition > 0) {cursorPosition--;@@ -69,9 +78,9 @@ export async function checkboxWithHover<T extends { name: string }>(_allChoices: CheckboxChoice<T>[]): string => {if (selected.length === 0) {- return pc.dim(values[cursorPosition].name);+ return pc.dim(getName(values[cursorPosition]));}- return selected.map((c) => c.value.name).join(", ");+ return selected.map((c) => getName(c.value)).join(", ");},},},diff --git a/packages/cli/src/utils/selectOrInput.ts b/packages/cli/src/utils/selectOrInput.tsnew file mode 100644index 00000000..a0252697--- /dev/null+++ b/packages/cli/src/utils/selectOrInput.ts@@ -0,0 +1,101 @@+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;+}++const selectOrInput: (config: SelectOrInputConfig) => Promise<string> = createPrompt<+ string,+ SelectOrInputConfig+>((config, done): string => {+ const { message, options, recommendedIndex = 0 } = config;+ const [cursor, setCursor] = useState(recommendedIndex);+ 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[recommendedIndex]);+ } 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 === recommendedIndex;+ 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/packages/cli/tsup.config.ts b/packages/cli/tsup.config.tsindex a2b42870..f06613a8 100644--- a/packages/cli/tsup.config.ts+++ b/packages/cli/tsup.config.ts@@ -9,4 +9,12 @@ export default defineConfig({banner: {js: "#!/usr/bin/env node",},+ noExternal: [],+ external: [+ "@inquirer/core",+ "@inquirer/type",+ "@inquirer/prompts",+ "mute-stream",+ "stream",+ ],});diff --git a/packages/sdk/src/client.test.ts b/packages/sdk/src/client.test.tsindex e1fab938..24f9c50f 100644--- a/packages/sdk/src/client.test.ts+++ b/packages/sdk/src/client.test.ts@@ -70,7 +70,7 @@ describe("Context7 Client", () => {const result = await client.searchLibrary(`I want to use ${query}`, query);expect(result.length).toBeGreaterThan(0);}- });+ }, 15000);});describe("getContext - JSON format (default)", () => {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 20d33370..f8645a24 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -7,6 +7,13 @@ settings:importers:.:+ dependencies:+ '@inquirer/core':+ specifier: ^11.1.1+ version: 11.1.1(@types/[email protected])+ '@inquirer/type':+ specifier: ^4.0.3+ version: 4.0.3(@types/[email protected])devDependencies:'@changesets/cli':specifier: ^2.29.7@@ -2941,6 +2948,18 @@ snapshots:optionalDependencies:'@types/node': 22.19.7+ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/ansi': 2.0.3+ '@inquirer/figures': 2.0.3+ '@inquirer/type': 4.0.3(@types/[email protected])+ cli-width: 4.1.0+ mute-stream: 3.0.0+ signal-exit: 4.1.0+ wrap-ansi: 9.0.2+ optionalDependencies:+ '@types/node': 25.0.3+'@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/core': 11.1.1(@types/[email protected])@@ -3037,6 +3056,10 @@ snapshots:optionalDependencies:'@types/node': 22.19.7+ '@inquirer/[email protected](@types/[email protected])':+ optionalDependencies:+ '@types/node': 25.0.3+'@jridgewell/[email protected]':dependencies:'@jridgewell/sourcemap-codec': 1.5.5