Context7 Platform -- Up-to-date docs for AI agents
feat(cli): improve skill search display and revamp generate UX (#1618)
Fahreddin Özcan6328ed154e3d
diff --git a/.changeset/bright-skills-trust.md b/.changeset/bright-skills-trust.mdnew file mode 100644index 00000000..1aae83ba--- /dev/null+++ b/.changeset/bright-skills-trust.md@@ -0,0 +1,11 @@+---+"ctx7": patch+---++Skill search & generate command improvements:++- Add "Installs" and "Trust(0-10)" columns to skill search results with aligned column headers+- Auto-login via OAuth when the generate command requires authentication instead of showing an error+- Reorder question options so the recommended choice always appears first with a "✓ Recommended" badge+- Add "View skill" action that opens generated content in the user's default editor (`$EDITOR`)+- Revamp generate wizard copy: do/don't examples for skill descriptions, rename "libraries" to "sources", and clarify follow-up question and generation spinner textdiff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.tsindex f0b73487..327693b3 100644--- a/packages/cli/src/commands/auth.ts+++ b/packages/cli/src/commands/auth.ts@@ -48,21 +48,7 @@ export function registerAuthCommands(program: Command): void {});}-async function loginCommand(options: { browser: boolean }): Promise<void> {- trackEvent("command", { name: "login" });- const existingTokens = loadTokens();- if (existingTokens) {- const expired = isTokenExpired(existingTokens);- if (!expired || existingTokens.refresh_token) {- console.log(pc.yellow("You are already logged in."));- console.log(- pc.dim("Run 'ctx7 logout' first if you want to log in with a different account.")- );- return;- }- clearTokens();- }-+export async function performLogin(openBrowser = true): Promise<string | null> {const spinner = ora("Preparing login...").start();try {@@ -85,7 +71,7 @@ async function loginCommand(options: { browser: boolean }): Promise<void> {console.log(pc.bold("Opening browser to log in..."));console.log("");- if (options.browser) {+ if (openBrowser) {await open(authUrl);console.log(pc.dim("If the browser didn't open, visit this URL:"));} else {@@ -111,23 +97,45 @@ async function loginCommand(options: { browser: boolean }): Promise<void> {callbackServer.close();waitingSpinner.succeed(pc.green("Login successful!"));- console.log("");- console.log(pc.dim("You can now use authenticated Context7 features."));+ return tokens.access_token;} catch (error) {callbackServer.close();waitingSpinner.fail(pc.red("Login failed"));if (error instanceof Error) {console.error(pc.red(error.message));}- process.exit(1);+ return null;}} catch (error) {spinner.fail(pc.red("Login failed"));if (error instanceof Error) {console.error(pc.red(error.message));}+ return null;+ }+}++async function loginCommand(options: { browser: boolean }): Promise<void> {+ trackEvent("command", { name: "login" });+ const existingTokens = loadTokens();+ if (existingTokens) {+ const expired = isTokenExpired(existingTokens);+ if (!expired || existingTokens.refresh_token) {+ console.log(pc.yellow("You are already logged in."));+ console.log(+ pc.dim("Run 'ctx7 logout' first if you want to log in with a different account.")+ );+ return;+ }+ clearTokens();+ }++ const token = await performLogin(options.browser);+ if (!token) {process.exit(1);}+ console.log("");+ console.log(pc.dim("You can now use authenticated Context7 features."));}function logoutCommand(): void {diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.tsindex 44aae178..ab0646d9 100644--- a/packages/cli/src/commands/generate.ts+++ b/packages/cli/src/commands/generate.ts@@ -1,9 +1,10 @@import { Command } from "commander";import pc from "picocolors";import ora from "ora";-import { mkdir, writeFile } from "fs/promises";+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 {@@ -13,6 +14,7 @@ import {getSkillQuota,} from "../utils/api.js";import { loadTokens, isTokenExpired } 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";@@ -57,20 +59,21 @@ async function generateCommand(options: GenerateOptions): Promise<void> {trackEvent("command", { name: "generate" });log.blank();- // Check authentication+ let accessToken: string | null = null;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;+ if (tokens && !isTokenExpired(tokens)) {+ accessToken = tokens.access_token;+ } else {+ log.info("Authentication required. Logging in...");+ log.blank();+ accessToken = await performLogin();+ if (!accessToken) {+ log.error("Login failed. Please try again.");+ return;+ }+ log.blank();}- const accessToken = tokens.access_token;-const initSpinner = ora().start();const quota = await getSkillQuota(accessToken);@@ -103,14 +106,23 @@ async function generateCommand(options: GenerateOptions): Promise<void> {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")+ 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:"));- 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'));+ // 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 {@@ -128,16 +140,29 @@ async function generateCommand(options: GenerateOptions): Promise<void> {return;}- const searchSpinner = ora("Finding relevant libraries...").start();+ 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 libraries found"));+ 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 libraries`));+ searchSpinner.succeed(pc.green(`Found ${searchResult.results.length} relevant sources`));log.blank();let selectedLibraries: LibrarySearchResult[];@@ -166,9 +191,10 @@ async function generateCommand(options: GenerateOptions): Promise<void> {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 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()}`] : [];@@ -193,7 +219,7 @@ async function generateCommand(options: GenerateOptions): Promise<void> {selectedLibraries = await checkboxWithHover({- message: "Select libraries:",+ message: "Select sources:",choices: libraryChoices,pageSize: 10,loop: false,@@ -202,7 +228,7 @@ async function generateCommand(options: GenerateOptions): Promise<void> {);if (!selectedLibraries || selectedLibraries.length === 0) {- log.info("No libraries selected. Try running the command again.");+ log.info("No sources selected. Try running the command again.");return;}} catch {@@ -212,7 +238,9 @@ async function generateCommand(options: GenerateOptions): Promise<void> {log.blank();- const questionsSpinner = ora("Preparing questions...").start();+ 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);@@ -259,8 +287,15 @@ async function generateCommand(options: GenerateOptions): Promise<void> {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 libraryNames = selectedLibraries.map((lib) => lib.title).join(", ");const queryLog: QueryLogEntry[] = [];let genSpinner: ReturnType<typeof ora> | null = null;@@ -270,7 +305,6 @@ async function generateCommand(options: GenerateOptions): Promise<void> {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)) {@@ -301,6 +335,7 @@ async function generateCommand(options: GenerateOptions): Promise<void> {};let isGeneratingContent = false;+ let initialStatus = "Reading selected Context7 sources to generate the skill...";const handleStreamEvent = (event: GenerateStreamEvent) => {if (event.type === "progress") {@@ -308,13 +343,13 @@ async function generateCommand(options: GenerateOptions): Promise<void> {if (event.message.startsWith("Generating skill content...") && !isGeneratingContent) {isGeneratingContent = true;if (queryLog.length > 0) {- genSpinner.succeed(pc.green(`Queried documentation`));+ 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 = event.message + formatQueryLogText();+ genSpinner.text = initialStatus + formatQueryLogText();}}} else if (event.type === "tool_result") {@@ -340,9 +375,10 @@ async function generateCommand(options: GenerateOptions): Promise<void> {queryLog.length = 0;isGeneratingContent = false;- const initialStatus = feedback+ previewFileWritten = false;+ initialStatus = feedback? "Regenerating skill with your feedback..."- : `Generating skill for "${libraryNames}"...`;+ : "Reading selected Context7 sources to generate the skill...";genSpinner = ora(initialStatus).start();@@ -384,16 +420,28 @@ async function generateCommand(options: GenerateOptions): Promise<void> {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();+ const openInEditor = async () => {+ const previewDir = join(homedir(), ".context7", "previews");+ 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",+ shell: true,+ });+ child.on("close", () => resolve());+ });+ };++ const syncFromPreviewFile = async () => {+ if (previewFile) {+ generatedContent = await readFile(previewFile, "utf-8");+ }};showPreview();@@ -404,8 +452,8 @@ async function generateCommand(options: GenerateOptions): Promise<void> {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.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" },];@@ -415,16 +463,18 @@ async function generateCommand(options: GenerateOptions): Promise<void> {choices,});- if (action === "expand") {- showFullContent();+ 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") {@@ -439,6 +489,7 @@ async function generateCommand(options: GenerateOptions): Promise<void> {log.blank();}} catch {+ await cleanupPreviewFile();log.warn("Generation cancelled");return;}@@ -495,9 +546,11 @@ async function generateCommand(options: GenerateOptions): Promise<void> {trackEvent("gen_install");log.blank();- console.log(pc.green(pc.bold("Skill saved successfully")));+ 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/skill.ts b/packages/cli/src/commands/skill.tsindex 9e9bab14..293452f4 100644--- a/packages/cli/src/commands/skill.ts+++ b/packages/cli/src/commands/skill.ts@@ -15,7 +15,12 @@ import {getSelectedIdes,hasExplicitIdeOption,} from "../utils/ide.js";-import { checkboxWithHover, terminalLink, formatInstallCount } from "../utils/prompts.js";+import {+ checkboxWithHover,+ terminalLink,+ formatInstallCount,+ formatTrustScore,+} from "../utils/prompts.js";import { installSkillFiles, symlinkSkill } from "../utils/installer.js";import { trackEvent } from "../utils/tracking.js";import { registerGenerateCommand } from "./generate.js";@@ -393,12 +398,16 @@ async function searchCommand(query: string): Promise<void> {const indexWidth = data.results.length.toString().length;const maxNameLen = Math.max(...data.results.map((s) => s.name.length));+ const installsColWidth = 10;const choices = data.results.map((s, index) => {const indexStr = pc.dim(`${(index + 1).toString().padStart(indexWidth)}.`);const paddedName = s.name.padEnd(maxNameLen);- const installs = formatInstallCount(s.installCount);+ const installsRaw = s.installCount ? String(s.installCount) : "-";+ const paddedInstalls =+ formatInstallCount(s.installCount, pc.dim("-")) ++ " ".repeat(installsColWidth - installsRaw.length);+ const trust = formatTrustScore(s.trustScore);- // Build metadata panel shown when item is hoveredconst skillLink = terminalLink(s.name,`https://context7.com/skills${s.project}/${s.name}`,@@ -415,7 +424,7 @@ async function searchCommand(query: string): Promise<void> {];return {- name: installs ? `${indexStr} ${paddedName} ${installs}` : `${indexStr} ${paddedName}`,+ name: `${indexStr} ${paddedName} ${paddedInstalls}${trust}`,value: s,description: metadataLines.join("\n"),};@@ -423,9 +432,11 @@ async function searchCommand(query: string): Promise<void> {log.blank();- const installsOffset = 4 + indexWidth + 1 + 1 + maxNameLen + 1 - 3;- const message =- "Select skills to install:" + " ".repeat(Math.max(1, installsOffset - 25)) + pc.dim("installs");+ const checkboxPrefixWidth = 3; // "❯◯ " or " ◯ "+ const headerPad = " ".repeat(checkboxPrefixWidth + indexWidth + 1 + 1 + maxNameLen + 1);+ const headerLine =+ headerPad + pc.dim("Installs".padEnd(installsColWidth)) + pc.dim("Trust(0-10)");+ const message = "Select skills to install:\n" + headerLine;let selectedSkills: SkillSearchResult[];try {diff --git a/packages/cli/src/types.ts b/packages/cli/src/types.tsindex 54ebb628..2d39c34e 100644--- a/packages/cli/src/types.ts+++ b/packages/cli/src/types.ts@@ -8,11 +8,11 @@ export interface Skill {description: string;url: string;installCount?: number;+ trustScore?: number;}export interface SkillSearchResult extends Skill {project: string;- installCount?: number;}export interface ListSkillsResponse {diff --git a/packages/cli/src/utils/prompts.ts b/packages/cli/src/utils/prompts.tsindex f022862e..a2f20736 100644--- a/packages/cli/src/utils/prompts.ts+++ b/packages/cli/src/utils/prompts.ts@@ -10,17 +10,24 @@ type CheckboxChoice<T> = Exclude<CheckboxConfig<T>["choices"][number], Separator*/export function terminalLink(text: string, url: string, color?: (s: string) => string): string {const colorFn = color ?? ((s: string) => s);- return `\x1b]8;;${url}\x07${colorFn(text)}\x1b]8;;\x07`;+ return `\x1b]8;;${url}\x07${colorFn(text)}\x1b]8;;\x07 ${pc.white("↗")}`;}/*** Formats install count for display.*/-export function formatInstallCount(count: number | undefined): string {- if (count === undefined || count === 0) return "";+export function formatInstallCount(count: number | undefined, placeholder = ""): string {+ if (count === undefined || count === 0) return placeholder;return pc.yellow(String(count));}++export function formatTrustScore(score: number | undefined): string {+ if (score === undefined || score < 0) return pc.dim("-");++ if (score < 3) return pc.red(score.toFixed(1));+ return pc.yellow(score.toFixed(1));+}export interface CheckboxWithHoverOptions<T> {/** Function to extract display name from value. Defaults to (v) => v.name */getName?: (value: T) => string;diff --git a/packages/cli/src/utils/selectOrInput.ts b/packages/cli/src/utils/selectOrInput.tsindex a0252697..78fb6301 100644--- a/packages/cli/src/utils/selectOrInput.ts+++ b/packages/cli/src/utils/selectOrInput.ts@@ -16,12 +16,22 @@ export interface SelectOrInputConfig {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, recommendedIndex = 0 } = config;- const [cursor, setCursor] = useState(recommendedIndex);+ const { message, options: rawOptions, recommendedIndex = 0 } = config;+ const options = reorderOptions(rawOptions, recommendedIndex);+ const [cursor, setCursor] = useState(0);const [inputValue, setInputValue] = useState("");const prefix = usePrefix({});@@ -40,7 +50,7 @@ const selectOrInput: (config: SelectOrInputConfig) => Promise<string> = createPrif (isEnterKey(key)) {if (cursor === options.length) {const finalValue = inputValue.trim();- done(finalValue || options[recommendedIndex]);+ done(finalValue || options[0]);} else {done(options[cursor]);}@@ -76,7 +86,7 @@ const selectOrInput: (config: SelectOrInputConfig) => Promise<string> = createPrlet output = `${prefix} ${pc.bold(message)}\n\n`;options.forEach((opt: string, idx: number) => {- const isRecommended = idx === recommendedIndex;+ const isRecommended = idx === 0;const isCursor = idx === cursor;const number = pc.cyan(`${idx + 1}.`);const text = isRecommended ? `${opt} ${pc.green("✓ Recommended")}` : opt;