From 8e6dd08b90f14dccefd71ef195698f469de91e99 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Sat, 18 Apr 2026 00:08:03 +0200 Subject: [PATCH 1/8] feat(scaffolder): parallel install + single-confirm auth prompt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Squeezes ~30-60s off first-run TTHW by running ` install` in the background alongside the LLM generation call instead of serially after it. Install captures stdout/stderr into buffers so it doesn't clobber the spinner that the generation phase owns. Collapses the 3-way auth prompt (Log in / BYOK paste / Skip) to a single confirm("Log in to helpbase free?"). The no-key founder persona always picked Log in; the BYOK paste option was cognitive noise. BYOK users still route via env var — the scaffolder now detects any of AI_GATEWAY_API_KEY / ANTHROPIC_API_KEY / OPENAI_API_KEY via isByokMode() and skips the prompt entirely in that case (not just Gateway). Drops the now-unused writeAiGatewayKey helper + its test. Co-Authored-By: Claude Opus 4.7 (1M context) --- packages/create-helpbase/src/env-local.ts | 34 ---- packages/create-helpbase/src/index.ts | 158 ++++++++++-------- .../test/env-local.unit.test.ts | 51 ------ 3 files changed, 90 insertions(+), 153 deletions(-) delete mode 100644 packages/create-helpbase/src/env-local.ts delete mode 100644 packages/create-helpbase/test/env-local.unit.test.ts diff --git a/packages/create-helpbase/src/env-local.ts b/packages/create-helpbase/src/env-local.ts deleted file mode 100644 index 338d71c..0000000 --- a/packages/create-helpbase/src/env-local.ts +++ /dev/null @@ -1,34 +0,0 @@ -import fs from "node:fs" -import path from "node:path" - -/** - * Write `AI_GATEWAY_API_KEY=` into the scaffolded project's - * `.env.local`. Idempotent: if the key already exists, replace the line. - * If `.env.local` doesn't exist, create it. Next.js + the helpbase CLI - * both read `.env.local` at the project root, so one file serves both. - */ -export function writeAiGatewayKey(projectDir: string, key: string): void { - const envPath = path.join(projectDir, ".env.local") - const line = `AI_GATEWAY_API_KEY=${key}` - - if (!fs.existsSync(envPath)) { - fs.writeFileSync(envPath, `${line}\n`, { mode: 0o600 }) - return - } - - const existing = fs.readFileSync(envPath, "utf-8") - const lines = existing.split("\n") - let replaced = false - const next = lines.map((l) => { - if (l.startsWith("AI_GATEWAY_API_KEY=")) { - replaced = true - return line - } - return l - }) - if (!replaced) { - if (next.length > 0 && next[next.length - 1] !== "") next.push(line) - else next.splice(next.length - 1, 0, line) - } - fs.writeFileSync(envPath, next.join("\n"), { mode: 0o600 }) -} diff --git a/packages/create-helpbase/src/index.ts b/packages/create-helpbase/src/index.ts index 2e2f193..4dc2b17 100644 --- a/packages/create-helpbase/src/index.ts +++ b/packages/create-helpbase/src/index.ts @@ -19,8 +19,8 @@ import { generateArticlesFromContent, } from "@workspace/shared/ai-text" import { scaffoldProject, clearSampleContent } from "./scaffold.js" -import { writeAiGatewayKey } from "./env-local.js" import { readHelpbaseAuthToken } from "./auth.js" +import { isByokMode } from "@workspace/shared/llm" import { generateFromRepo, AllDocsDroppedError, @@ -153,44 +153,23 @@ async function run(directory: string | undefined, opts: RunOptions) { // 3. Auth resolution — conditional on existing state. // Skip entirely when the user already has a helpbase session on disk - // or AI_GATEWAY_API_KEY set. Otherwise offer a three-way choice that - // leads with `helpbase login` (free, captures email) instead of - // asking for a Vercel Gateway key most users don't have. - // Saves ~10-15s of dead-air friction for returning developers, and - // surfaces the login path in the CLI where evaluation actually - // happens, instead of hiding it behind an error message. + // or any BYOK env var set (ANTHROPIC_API_KEY / OPENAI_API_KEY / + // AI_GATEWAY_API_KEY via isByokMode()). + // Otherwise offer a single confirm — the target persona (YC founder + // with no key) always picks "log in free," so a 3-way select was + // cognitive noise. BYOK users route via env var before running; + // paste-a-key was removed to cut prompt count for the common path. let authToken = readHelpbaseAuthToken() - const byokAlreadyResolved = Boolean(process.env.AI_GATEWAY_API_KEY) - let aiGatewayKey: string | undefined - if (isInteractive && source.kind !== "skip" && !authToken && !byokAlreadyResolved) { - const authChoice = await select({ - message: "AI generation needs auth. Pick one:", - options: [ - { - value: "login", - label: "Log in (free, no card, 500k tokens/day)", - hint: "runs `helpbase login` — 30 seconds", - }, - { - value: "byok", - label: "Paste a Vercel AI Gateway key", - hint: "BYOK — unlimited on your own billing", - }, - { - value: "skip", - label: "Skip", - hint: "ship with sample content", - }, - ], - initialValue: "login", + if (isInteractive && source.kind !== "skip" && !authToken && !isByokMode()) { + const wantsLogin = await confirm({ + message: "Log in to helpbase free? (500k tokens/day, no card — 30s browser flow)", + initialValue: true, }) - - if (isCancel(authChoice)) { + if (isCancel(wantsLogin)) { cancel("Setup cancelled.") process.exit(0) } - - if (authChoice === "login") { + if (wantsLogin) { const loginResult = await runHelpbaseLogin() if (loginResult === "failed") { note( @@ -201,22 +180,9 @@ async function run(directory: string | undefined, opts: RunOptions) { // Re-read the token file — login just wrote it. authToken = readHelpbaseAuthToken() } - } else if (authChoice === "byok") { - const keyResponse = await text({ - message: "Paste your Vercel AI Gateway key", - placeholder: "vck_...", - }) - if (isCancel(keyResponse)) { - cancel("Setup cancelled.") - process.exit(0) - } - const trimmed = (keyResponse as string | undefined)?.trim() - if (trimmed && trimmed.length > 0 && trimmed !== "skip") { - aiGatewayKey = trimmed - } } - // authChoice === "skip" → fall through with no token, generation - // will error with the MissingApiKey path and sample content stays. + // Declined → fall through with no token, generation will error with + // the MissingApiKey path and the scaffolded sample content stays. } // 4. Scaffold the project @@ -229,13 +195,27 @@ async function run(directory: string | undefined, opts: RunOptions) { internal: opts.internal, }) - if (aiGatewayKey) { - writeAiGatewayKey(projectDir, aiGatewayKey) - } - s.stop("Project scaffolded!") - // 5. AI content generation — branches by source kind. + // 5. Kick off `pnpm install` in the background so it runs while the LLM + // call is in flight. Install is network + disk I/O, LLM synthesis is + // network I/O — they don't compete. Cuts 30-60s off TTHW on the first + // real run (install used to be strictly serial, after generation). + // Install's stdout/stderr are captured (not piped to terminal) so they + // don't clobber the spinner that generation owns. + const pkgManager = detectPackageManager() + const installPromise: Promise<{ success: true } | { success: false; reason: string }> = + opts.install !== false + ? runInstallInBackground(projectDir, pkgManager) + : Promise.resolve({ success: true } as const) + + if (opts.install !== false) { + console.log( + ` ${pc.dim("›")} Installing dependencies with ${pc.cyan(pkgManager)} in background...`, + ) + } + + // 6. AI content generation — branches by source kind. // // Invariant (Issue 1 fix from /plan-eng-review 2026-04-17): sample // content stays on disk until LLM synthesis SUCCEEDS. The old flow @@ -264,28 +244,26 @@ async function run(directory: string | undefined, opts: RunOptions) { }) } - // 6. Emit mcp.json at project root if generation produced docs. + // 7. Emit mcp.json at project root if generation produced docs. // For `skip` source we keep the sample content + skip emit (sample // content has no citations worth wiring into MCP for a stranger). if (generationSucceeded) { emitMcpJson(projectDir) } - // 7. Install dependencies - const pkgManager = detectPackageManager() + // 8. Wait for install to finish. If the LLM path was slower, install is + // already done and this resolves instantly; if install was slower, the + // spinner tells the user we're still waiting on it. if (opts.install !== false) { - s.start(`Installing dependencies with ${pkgManager}... (this may take a minute)`) - try { - execSync(`${pkgManager} install`, { - cwd: projectDir, - stdio: ["pipe", "pipe", "pipe"], - timeout: 120000, // 2 minute timeout - }) + s.start(`Finishing ${pkgManager} install...`) + const installResult = await installPromise + if (installResult.success) { s.stop("Dependencies installed!") - } catch { + } else { s.stop(pc.yellow("Failed to install dependencies.")) note( - `Run ${pc.cyan(`cd ${projectName as string} && ${pkgManager} install`)} manually.`, + `Run ${pc.cyan(`cd ${projectName as string} && ${pkgManager} install`)} manually.\n` + + ` Reason: ${installResult.reason}`, "Manual install needed", ) } @@ -619,6 +597,50 @@ function detectPackageManager(): string { return "npm" } +/** + * Spawn ` install` as a background child process and resolve + * once it exits. Captures stdout + stderr into buffers (not piped to the + * terminal) so it doesn't interleave with the spinner owned by AI + * generation. On non-zero exit we keep the last 500 chars of stderr so + * the manual-retry note gives a real reason. + * + * 2-minute timeout matches the previous `execSync` behavior — slow CI + * networks occasionally hit it, but 3min+ is almost always a cold Docker + * image pulling the registry for the first time, not a normal user run. + */ +function runInstallInBackground( + projectDir: string, + pkgManager: string, +): Promise<{ success: true } | { success: false; reason: string }> { + return new Promise((resolve) => { + let stderrTail = "" + const child = spawn(pkgManager, ["install"], { + cwd: projectDir, + stdio: ["ignore", "pipe", "pipe"], + timeout: 120000, + }) + child.stdout?.on("data", () => { + // drain to keep the pipe flowing; output is intentionally dropped + }) + child.stderr?.on("data", (chunk: Buffer) => { + // Retain only the tail — package managers can be very chatty, and + // we only surface the reason on failure. + stderrTail = (stderrTail + chunk.toString()).slice(-500) + }) + child.once("error", (err) => { + resolve({ success: false, reason: err.message }) + }) + child.once("exit", (code) => { + if (code === 0) { + resolve({ success: true }) + } else { + const reason = stderrTail.trim() || `${pkgManager} install exited ${code}` + resolve({ success: false, reason }) + } + }) + }) +} + /** * Write generated articles into `/content//*.mdx` and * scaffold the matching `_category.json` files. URL branch only — the repo @@ -664,7 +686,7 @@ function printGenerationFallbackHint(err: unknown, url: string): void { note( `Run ${pc.cyan("helpbase login")} (free, no card) then:\n` + ` ${pc.cyan(`helpbase generate --url ${url}`)}\n\n` + - `Or bring your own key: ${pc.cyan("export AI_GATEWAY_API_KEY=...")} ` + + `Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} ` + `(docs: ${pc.cyan("helpbase.dev/docs/byok")})`, "AI generation skipped", ) @@ -689,7 +711,7 @@ function printRepoGenerationFallbackHint(err: unknown, repoPath: string): void { note( `Run ${pc.cyan("helpbase login")} (free, no card) then:\n` + ` ${pc.cyan(`helpbase context ${repoPath}`)}\n\n` + - `Or bring your own key: ${pc.cyan("export AI_GATEWAY_API_KEY=...")} ` + + `Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} ` + `(docs: ${pc.cyan("helpbase.dev/docs/byok")})`, "AI generation skipped", ) diff --git a/packages/create-helpbase/test/env-local.unit.test.ts b/packages/create-helpbase/test/env-local.unit.test.ts deleted file mode 100644 index 1f7084a..0000000 --- a/packages/create-helpbase/test/env-local.unit.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { describe, it, expect, afterEach } from "vitest" -import fs from "node:fs" -import os from "node:os" -import path from "node:path" -import { writeAiGatewayKey } from "../src/env-local.js" - -const tempDirs: string[] = [] - -function mkTempDir(): string { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "create-helpbase-env-")) - tempDirs.push(dir) - return dir -} - -afterEach(() => { - for (const dir of tempDirs.splice(0)) { - if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true }) - } -}) - -describe("writeAiGatewayKey", () => { - it("creates .env.local with the key when the file doesn't exist", () => { - const dir = mkTempDir() - writeAiGatewayKey(dir, "sk-test-123") - const contents = fs.readFileSync(path.join(dir, ".env.local"), "utf-8") - expect(contents).toBe("AI_GATEWAY_API_KEY=sk-test-123\n") - }) - - it("appends the key when .env.local exists without it", () => { - const dir = mkTempDir() - fs.writeFileSync(path.join(dir, ".env.local"), "FOO=bar\n") - writeAiGatewayKey(dir, "sk-xyz") - const contents = fs.readFileSync(path.join(dir, ".env.local"), "utf-8") - expect(contents).toContain("FOO=bar") - expect(contents).toContain("AI_GATEWAY_API_KEY=sk-xyz") - }) - - it("replaces the existing AI_GATEWAY_API_KEY line", () => { - const dir = mkTempDir() - fs.writeFileSync( - path.join(dir, ".env.local"), - "FOO=bar\nAI_GATEWAY_API_KEY=old\nBAZ=qux\n", - ) - writeAiGatewayKey(dir, "new-key") - const contents = fs.readFileSync(path.join(dir, ".env.local"), "utf-8") - expect(contents).toContain("AI_GATEWAY_API_KEY=new-key") - expect(contents).not.toContain("old") - expect(contents).toContain("FOO=bar") - expect(contents).toContain("BAZ=qux") - }) -}) From dc25907d4fd57a804b14018946364e09410b2002 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Sat, 18 Apr 2026 00:08:15 +0200 Subject: [PATCH 2/8] fix(cli): inline-auth uses isByokMode; device-flow poll interval 1s inline-auth.ts only checked AI_GATEWAY_API_KEY when deciding to skip the hosted-login prompt. Users with only ANTHROPIC_API_KEY or OPENAI_API_KEY set would see a pointless "sign in?" prompt even though the downstream callLlm* path already bypasses the proxy via isByokMode(). Source of truth is now isByokMode() from @workspace/shared/llm, so the prompt and the actual LLM routing agree. auth-device.ts default polling interval drops from 2s to 1s. RFC 8628 says `interval` is the minimum between polls, not a target, so 1s is spec-compliant and cuts ~1s of perceived wait after the user clicks Authorize in the browser. Server-supplied interval still wins. The "slow_down" RFC branch still adds +5s per the spec. Co-Authored-By: Claude Opus 4.7 (1M context) --- packages/cli/src/lib/auth-device.ts | 6 +++++- packages/cli/src/lib/inline-auth.ts | 12 +++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/cli/src/lib/auth-device.ts b/packages/cli/src/lib/auth-device.ts index 3118dd2..84b9499 100644 --- a/packages/cli/src/lib/auth-device.ts +++ b/packages/cli/src/lib/auth-device.ts @@ -36,7 +36,11 @@ export async function deviceLogin(opts: DeviceLoginOptions = {}): Promise { - if (process.env.AI_GATEWAY_API_KEY) { + // Any of AI_GATEWAY_API_KEY / ANTHROPIC_API_KEY / OPENAI_API_KEY skips + // the hosted-login prompt. The downstream `callLlmObject` / `callLlmText` + // branch on isByokMode() too, so this keeps the UI consistent with the + // actual LLM-call routing. + if (isByokMode()) { return { byok: true } } From 4a5286905e8fca01c71d2bb78290d213302ab643 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Sat, 18 Apr 2026 00:08:31 +0200 Subject: [PATCH 3/8] docs(byok): kill stale Gateway-only framing; lead Quick Start with context MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The BYOK feature expanded from AI_GATEWAY_API_KEY only to three keys (ANTHROPIC_API_KEY, OPENAI_API_KEY, AI_GATEWAY_API_KEY) but the prose surfaces kept saying "use your own Vercel AI Gateway key." Trust signal off — the docs lied about what the tool does. Rewrites apps/web/content/guides/byok.mdx into a "three ways to skip the hosted proxy" reference with per-provider examples (Anthropic direct, OpenAI direct, Gateway for multi-provider). Syncs to the registry + scaffolder-template copies. Pulls one source-of-truth byokHint() helper in llm-errors-cli.ts so the three LLM-failure paths (quota, global cap, network) name all three keys in lockstep. Touches the matching stale hints in generate.ts, context.ts, and sync.ts — the --help text and the MissingApiKey fallback now reference login AND all three BYOK keys, not just Gateway. README Quick Start inversion: the <90s path (`helpbase login` + `helpbase context .`) is now the primary entry point. The scaffolder moves to a secondary "Scaffold a full Next.js help-center site" heading for users who want a deployable site, not just `.helpbase/` MDX in an existing repo. The scaffolder note now mentions all three BYOK keys too. Co-Authored-By: Claude Opus 4.7 (1M context) --- README.md | 36 +++-- apps/web/content/guides/byok.mdx | 127 ++++++++++++------ packages/cli/src/commands/context.ts | 5 +- packages/cli/src/commands/generate.ts | 7 +- packages/cli/src/commands/sync.ts | 6 +- packages/cli/src/lib/llm-errors-cli.ts | 17 ++- .../templates/content/guides/byok.mdx | 127 ++++++++++++------ registry/helpbase/content/guides/byok.mdx | 127 ++++++++++++------ 8 files changed, 295 insertions(+), 157 deletions(-) diff --git a/README.md b/README.md index 354d17c..48c953c 100644 --- a/README.md +++ b/README.md @@ -58,20 +58,22 @@ log into. - **Reduced-motion aware** — animations respect `prefers-reduced-motion` - **Production-tested** — 300+ tests across the CLI, scaffolder, MCP server, and content pipeline, plus an install-path smoke test in CI -## Try it on your repo in 60 seconds +## Quick start -Point `helpbase context` at any repo. It synthesizes task-oriented how-to -guides grounded in cited files, writes MDX to `.helpbase/docs/`, emits -`llms.txt` + an MCP config hint, and can answer questions in-terminal -without any MCP client setup. Same content, two surfaces: humans read -the MDX, agents query over MCP. +Point `helpbase context` at any repo. Under 90 seconds from zero to +generated docs. Works on macOS, Linux, and Windows. Requires Node 20+. ```bash -npx helpbase login # magic-link, no card, free 500k tokens/day +npx helpbase login # magic-link device flow, free 500k tokens/day, no card npx helpbase context . # synthesize cited how-tos from your repo npx helpbase context . --ask "how do I log in?" # answer in terminal, no MCP client required ``` +`helpbase context` walks your code + markdown, synthesizes task-oriented +how-to guides grounded in cited files, writes MDX to `.helpbase/docs/`, +and emits `llms.txt` + an MCP config hint. Same content, two surfaces: +humans read the MDX, agents query over MCP. + Every generated doc cites specific files + line ranges. Citations that don't match the repo literally are dropped before write — no hallucinated docs. Secret-shaped content aborts the run before any file hits disk. @@ -80,10 +82,11 @@ docs. Secret-shaped content aborts the run before any file hits disk. Paste one of the blocks from `.helpbase/mcp.json` into Claude Desktop, Cursor, or Claude Code and your agent has your repo as docs. -## Quick start +## Scaffold a full Next.js help-center site -The fastest way to try helpbase. Works on macOS, Linux, and Windows. Requires -Node 20+ and pnpm or npm. +Want a standalone docs site you can deploy, not just `.helpbase/` MDX in +the current repo? Use the scaffolder. Takes ~2 minutes end-to-end +(install runs in parallel with AI generation). ```bash npx create-helpbase my-help-center @@ -92,9 +95,14 @@ npx create-helpbase my-help-center The scaffolder asks what to seed content from: - **A website** — paste a URL, it scrapes the page and generates articles. -- **A code repository** — paste a local path or a `github.com` URL. The scaffolder walks your source, synthesizes cited how-to guides with file + line refs, and writes them to `content/`. Needs a helpbase login (free, 500k tokens/day) or `AI_GATEWAY_API_KEY`. +- **A code repository** — paste a local path or a `github.com` URL. The scaffolder walks your source, synthesizes cited how-to guides with file + line refs, and writes them to `content/`. - **Skip** — ship with sample articles. +If you're not logged in, the scaffolder offers one-click inline login +(free, 500k tokens/day, no card). If you prefer BYOK, export +`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or `AI_GATEWAY_API_KEY` before +running and the scaffolder uses that directly. + Dependencies install, the dev server starts, and your browser opens at `http://localhost:3000`. Edit the markdown in `content/` and the dev server hot-reloads. @@ -127,9 +135,9 @@ The `--test` flag uses Gemini 3.1 Flash Lite for cheap, fast generation. Pass `--model anthropic/claude-sonnet-4.6` (or any Gateway-supported model) to override. -**Power users + CI:** skip the helpbase proxy entirely with your own -[Vercel AI Gateway](https://vercel.com/ai-gateway) key — `export -AI_GATEWAY_API_KEY=...` before running. See +**Power users + CI:** skip the helpbase proxy with whichever key you +already have — `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or +`AI_GATEWAY_API_KEY` (any one works, first found wins). See [helpbase.dev/docs/byok](https://helpbase.dev/docs/byok). ### Drop into an existing Next.js app diff --git a/apps/web/content/guides/byok.mdx b/apps/web/content/guides/byok.mdx index b09b1b3..810c7a0 100644 --- a/apps/web/content/guides/byok.mdx +++ b/apps/web/content/guides/byok.mdx @@ -1,40 +1,41 @@ --- schemaVersion: 1 -title: "Bring your own Gateway key (BYOK)" -description: "When and how to bypass the helpbase hosted proxy with your own Vercel AI Gateway key. For CI, power users, and privacy-sensitive workflows." +title: "Bring your own key (BYOK)" +description: "Three ways to skip the helpbase hosted proxy and call your LLM provider directly. For CI, power users, and privacy-sensitive workflows." tags: ["byok", "advanced", "ci"] order: 99 featured: false --- -helpbase is free to use with a one-command login — 500,000 tokens per day, no -credit card. That covers most people. +helpbase is free to use with a one-command login — 500,000 tokens per day, +no credit card. That covers most people. You might want your own key instead when: -- **You're running in CI.** helpbase sessions are designed for interactive use; - machines need a token. -- **You're already paying for Vercel AI Gateway.** Route everything through - the account you already meter and bill. +- **You're running in CI.** helpbase sessions are designed for interactive + use; machines need a token they already have. +- **You already have a provider key.** Most teams have an Anthropic or OpenAI + key lying around. Use it directly — no second provider to sign up for. - **Free-tier limits are too low for your workload.** 500k/day is ~10 full - `generate` runs or ~250 `context --ask` calls. If you run more, BYOK is - unlimited (well — limited to your own Gateway spend cap). -- **You want zero helpbase.dev round-trips.** Every BYOK call goes direct - to Vercel AI Gateway. helpbase never sees your prompts. + `generate` runs or ~250 `context --ask` calls. BYOK is unlimited (within + your provider's own spend cap). +- **You want zero helpbase.dev round-trips.** Every BYOK call goes direct to + your provider. helpbase never sees your prompts. -## How it works +## Three keys, any one works -Set `AI_GATEWAY_API_KEY` in your environment. That's it. The CLI detects it -and bypasses the helpbase proxy for every LLM call: +Set whichever one you already have. First key found wins; precedence is +`AI_GATEWAY_API_KEY` > `ANTHROPIC_API_KEY` > `OPENAI_API_KEY`. -```bash -export AI_GATEWAY_API_KEY=vck_live_... -helpbase generate --url https://docs.example.com -``` +| Env var | Routes to | Use when | +|---|---|---| +| `ANTHROPIC_API_KEY` | `@ai-sdk/anthropic` direct | You already have an Anthropic key. Pair with `--model anthropic/`. | +| `OPENAI_API_KEY` | `@ai-sdk/openai` direct | You already have an OpenAI key. Pair with `--model openai/`. | +| `AI_GATEWAY_API_KEY` | [Vercel AI Gateway](https://vercel.com/ai-gateway) | You want one key to route any provider (Anthropic, OpenAI, Google, etc.) with one bill. | ``` ┌──────────────────┐ -│ helpbase CLI │─────► Vercel AI SDK direct ─────► Vercel AI Gateway +│ helpbase CLI │─────► Vercel AI SDK direct ─────► your provider │ │ (your key, your bill) └──────────────────┘ (no quota check, no usage log, no helpbase.dev round-trip) @@ -43,7 +44,43 @@ helpbase generate --url https://docs.example.com No changes to prompts, no different models — same output as the hosted path, just routed direct. -## Getting a key +## Anthropic direct + +```bash +export ANTHROPIC_API_KEY=sk-ant-... +helpbase generate --url https://docs.example.com \ + --model anthropic/claude-3-5-sonnet-latest +``` + +The `--model` prefix must be `anthropic/` when only `ANTHROPIC_API_KEY` is +set. Any other prefix will error with a clear message telling you the +exact command to try instead. + +Get a key at [console.anthropic.com](https://console.anthropic.com). + +## OpenAI direct + +```bash +export OPENAI_API_KEY=sk-... +helpbase generate --url https://docs.example.com \ + --model openai/gpt-4o-mini +``` + +Same rule: the `--model` prefix must be `openai/` when only `OPENAI_API_KEY` +is set. + +Get a key at [platform.openai.com](https://platform.openai.com). + +## Vercel AI Gateway (multi-provider) + +```bash +export AI_GATEWAY_API_KEY=vck_live_... +helpbase generate --url https://docs.example.com +# Any --model works: +helpbase generate --url https://docs.example.com --model anthropic/claude-sonnet-4.6 +helpbase generate --url https://docs.example.com --model google/gemini-3.1-flash-lite-preview +helpbase generate --url https://docs.example.com --model openai/gpt-4o-mini +``` 1. Sign in at [vercel.com/ai-gateway](https://vercel.com/ai-gateway). 2. Create an API key. @@ -52,25 +89,24 @@ path, just routed direct. ## CI usage -In GitHub Actions and other CI, set `AI_GATEWAY_API_KEY` as a repo secret -and pass it through: +In GitHub Actions and other CI, set whichever key you use as a repo secret: ```yaml - run: helpbase generate --url https://docs.example.com env: - AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ``` CI users don't need `helpbase login`. If you still want to run `helpbase deploy` from CI (which requires a helpbase account), set `HELPBASE_TOKEN` -as well — that's the helpbase session, separate from the Gateway key. +as well — that's the helpbase session, separate from the provider key. ## Switching back to hosted -Unset the env var: +Unset whichever key is active: ```bash -unset AI_GATEWAY_API_KEY +unset ANTHROPIC_API_KEY # or OPENAI_API_KEY, or AI_GATEWAY_API_KEY ``` The next CLI command will use the helpbase hosted proxy again. No state to @@ -82,32 +118,35 @@ clear, no account to delete. helpbase whoami ``` -If `AI_GATEWAY_API_KEY` is set, `whoami` will show "BYOK mode active — calls -bypass helpbase (no quota applied)". Otherwise it shows your usage against -the free-tier cap. +`whoami` names the active key if BYOK is on: "BYOK mode: `ANTHROPIC_API_KEY` +is set — calls bypass helpbase (no quota applied)". Otherwise it shows your +usage against the free-tier cap. ## Costs -BYOK costs are whatever Gateway charges for the model you pick. As of this -writing the default and `--test` are both `google/gemini-3.1-flash-lite-preview` -(cheap + fast, ~1M context). Rough costs for a 9-article `helpbase generate` -run (~50,000 tokens): +BYOK costs are whatever your provider charges for the model you pick. +Rough costs for a 9-article `helpbase generate` run (~50,000 tokens): -- Gemini 3.1 Flash Lite (default / `--test`): ~$0.004 per run. +- Gemini 3.1 Flash Lite (Gateway default, `--test`): ~$0.004 per run. - Claude Sonnet 4.6 (`--model anthropic/claude-sonnet-4.6`): ~$0.20–0.40. - GPT-4o-mini (`--model openai/gpt-4o-mini`): ~$0.01–0.03. ## Troubleshooting -**"AI_GATEWAY_API_KEY is not set" but I just exported it.** New terminal sessions -don't see variables from old sessions. Re-export in the current shell, or -persist in `.env.local`. +**"ANTHROPIC_API_KEY is set but the model is '...'"** Direct-key mode +requires the `--model` prefix to match your key. Either pass +`--model anthropic/`, or set `AI_GATEWAY_API_KEY` instead to route any +provider through Gateway. + +**"`ANTHROPIC_API_KEY` is not set" but I just exported it.** New terminal +sessions don't see variables from old sessions. Re-export in the current +shell, or persist in `.env.local`. -**"BYOK mode active" but I want to use hosted.** Run `unset -AI_GATEWAY_API_KEY`. You can also delete the line from `.env.local`. +**"BYOK mode active" but I want to use hosted.** Run `unset ` +using whichever key `helpbase whoami` names. You can also delete the line +from `.env.local`. **CI passes the env var but still shows "not signed in".** `helpbase login` -and `AI_GATEWAY_API_KEY` serve different purposes. Login is for hosted -quota + deploy authorization. BYOK bypasses quota only. For deploy in CI, -you also need `HELPBASE_TOKEN` (a helpbase session token) alongside the -Gateway key. +and BYOK serve different purposes. Login is for hosted quota + deploy +authorization. BYOK bypasses quota only. For deploy in CI, you also need +`HELPBASE_TOKEN` (a helpbase session token) alongside your provider key. diff --git a/packages/cli/src/commands/context.ts b/packages/cli/src/commands/context.ts index 519db55..bf717c2 100644 --- a/packages/cli/src/commands/context.ts +++ b/packages/cli/src/commands/context.ts @@ -85,8 +85,9 @@ Examples: $ helpbase context . --only auth # regen just one category $ helpbase context . --require-clean # fail if tree is dirty (CI mode) -Pick one: set ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")}. -BYOK — helpbase calls the provider directly. First key found wins; --model overrides. +Auth: run ${pc.cyan("helpbase login")} (free, 500k tokens/day, no card) + OR export one of ${pc.cyan("ANTHROPIC_API_KEY")} / ${pc.cyan("OPENAI_API_KEY")} / ${pc.cyan("AI_GATEWAY_API_KEY")} + (BYOK — first key found wins; --model overrides) `, ) .action(async (repoPathArg: string, opts) => { diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.ts index 2dbae18..4108cb6 100644 --- a/packages/cli/src/commands/generate.ts +++ b/packages/cli/src/commands/generate.ts @@ -68,7 +68,8 @@ Examples: $ helpbase generate --screenshots ./flow --title "How to invite a teammate" $ helpbase generate --url https://myproduct.com --dry-run # preview without spending tokens -Set AI_GATEWAY_API_KEY first — get a key at https://vercel.com/ai-gateway. +Auth: run ${"`helpbase login`"} (free, 500k tokens/day) OR export one of +${"ANTHROPIC_API_KEY"} / ${"OPENAI_API_KEY"} / ${"AI_GATEWAY_API_KEY"} (BYOK, first found wins). `, ) .action(async (repoPath: string | undefined, opts) => { @@ -645,9 +646,9 @@ function printGenerateError(err: unknown, opts?: { url?: string; repo?: string; // scaffolder / scripts that bypass the command layer. console.error( `\n${pc.red("✖")} Could not generate articles\n` + - ` Reason: Not signed in and no AI_GATEWAY_API_KEY is set.\n` + + ` Reason: Not signed in and no BYOK key is set.\n` + ` Fix: Run ${pc.cyan("helpbase login")} (free, no card), then re-run.\n` + - ` Or bring your own key: ${pc.cyan("export AI_GATEWAY_API_KEY=...")} (docs: helpbase.dev/docs/byok)\n`, + ` Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} (docs: helpbase.dev/docs/byok)\n`, ) return } diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.ts index 8eff0f3..6579395 100644 --- a/packages/cli/src/commands/sync.ts +++ b/packages/cli/src/commands/sync.ts @@ -160,11 +160,11 @@ Set AI_GATEWAY_API_KEY first — https://vercel.com/ai-gateway if (err instanceof MissingApiKeyError) { throw new HelpbaseError({ code: "E_AUTH_REQUIRED", - problem: "Not signed in and no AI_GATEWAY_API_KEY set", + problem: "Not signed in and no BYOK key set", cause: "helpbase sync calls an LLM to propose doc edits; it needs auth or a BYOK key.", fix: [ `Run ${pc.cyan("helpbase login")} (free, no card), then re-run.`, - `Or bring your own key: ${pc.cyan("export AI_GATEWAY_API_KEY=...")}`, + `Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} (first found wins).`, "Docs: https://helpbase.dev/docs/byok", ], }) @@ -373,5 +373,5 @@ async function runDemo(_opts: SyncOptions): Promise { process.stdout.write(rendered + "\n") note("") ok(`Demo complete — ${proposals.length} proposal${proposals.length === 1 ? "" : "s"}, all citation-grounded.`) - info(`Next: ${pc.cyan("export AI_GATEWAY_API_KEY=...")} and run ${pc.cyan("helpbase sync")} in your repo.`) + info(`Next: run ${pc.cyan("helpbase login")} (free) or export ${pc.cyan("ANTHROPIC_API_KEY")} / ${pc.cyan("OPENAI_API_KEY")} / ${pc.cyan("AI_GATEWAY_API_KEY")}, then ${pc.cyan("helpbase sync")} in your repo.`) } diff --git a/packages/cli/src/lib/llm-errors-cli.ts b/packages/cli/src/lib/llm-errors-cli.ts index e00cc03..2b0d809 100644 --- a/packages/cli/src/lib/llm-errors-cli.ts +++ b/packages/cli/src/lib/llm-errors-cli.ts @@ -52,6 +52,17 @@ export function authRequiredError(retryCommand?: string): HelpbaseError { }) } +/** + * Shared BYOK hint line. One source of truth so every stale "Gateway-only" + * error copy updates in lockstep when the set of accepted keys changes. + */ +function byokHint(): string { + return ( + `Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} ` + + `(any one works, first found wins)` + ) +} + export function quotaExceededError( err: QuotaExceededError, retryCommand?: string, @@ -65,7 +76,7 @@ export function quotaExceededError( problem: `You've used today's free allocation (${used} / ${cap} tokens). Resets in ${reset}.`, fix: [ `Join the waitlist for the paid tier → ${pc.cyan(err.upgradeUrl)}${rerun}`, - `Or use your own Vercel AI Gateway key: ${pc.cyan("export AI_GATEWAY_API_KEY=...")}`, + byokHint(), `Docs: ${pc.cyan(err.byokDocsUrl)}`, ], }) @@ -78,7 +89,7 @@ export function globalCapError(err: GlobalCapError): HelpbaseError { problem: `helpbase is over its daily cap. Retry in ${reset}.`, fix: [ "Wait for the daily reset.", - `Or use your own Vercel AI Gateway key: ${pc.cyan("export AI_GATEWAY_API_KEY=...")}`, + byokHint(), `Docs: ${pc.cyan(err.byokDocsUrl)}`, ], }) @@ -92,7 +103,7 @@ export function llmNetworkError(err: LlmNetworkError): HelpbaseError { fix: [ "Check your internet connection.", "Retry — transient network blips are common.", - `Or bypass the proxy entirely: ${pc.cyan("export AI_GATEWAY_API_KEY=...")} (your own key).`, + `${byokHint()} — all three bypass the proxy.`, ], }) } diff --git a/packages/create-helpbase/templates/content/guides/byok.mdx b/packages/create-helpbase/templates/content/guides/byok.mdx index b09b1b3..810c7a0 100644 --- a/packages/create-helpbase/templates/content/guides/byok.mdx +++ b/packages/create-helpbase/templates/content/guides/byok.mdx @@ -1,40 +1,41 @@ --- schemaVersion: 1 -title: "Bring your own Gateway key (BYOK)" -description: "When and how to bypass the helpbase hosted proxy with your own Vercel AI Gateway key. For CI, power users, and privacy-sensitive workflows." +title: "Bring your own key (BYOK)" +description: "Three ways to skip the helpbase hosted proxy and call your LLM provider directly. For CI, power users, and privacy-sensitive workflows." tags: ["byok", "advanced", "ci"] order: 99 featured: false --- -helpbase is free to use with a one-command login — 500,000 tokens per day, no -credit card. That covers most people. +helpbase is free to use with a one-command login — 500,000 tokens per day, +no credit card. That covers most people. You might want your own key instead when: -- **You're running in CI.** helpbase sessions are designed for interactive use; - machines need a token. -- **You're already paying for Vercel AI Gateway.** Route everything through - the account you already meter and bill. +- **You're running in CI.** helpbase sessions are designed for interactive + use; machines need a token they already have. +- **You already have a provider key.** Most teams have an Anthropic or OpenAI + key lying around. Use it directly — no second provider to sign up for. - **Free-tier limits are too low for your workload.** 500k/day is ~10 full - `generate` runs or ~250 `context --ask` calls. If you run more, BYOK is - unlimited (well — limited to your own Gateway spend cap). -- **You want zero helpbase.dev round-trips.** Every BYOK call goes direct - to Vercel AI Gateway. helpbase never sees your prompts. + `generate` runs or ~250 `context --ask` calls. BYOK is unlimited (within + your provider's own spend cap). +- **You want zero helpbase.dev round-trips.** Every BYOK call goes direct to + your provider. helpbase never sees your prompts. -## How it works +## Three keys, any one works -Set `AI_GATEWAY_API_KEY` in your environment. That's it. The CLI detects it -and bypasses the helpbase proxy for every LLM call: +Set whichever one you already have. First key found wins; precedence is +`AI_GATEWAY_API_KEY` > `ANTHROPIC_API_KEY` > `OPENAI_API_KEY`. -```bash -export AI_GATEWAY_API_KEY=vck_live_... -helpbase generate --url https://docs.example.com -``` +| Env var | Routes to | Use when | +|---|---|---| +| `ANTHROPIC_API_KEY` | `@ai-sdk/anthropic` direct | You already have an Anthropic key. Pair with `--model anthropic/`. | +| `OPENAI_API_KEY` | `@ai-sdk/openai` direct | You already have an OpenAI key. Pair with `--model openai/`. | +| `AI_GATEWAY_API_KEY` | [Vercel AI Gateway](https://vercel.com/ai-gateway) | You want one key to route any provider (Anthropic, OpenAI, Google, etc.) with one bill. | ``` ┌──────────────────┐ -│ helpbase CLI │─────► Vercel AI SDK direct ─────► Vercel AI Gateway +│ helpbase CLI │─────► Vercel AI SDK direct ─────► your provider │ │ (your key, your bill) └──────────────────┘ (no quota check, no usage log, no helpbase.dev round-trip) @@ -43,7 +44,43 @@ helpbase generate --url https://docs.example.com No changes to prompts, no different models — same output as the hosted path, just routed direct. -## Getting a key +## Anthropic direct + +```bash +export ANTHROPIC_API_KEY=sk-ant-... +helpbase generate --url https://docs.example.com \ + --model anthropic/claude-3-5-sonnet-latest +``` + +The `--model` prefix must be `anthropic/` when only `ANTHROPIC_API_KEY` is +set. Any other prefix will error with a clear message telling you the +exact command to try instead. + +Get a key at [console.anthropic.com](https://console.anthropic.com). + +## OpenAI direct + +```bash +export OPENAI_API_KEY=sk-... +helpbase generate --url https://docs.example.com \ + --model openai/gpt-4o-mini +``` + +Same rule: the `--model` prefix must be `openai/` when only `OPENAI_API_KEY` +is set. + +Get a key at [platform.openai.com](https://platform.openai.com). + +## Vercel AI Gateway (multi-provider) + +```bash +export AI_GATEWAY_API_KEY=vck_live_... +helpbase generate --url https://docs.example.com +# Any --model works: +helpbase generate --url https://docs.example.com --model anthropic/claude-sonnet-4.6 +helpbase generate --url https://docs.example.com --model google/gemini-3.1-flash-lite-preview +helpbase generate --url https://docs.example.com --model openai/gpt-4o-mini +``` 1. Sign in at [vercel.com/ai-gateway](https://vercel.com/ai-gateway). 2. Create an API key. @@ -52,25 +89,24 @@ path, just routed direct. ## CI usage -In GitHub Actions and other CI, set `AI_GATEWAY_API_KEY` as a repo secret -and pass it through: +In GitHub Actions and other CI, set whichever key you use as a repo secret: ```yaml - run: helpbase generate --url https://docs.example.com env: - AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ``` CI users don't need `helpbase login`. If you still want to run `helpbase deploy` from CI (which requires a helpbase account), set `HELPBASE_TOKEN` -as well — that's the helpbase session, separate from the Gateway key. +as well — that's the helpbase session, separate from the provider key. ## Switching back to hosted -Unset the env var: +Unset whichever key is active: ```bash -unset AI_GATEWAY_API_KEY +unset ANTHROPIC_API_KEY # or OPENAI_API_KEY, or AI_GATEWAY_API_KEY ``` The next CLI command will use the helpbase hosted proxy again. No state to @@ -82,32 +118,35 @@ clear, no account to delete. helpbase whoami ``` -If `AI_GATEWAY_API_KEY` is set, `whoami` will show "BYOK mode active — calls -bypass helpbase (no quota applied)". Otherwise it shows your usage against -the free-tier cap. +`whoami` names the active key if BYOK is on: "BYOK mode: `ANTHROPIC_API_KEY` +is set — calls bypass helpbase (no quota applied)". Otherwise it shows your +usage against the free-tier cap. ## Costs -BYOK costs are whatever Gateway charges for the model you pick. As of this -writing the default and `--test` are both `google/gemini-3.1-flash-lite-preview` -(cheap + fast, ~1M context). Rough costs for a 9-article `helpbase generate` -run (~50,000 tokens): +BYOK costs are whatever your provider charges for the model you pick. +Rough costs for a 9-article `helpbase generate` run (~50,000 tokens): -- Gemini 3.1 Flash Lite (default / `--test`): ~$0.004 per run. +- Gemini 3.1 Flash Lite (Gateway default, `--test`): ~$0.004 per run. - Claude Sonnet 4.6 (`--model anthropic/claude-sonnet-4.6`): ~$0.20–0.40. - GPT-4o-mini (`--model openai/gpt-4o-mini`): ~$0.01–0.03. ## Troubleshooting -**"AI_GATEWAY_API_KEY is not set" but I just exported it.** New terminal sessions -don't see variables from old sessions. Re-export in the current shell, or -persist in `.env.local`. +**"ANTHROPIC_API_KEY is set but the model is '...'"** Direct-key mode +requires the `--model` prefix to match your key. Either pass +`--model anthropic/`, or set `AI_GATEWAY_API_KEY` instead to route any +provider through Gateway. + +**"`ANTHROPIC_API_KEY` is not set" but I just exported it.** New terminal +sessions don't see variables from old sessions. Re-export in the current +shell, or persist in `.env.local`. -**"BYOK mode active" but I want to use hosted.** Run `unset -AI_GATEWAY_API_KEY`. You can also delete the line from `.env.local`. +**"BYOK mode active" but I want to use hosted.** Run `unset ` +using whichever key `helpbase whoami` names. You can also delete the line +from `.env.local`. **CI passes the env var but still shows "not signed in".** `helpbase login` -and `AI_GATEWAY_API_KEY` serve different purposes. Login is for hosted -quota + deploy authorization. BYOK bypasses quota only. For deploy in CI, -you also need `HELPBASE_TOKEN` (a helpbase session token) alongside the -Gateway key. +and BYOK serve different purposes. Login is for hosted quota + deploy +authorization. BYOK bypasses quota only. For deploy in CI, you also need +`HELPBASE_TOKEN` (a helpbase session token) alongside your provider key. diff --git a/registry/helpbase/content/guides/byok.mdx b/registry/helpbase/content/guides/byok.mdx index b09b1b3..810c7a0 100644 --- a/registry/helpbase/content/guides/byok.mdx +++ b/registry/helpbase/content/guides/byok.mdx @@ -1,40 +1,41 @@ --- schemaVersion: 1 -title: "Bring your own Gateway key (BYOK)" -description: "When and how to bypass the helpbase hosted proxy with your own Vercel AI Gateway key. For CI, power users, and privacy-sensitive workflows." +title: "Bring your own key (BYOK)" +description: "Three ways to skip the helpbase hosted proxy and call your LLM provider directly. For CI, power users, and privacy-sensitive workflows." tags: ["byok", "advanced", "ci"] order: 99 featured: false --- -helpbase is free to use with a one-command login — 500,000 tokens per day, no -credit card. That covers most people. +helpbase is free to use with a one-command login — 500,000 tokens per day, +no credit card. That covers most people. You might want your own key instead when: -- **You're running in CI.** helpbase sessions are designed for interactive use; - machines need a token. -- **You're already paying for Vercel AI Gateway.** Route everything through - the account you already meter and bill. +- **You're running in CI.** helpbase sessions are designed for interactive + use; machines need a token they already have. +- **You already have a provider key.** Most teams have an Anthropic or OpenAI + key lying around. Use it directly — no second provider to sign up for. - **Free-tier limits are too low for your workload.** 500k/day is ~10 full - `generate` runs or ~250 `context --ask` calls. If you run more, BYOK is - unlimited (well — limited to your own Gateway spend cap). -- **You want zero helpbase.dev round-trips.** Every BYOK call goes direct - to Vercel AI Gateway. helpbase never sees your prompts. + `generate` runs or ~250 `context --ask` calls. BYOK is unlimited (within + your provider's own spend cap). +- **You want zero helpbase.dev round-trips.** Every BYOK call goes direct to + your provider. helpbase never sees your prompts. -## How it works +## Three keys, any one works -Set `AI_GATEWAY_API_KEY` in your environment. That's it. The CLI detects it -and bypasses the helpbase proxy for every LLM call: +Set whichever one you already have. First key found wins; precedence is +`AI_GATEWAY_API_KEY` > `ANTHROPIC_API_KEY` > `OPENAI_API_KEY`. -```bash -export AI_GATEWAY_API_KEY=vck_live_... -helpbase generate --url https://docs.example.com -``` +| Env var | Routes to | Use when | +|---|---|---| +| `ANTHROPIC_API_KEY` | `@ai-sdk/anthropic` direct | You already have an Anthropic key. Pair with `--model anthropic/`. | +| `OPENAI_API_KEY` | `@ai-sdk/openai` direct | You already have an OpenAI key. Pair with `--model openai/`. | +| `AI_GATEWAY_API_KEY` | [Vercel AI Gateway](https://vercel.com/ai-gateway) | You want one key to route any provider (Anthropic, OpenAI, Google, etc.) with one bill. | ``` ┌──────────────────┐ -│ helpbase CLI │─────► Vercel AI SDK direct ─────► Vercel AI Gateway +│ helpbase CLI │─────► Vercel AI SDK direct ─────► your provider │ │ (your key, your bill) └──────────────────┘ (no quota check, no usage log, no helpbase.dev round-trip) @@ -43,7 +44,43 @@ helpbase generate --url https://docs.example.com No changes to prompts, no different models — same output as the hosted path, just routed direct. -## Getting a key +## Anthropic direct + +```bash +export ANTHROPIC_API_KEY=sk-ant-... +helpbase generate --url https://docs.example.com \ + --model anthropic/claude-3-5-sonnet-latest +``` + +The `--model` prefix must be `anthropic/` when only `ANTHROPIC_API_KEY` is +set. Any other prefix will error with a clear message telling you the +exact command to try instead. + +Get a key at [console.anthropic.com](https://console.anthropic.com). + +## OpenAI direct + +```bash +export OPENAI_API_KEY=sk-... +helpbase generate --url https://docs.example.com \ + --model openai/gpt-4o-mini +``` + +Same rule: the `--model` prefix must be `openai/` when only `OPENAI_API_KEY` +is set. + +Get a key at [platform.openai.com](https://platform.openai.com). + +## Vercel AI Gateway (multi-provider) + +```bash +export AI_GATEWAY_API_KEY=vck_live_... +helpbase generate --url https://docs.example.com +# Any --model works: +helpbase generate --url https://docs.example.com --model anthropic/claude-sonnet-4.6 +helpbase generate --url https://docs.example.com --model google/gemini-3.1-flash-lite-preview +helpbase generate --url https://docs.example.com --model openai/gpt-4o-mini +``` 1. Sign in at [vercel.com/ai-gateway](https://vercel.com/ai-gateway). 2. Create an API key. @@ -52,25 +89,24 @@ path, just routed direct. ## CI usage -In GitHub Actions and other CI, set `AI_GATEWAY_API_KEY` as a repo secret -and pass it through: +In GitHub Actions and other CI, set whichever key you use as a repo secret: ```yaml - run: helpbase generate --url https://docs.example.com env: - AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} ``` CI users don't need `helpbase login`. If you still want to run `helpbase deploy` from CI (which requires a helpbase account), set `HELPBASE_TOKEN` -as well — that's the helpbase session, separate from the Gateway key. +as well — that's the helpbase session, separate from the provider key. ## Switching back to hosted -Unset the env var: +Unset whichever key is active: ```bash -unset AI_GATEWAY_API_KEY +unset ANTHROPIC_API_KEY # or OPENAI_API_KEY, or AI_GATEWAY_API_KEY ``` The next CLI command will use the helpbase hosted proxy again. No state to @@ -82,32 +118,35 @@ clear, no account to delete. helpbase whoami ``` -If `AI_GATEWAY_API_KEY` is set, `whoami` will show "BYOK mode active — calls -bypass helpbase (no quota applied)". Otherwise it shows your usage against -the free-tier cap. +`whoami` names the active key if BYOK is on: "BYOK mode: `ANTHROPIC_API_KEY` +is set — calls bypass helpbase (no quota applied)". Otherwise it shows your +usage against the free-tier cap. ## Costs -BYOK costs are whatever Gateway charges for the model you pick. As of this -writing the default and `--test` are both `google/gemini-3.1-flash-lite-preview` -(cheap + fast, ~1M context). Rough costs for a 9-article `helpbase generate` -run (~50,000 tokens): +BYOK costs are whatever your provider charges for the model you pick. +Rough costs for a 9-article `helpbase generate` run (~50,000 tokens): -- Gemini 3.1 Flash Lite (default / `--test`): ~$0.004 per run. +- Gemini 3.1 Flash Lite (Gateway default, `--test`): ~$0.004 per run. - Claude Sonnet 4.6 (`--model anthropic/claude-sonnet-4.6`): ~$0.20–0.40. - GPT-4o-mini (`--model openai/gpt-4o-mini`): ~$0.01–0.03. ## Troubleshooting -**"AI_GATEWAY_API_KEY is not set" but I just exported it.** New terminal sessions -don't see variables from old sessions. Re-export in the current shell, or -persist in `.env.local`. +**"ANTHROPIC_API_KEY is set but the model is '...'"** Direct-key mode +requires the `--model` prefix to match your key. Either pass +`--model anthropic/`, or set `AI_GATEWAY_API_KEY` instead to route any +provider through Gateway. + +**"`ANTHROPIC_API_KEY` is not set" but I just exported it.** New terminal +sessions don't see variables from old sessions. Re-export in the current +shell, or persist in `.env.local`. -**"BYOK mode active" but I want to use hosted.** Run `unset -AI_GATEWAY_API_KEY`. You can also delete the line from `.env.local`. +**"BYOK mode active" but I want to use hosted.** Run `unset ` +using whichever key `helpbase whoami` names. You can also delete the line +from `.env.local`. **CI passes the env var but still shows "not signed in".** `helpbase login` -and `AI_GATEWAY_API_KEY` serve different purposes. Login is for hosted -quota + deploy authorization. BYOK bypasses quota only. For deploy in CI, -you also need `HELPBASE_TOKEN` (a helpbase session token) alongside the -Gateway key. +and BYOK serve different purposes. Login is for hosted quota + deploy +authorization. BYOK bypasses quota only. For deploy in CI, you also need +`HELPBASE_TOKEN` (a helpbase session token) alongside your provider key. From 041c5c820d5a4cd26b868c17564e2e4c49f69082 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Sat, 18 Apr 2026 08:19:06 +0200 Subject: [PATCH 4/8] fix(byok): web error pages + 9 broken /docs/byok links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two follow-ups from the /devex-review audit of the live site: 1) apps/web/app/(main)/errors/[code]/page.tsx had 8 stale Gateway-only hints across 5 error codes (e-missing-api-key, e-auth-required, e-quota-exceeded, e-global-cap, e-llm-network, e-llm-gateway). The CLI-side copy was updated in #8; these web-rendered pages at helpbase.dev/errors/ still said "export AI_GATEWAY_API_KEY=..." as the only BYOK option. Rewrote each to the 3-key pattern matching llm-errors-cli.ts. 2) /docs/byok was a 404 everywhere. The live guide lives at /guides/byok. Nine surfaces (README, waitlist page, sync guide, CLI error hints, workflow README, BYOK_DOCS_URL const) pointed at the broken URL — every link a new user followed was dead. Updated BYOK_DOCS_URL in shared/llm-wire.ts as the source of truth, plus all hardcoded strings that didn't flow through it. Test fixtures updated for consistency. Ran pnpm sync:templates + pnpm registry:build so the scaffolder template + registry JSON pick up the fixed sync-in-5-minutes.mdx copy and the workflow README change. 654/654 tests green across shared/cli/scaffolder/web (excluding 2 pre-existing env-bleed cli tests unrelated to this change). Co-Authored-By: Claude Opus 4.7 (1M context) --- README.md | 2 +- apps/web/app/(main)/errors/[code]/page.tsx | 31 ++++++++++--------- apps/web/app/(main)/waitlist/page.tsx | 4 +-- apps/web/content/guides/sync-in-5-minutes.mdx | 7 +++-- apps/web/public/r/helpbase-workflow.json | 2 +- packages/cli/src/commands/generate.ts | 2 +- packages/cli/src/commands/sync.ts | 2 +- packages/create-helpbase/src/index.ts | 4 +-- .../content/guides/sync-in-5-minutes.mdx | 7 +++-- .../shared/src/__tests__/llm-errors.test.ts | 4 +-- packages/shared/src/__tests__/llm.test.ts | 4 +-- packages/shared/src/llm-wire.ts | 2 +- packages/shared/src/llm.ts | 4 +-- registry/helpbase-workflow/README.md | 9 +++--- .../content/guides/sync-in-5-minutes.mdx | 7 +++-- 15 files changed, 49 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 48c953c..1e2f472 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ override. **Power users + CI:** skip the helpbase proxy with whichever key you already have — `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or `AI_GATEWAY_API_KEY` (any one works, first found wins). See -[helpbase.dev/docs/byok](https://helpbase.dev/docs/byok). +[helpbase.dev/guides/byok](https://helpbase.dev/guides/byok). ### Drop into an existing Next.js app diff --git a/apps/web/app/(main)/errors/[code]/page.tsx b/apps/web/app/(main)/errors/[code]/page.tsx index 97e942f..07c4e61 100644 --- a/apps/web/app/(main)/errors/[code]/page.tsx +++ b/apps/web/app/(main)/errors/[code]/page.tsx @@ -158,13 +158,16 @@ const ERRORS: Record = { }, "e-missing-api-key": { code: "E_MISSING_API_KEY", - title: "AI_GATEWAY_API_KEY not set", + title: "No helpbase session or BYOK key", summary: - "helpbase generate needs an AI gateway key to call the model provider.", - causes: ["AI_GATEWAY_API_KEY isn't in your environment."], + "helpbase generate needs either a helpbase session (free tier) or a BYOK provider key to call the LLM.", + causes: [ + "You're not signed in (no `~/.helpbase/auth.json`) and no BYOK env var is set.", + ], fixes: [ - "Get a key at https://vercel.com/ai-gateway.", - "Export it: `export AI_GATEWAY_API_KEY=`.", + "Run `helpbase login` — free, 500k tokens/day, no card.", + "Or export any one of `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `AI_GATEWAY_API_KEY` (first found wins).", + "See https://helpbase.dev/guides/byok for per-provider setup.", ], }, "e-no-mcp-token": { @@ -291,9 +294,9 @@ const ERRORS: Record = { fixes: [ "Run `helpbase login` — free tier, no card, 500k tokens/day.", "For CI: set `HELPBASE_TOKEN` to a valid session token.", - "Or bring your own key: `export AI_GATEWAY_API_KEY=…` (see /docs/byok).", + "Or bring your own key: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or `AI_GATEWAY_API_KEY` (first found wins — see /guides/byok).", ], - seeAlso: [{ label: "BYOK docs", href: "/docs/byok" }], + seeAlso: [{ label: "BYOK docs", href: "/guides/byok" }], }, "e-quota-exceeded": { code: "E_QUOTA_EXCEEDED", @@ -307,11 +310,11 @@ const ERRORS: Record = { fixes: [ "Wait for the UTC-midnight reset.", "Join the paid-tier waitlist: https://helpbase.dev/waitlist", - "Bring your own Vercel AI Gateway key: `export AI_GATEWAY_API_KEY=…` (unlimited, your own bill).", + "Bring your own key: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or `AI_GATEWAY_API_KEY` (unlimited on your own bill, first found wins).", ], seeAlso: [ { label: "Waitlist", href: "/waitlist" }, - { label: "BYOK docs", href: "/docs/byok" }, + { label: "BYOK docs", href: "/guides/byok" }, ], }, "e-global-cap": { @@ -325,9 +328,9 @@ const ERRORS: Record = { ], fixes: [ "Wait for the UTC-midnight reset.", - "Bring your own Vercel AI Gateway key to bypass the hosted proxy entirely: `export AI_GATEWAY_API_KEY=…`", + "Bring your own key to bypass the hosted proxy entirely: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or `AI_GATEWAY_API_KEY`.", ], - seeAlso: [{ label: "BYOK docs", href: "/docs/byok" }], + seeAlso: [{ label: "BYOK docs", href: "/guides/byok" }], }, "e-llm-network": { code: "E_LLM_NETWORK", @@ -342,9 +345,9 @@ const ERRORS: Record = { fixes: [ "Check your connection and retry — transient blips are common.", "If you're behind a corporate proxy, verify helpbase.dev is reachable.", - "Fall back to BYOK so calls don't go through helpbase.dev: `export AI_GATEWAY_API_KEY=…`", + "Fall back to BYOK so calls don't go through helpbase.dev: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or `AI_GATEWAY_API_KEY`.", ], - seeAlso: [{ label: "BYOK docs", href: "/docs/byok" }], + seeAlso: [{ label: "BYOK docs", href: "/guides/byok" }], }, "e-llm-gateway": { code: "E_LLM_GATEWAY", @@ -352,7 +355,7 @@ const ERRORS: Record = { summary: "The underlying model provider (e.g. Anthropic, Google) returned a non-success response. No tokens were charged against your quota.", causes: [ - "The model ID is wrong or unsupported by Vercel AI Gateway.", + "The model ID is wrong or unsupported by the provider you're routed to (Gateway, Anthropic, or OpenAI direct).", "Upstream provider is degraded.", "The prompt triggered a provider-side safety filter.", ], diff --git a/apps/web/app/(main)/waitlist/page.tsx b/apps/web/app/(main)/waitlist/page.tsx index 39b7778..e7fdeee 100644 --- a/apps/web/app/(main)/waitlist/page.tsx +++ b/apps/web/app/(main)/waitlist/page.tsx @@ -42,8 +42,8 @@ async function WaitlistContent({

Need more tokens right now?{" "} - - Bring your own Vercel AI Gateway key + + Bring your own key (Anthropic, OpenAI, or Gateway) {" "} — unlimited, your own cost.

diff --git a/apps/web/content/guides/sync-in-5-minutes.mdx b/apps/web/content/guides/sync-in-5-minutes.mdx index 0353613..ad6c75f 100644 --- a/apps/web/content/guides/sync-in-5-minutes.mdx +++ b/apps/web/content/guides/sync-in-5-minutes.mdx @@ -47,9 +47,10 @@ Magic-link flow. Free tier is 500,000 tokens per day — enough for roughly 10 full generates or 250 `context --ask` calls. -Prefer your own key? Set `AI_GATEWAY_API_KEY` and helpbase will route through -your Vercel AI Gateway account instead. See -[helpbase.dev/docs/byok](https://helpbase.dev/docs/byok). +Prefer your own key? Set `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or +`AI_GATEWAY_API_KEY` — helpbase routes direct to whichever provider you set +(first found wins). See +[helpbase.dev/guides/byok](https://helpbase.dev/guides/byok). ## Step 3 — Make a code change worth documenting diff --git a/apps/web/public/r/helpbase-workflow.json b/apps/web/public/r/helpbase-workflow.json index 9b8ea77..8ceb02f 100644 --- a/apps/web/public/r/helpbase-workflow.json +++ b/apps/web/public/r/helpbase-workflow.json @@ -12,7 +12,7 @@ }, { "path": "registry/helpbase-workflow/README.md", - "content": "# helpbase-workflow\n\nDrop-in GitHub Actions workflow that runs `helpbase sync` on a schedule and\non every push to your main branch. When a code change would make an MDX\ndoc wrong, the workflow opens a PR with the proposed update, grounded in\ncitations into your source.\n\nNo SaaS in the path. Runs in your Actions minutes, reads your secrets,\nwrites to your repo.\n\n## Install\n\n```bash\nnpx shadcn add https://helpbase.dev/r/helpbase-workflow.json\n```\n\nThat drops a single file into your repo:\n\n```\n.github/workflows/helpbase-sync.yml\n```\n\n## Configure\n\nAdd one secret to your GitHub repo (**Settings → Secrets and variables →\nActions → New repository secret**). You have two options:\n\n- **`AI_GATEWAY_API_KEY`** (recommended for CI) — your key from\n [vercel.com/ai-gateway](https://vercel.com/ai-gateway). Bypasses helpbase's\n hosted proxy entirely. Your Gateway account, your bill, no daily quota\n limit. See [helpbase.dev/docs/byok](https://helpbase.dev/docs/byok).\n- **`HELPBASE_TOKEN`** — a helpbase session access token. After running\n `helpbase login` locally, pull the value from `~/.helpbase/auth.json`:\n `jq -r .access_token ~/.helpbase/auth.json`. Uses helpbase's hosted proxy\n and the free-tier 500k tokens/day cap. Note: session tokens are relatively\n short-lived — rotate the secret when it expires.\n\nIf both are set, `AI_GATEWAY_API_KEY` wins (BYOK mode).\n\n`GH_TOKEN` is read from `github.token` automatically, so you don't need\nto provision it manually.\n\n## Customize\n\nThe workflow ships with sensible defaults you'll likely want to tweak:\n\n- **Schedule** — default is Monday 09:00 UTC (`cron: \"0 9 * * 1\"`). Edit\n the `cron` line to match when your team starts the week.\n- **Base branch** — default assumes `main`. Change both `branches: [main]`\n under `push:` and `--since origin/main` in the run step if you use\n `master`, `trunk`, or something else.\n- **Content directory** — default assumes `content/`. If your docs live\n elsewhere, append `--content docs/` to the `helpbase sync` command.\n\n## What the PR looks like\n\nEvery edit in the generated PR carries a `citations` trailer pointing at\nspecific lines of source code that justified the change. Review those\ncitations first — if a citation is missing or wrong, reject the PR; the\nschema makes this rare but not impossible.\n\n## Run locally\n\nTo preview what the workflow would propose, run the same command on your\nmachine:\n\n```bash\nAI_GATEWAY_API_KEY=your_key_here \\\n npx helpbase sync --since origin/main --dry-run\n```\n\nDrop `--dry-run` when you're ready to see the real proposals.\n", + "content": "# helpbase-workflow\n\nDrop-in GitHub Actions workflow that runs `helpbase sync` on a schedule and\non every push to your main branch. When a code change would make an MDX\ndoc wrong, the workflow opens a PR with the proposed update, grounded in\ncitations into your source.\n\nNo SaaS in the path. Runs in your Actions minutes, reads your secrets,\nwrites to your repo.\n\n## Install\n\n```bash\nnpx shadcn add https://helpbase.dev/r/helpbase-workflow.json\n```\n\nThat drops a single file into your repo:\n\n```\n.github/workflows/helpbase-sync.yml\n```\n\n## Configure\n\nAdd one secret to your GitHub repo (**Settings → Secrets and variables →\nActions → New repository secret**). You have two options:\n\n- **Any BYOK key** (recommended for CI) — `ANTHROPIC_API_KEY`,\n `OPENAI_API_KEY`, or `AI_GATEWAY_API_KEY`. Bypasses helpbase's hosted\n proxy entirely. Your provider account, your bill, no daily quota\n limit. First key found wins. See\n [helpbase.dev/guides/byok](https://helpbase.dev/guides/byok).\n- **`HELPBASE_TOKEN`** — a helpbase session access token. After running\n `helpbase login` locally, pull the value from `~/.helpbase/auth.json`:\n `jq -r .access_token ~/.helpbase/auth.json`. Uses helpbase's hosted proxy\n and the free-tier 500k tokens/day cap. Note: session tokens are relatively\n short-lived — rotate the secret when it expires.\n\nIf both are set, `AI_GATEWAY_API_KEY` wins (BYOK mode).\n\n`GH_TOKEN` is read from `github.token` automatically, so you don't need\nto provision it manually.\n\n## Customize\n\nThe workflow ships with sensible defaults you'll likely want to tweak:\n\n- **Schedule** — default is Monday 09:00 UTC (`cron: \"0 9 * * 1\"`). Edit\n the `cron` line to match when your team starts the week.\n- **Base branch** — default assumes `main`. Change both `branches: [main]`\n under `push:` and `--since origin/main` in the run step if you use\n `master`, `trunk`, or something else.\n- **Content directory** — default assumes `content/`. If your docs live\n elsewhere, append `--content docs/` to the `helpbase sync` command.\n\n## What the PR looks like\n\nEvery edit in the generated PR carries a `citations` trailer pointing at\nspecific lines of source code that justified the change. Review those\ncitations first — if a citation is missing or wrong, reject the PR; the\nschema makes this rare but not impossible.\n\n## Run locally\n\nTo preview what the workflow would propose, run the same command on your\nmachine:\n\n```bash\nAI_GATEWAY_API_KEY=your_key_here \\\n npx helpbase sync --since origin/main --dry-run\n```\n\nDrop `--dry-run` when you're ready to see the real proposals.\n", "type": "registry:file", "target": ".github/workflows/helpbase-sync.README.md" } diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.ts index 4108cb6..72a27d1 100644 --- a/packages/cli/src/commands/generate.ts +++ b/packages/cli/src/commands/generate.ts @@ -648,7 +648,7 @@ function printGenerateError(err: unknown, opts?: { url?: string; repo?: string; `\n${pc.red("✖")} Could not generate articles\n` + ` Reason: Not signed in and no BYOK key is set.\n` + ` Fix: Run ${pc.cyan("helpbase login")} (free, no card), then re-run.\n` + - ` Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} (docs: helpbase.dev/docs/byok)\n`, + ` Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} (docs: helpbase.dev/guides/byok)\n`, ) return } diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.ts index 6579395..aa80307 100644 --- a/packages/cli/src/commands/sync.ts +++ b/packages/cli/src/commands/sync.ts @@ -165,7 +165,7 @@ Set AI_GATEWAY_API_KEY first — https://vercel.com/ai-gateway fix: [ `Run ${pc.cyan("helpbase login")} (free, no card), then re-run.`, `Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} (first found wins).`, - "Docs: https://helpbase.dev/docs/byok", + "Docs: https://helpbase.dev/guides/byok", ], }) } diff --git a/packages/create-helpbase/src/index.ts b/packages/create-helpbase/src/index.ts index 4dc2b17..fd55124 100644 --- a/packages/create-helpbase/src/index.ts +++ b/packages/create-helpbase/src/index.ts @@ -687,7 +687,7 @@ function printGenerationFallbackHint(err: unknown, url: string): void { `Run ${pc.cyan("helpbase login")} (free, no card) then:\n` + ` ${pc.cyan(`helpbase generate --url ${url}`)}\n\n` + `Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} ` + - `(docs: ${pc.cyan("helpbase.dev/docs/byok")})`, + `(docs: ${pc.cyan("helpbase.dev/guides/byok")})`, "AI generation skipped", ) return @@ -712,7 +712,7 @@ function printRepoGenerationFallbackHint(err: unknown, repoPath: string): void { `Run ${pc.cyan("helpbase login")} (free, no card) then:\n` + ` ${pc.cyan(`helpbase context ${repoPath}`)}\n\n` + `Or bring your own key: ${pc.cyan("ANTHROPIC_API_KEY")}, ${pc.cyan("OPENAI_API_KEY")}, or ${pc.cyan("AI_GATEWAY_API_KEY")} ` + - `(docs: ${pc.cyan("helpbase.dev/docs/byok")})`, + `(docs: ${pc.cyan("helpbase.dev/guides/byok")})`, "AI generation skipped", ) return diff --git a/packages/create-helpbase/templates/content/guides/sync-in-5-minutes.mdx b/packages/create-helpbase/templates/content/guides/sync-in-5-minutes.mdx index 0353613..ad6c75f 100644 --- a/packages/create-helpbase/templates/content/guides/sync-in-5-minutes.mdx +++ b/packages/create-helpbase/templates/content/guides/sync-in-5-minutes.mdx @@ -47,9 +47,10 @@ Magic-link flow. Free tier is 500,000 tokens per day — enough for roughly 10 full generates or 250 `context --ask` calls. -Prefer your own key? Set `AI_GATEWAY_API_KEY` and helpbase will route through -your Vercel AI Gateway account instead. See -[helpbase.dev/docs/byok](https://helpbase.dev/docs/byok). +Prefer your own key? Set `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or +`AI_GATEWAY_API_KEY` — helpbase routes direct to whichever provider you set +(first found wins). See +[helpbase.dev/guides/byok](https://helpbase.dev/guides/byok). ## Step 3 — Make a code change worth documenting diff --git a/packages/shared/src/__tests__/llm-errors.test.ts b/packages/shared/src/__tests__/llm-errors.test.ts index 08ecac2..6a1499f 100644 --- a/packages/shared/src/__tests__/llm-errors.test.ts +++ b/packages/shared/src/__tests__/llm-errors.test.ts @@ -80,7 +80,7 @@ describe("Error classes carry code + shape", () => { dailyLimit: 500_000, resetAt: "2026-04-18T00:00:00Z", upgradeUrl: "https://helpbase.dev/waitlist", - byokDocsUrl: "https://helpbase.dev/docs/byok", + byokDocsUrl: "https://helpbase.dev/guides/byok", }) expect(e.code).toBe("quota_exceeded") expect(e.usedToday).toBe(500_000) @@ -89,7 +89,7 @@ describe("Error classes carry code + shape", () => { it("GlobalCapError", () => { const e = new GlobalCapError({ resetAt: "2026-04-18T00:00:00Z", - byokDocsUrl: "https://helpbase.dev/docs/byok", + byokDocsUrl: "https://helpbase.dev/guides/byok", }) expect(e.code).toBe("global_cap_hit") }) diff --git a/packages/shared/src/__tests__/llm.test.ts b/packages/shared/src/__tests__/llm.test.ts index 8e93998..100cde7 100644 --- a/packages/shared/src/__tests__/llm.test.ts +++ b/packages/shared/src/__tests__/llm.test.ts @@ -255,7 +255,7 @@ describe("callLlmObject hosted path — error mapping", () => { dailyLimit: 500_000, resetAt: "2026-04-18T00:00:00Z", upgradeUrl: "https://helpbase.dev/waitlist", - byokDocsUrl: "https://helpbase.dev/docs/byok", + byokDocsUrl: "https://helpbase.dev/guides/byok", }) try { await callLlmObject({ model: "x/y", prompt: "p", schema, authToken: "ok" }) @@ -274,7 +274,7 @@ describe("callLlmObject hosted path — error mapping", () => { error: "global_cap_hit", message: "global", resetAt: "2026-04-18T00:00:00Z", - byokDocsUrl: "https://helpbase.dev/docs/byok", + byokDocsUrl: "https://helpbase.dev/guides/byok", }) await expect( callLlmObject({ model: "x/y", prompt: "p", schema, authToken: "ok" }), diff --git a/packages/shared/src/llm-wire.ts b/packages/shared/src/llm-wire.ts index fa71cdc..4366357 100644 --- a/packages/shared/src/llm-wire.ts +++ b/packages/shared/src/llm-wire.ts @@ -144,4 +144,4 @@ export type WireErrorCode = export const UPGRADE_URL = "https://helpbase.dev/waitlist" as const /** URL that BYOK hints in errors point at. */ -export const BYOK_DOCS_URL = "https://helpbase.dev/docs/byok" as const +export const BYOK_DOCS_URL = "https://helpbase.dev/guides/byok" as const diff --git a/packages/shared/src/llm.ts b/packages/shared/src/llm.ts index ee37a51..8a3078f 100644 --- a/packages/shared/src/llm.ts +++ b/packages/shared/src/llm.ts @@ -407,13 +407,13 @@ async function throwOnWireError(res: Response): Promise { dailyLimit: body.dailyLimit ?? 0, resetAt: body.resetAt ?? new Date().toISOString(), upgradeUrl: body.upgradeUrl ?? "https://helpbase.dev/waitlist", - byokDocsUrl: body.byokDocsUrl ?? "https://helpbase.dev/docs/byok", + byokDocsUrl: body.byokDocsUrl ?? "https://helpbase.dev/guides/byok", message: body.message, }) case "global_cap_hit": throw new GlobalCapError({ resetAt: body.resetAt ?? new Date().toISOString(), - byokDocsUrl: body.byokDocsUrl ?? "https://helpbase.dev/docs/byok", + byokDocsUrl: body.byokDocsUrl ?? "https://helpbase.dev/guides/byok", message: body.message, }) case "gateway_error": diff --git a/registry/helpbase-workflow/README.md b/registry/helpbase-workflow/README.md index 3b53716..c4dbd68 100644 --- a/registry/helpbase-workflow/README.md +++ b/registry/helpbase-workflow/README.md @@ -25,10 +25,11 @@ That drops a single file into your repo: Add one secret to your GitHub repo (**Settings → Secrets and variables → Actions → New repository secret**). You have two options: -- **`AI_GATEWAY_API_KEY`** (recommended for CI) — your key from - [vercel.com/ai-gateway](https://vercel.com/ai-gateway). Bypasses helpbase's - hosted proxy entirely. Your Gateway account, your bill, no daily quota - limit. See [helpbase.dev/docs/byok](https://helpbase.dev/docs/byok). +- **Any BYOK key** (recommended for CI) — `ANTHROPIC_API_KEY`, + `OPENAI_API_KEY`, or `AI_GATEWAY_API_KEY`. Bypasses helpbase's hosted + proxy entirely. Your provider account, your bill, no daily quota + limit. First key found wins. See + [helpbase.dev/guides/byok](https://helpbase.dev/guides/byok). - **`HELPBASE_TOKEN`** — a helpbase session access token. After running `helpbase login` locally, pull the value from `~/.helpbase/auth.json`: `jq -r .access_token ~/.helpbase/auth.json`. Uses helpbase's hosted proxy diff --git a/registry/helpbase/content/guides/sync-in-5-minutes.mdx b/registry/helpbase/content/guides/sync-in-5-minutes.mdx index 0353613..ad6c75f 100644 --- a/registry/helpbase/content/guides/sync-in-5-minutes.mdx +++ b/registry/helpbase/content/guides/sync-in-5-minutes.mdx @@ -47,9 +47,10 @@ Magic-link flow. Free tier is 500,000 tokens per day — enough for roughly 10 full generates or 250 `context --ask` calls. -Prefer your own key? Set `AI_GATEWAY_API_KEY` and helpbase will route through -your Vercel AI Gateway account instead. See -[helpbase.dev/docs/byok](https://helpbase.dev/docs/byok). +Prefer your own key? Set `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or +`AI_GATEWAY_API_KEY` — helpbase routes direct to whichever provider you set +(first found wins). See +[helpbase.dev/guides/byok](https://helpbase.dev/guides/byok). ## Step 3 — Make a code change worth documenting From 913c958f40db58c5e4ad39b60292fa7423860612 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Sat, 18 Apr 2026 08:30:44 +0200 Subject: [PATCH 5/8] chore: add pnpm check:links script MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Greps the repo for `https://helpbase.dev/` URLs and HEAD-checks each. Fails on 4xx (broken), treats 401/403/405 as OK (auth-gated or method-gated endpoints are still real), warns on 5xx/timeouts. Exclusions cut noise: test dirs (negative-test fixtures point at fake URLs), planning docs (*_PLAN.md / *_PROMPT.md), CHANGELOG.md, lockfiles. Scheme-ful URLs only — bare `helpbase.dev` in comments isn't a clickable link. Not wired into CI yet — run manually with `pnpm check:links`. Would have caught the 9 broken `/docs/byok` references fixed in the previous commit. First run on main surfaces 9 real 404s not yet fixed: `/docs` (README Demo link), `/docs/cli` (HELPBASE.md template — ships to users), `/docs/troubleshooting#*` (generate.ts error hints ×5), `/account/tokens` (README), plus one bare `/errors` const and a magic-link placeholder. Left for a follow-up so this commit stays scoped. Co-Authored-By: Claude Opus 4.7 (1M context) --- package.json | 1 + scripts/check-links.sh | 132 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100755 scripts/check-links.sh diff --git a/package.json b/package.json index 202ac6e..c73b626 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "smoke:deploy": "bash scripts/smoke-deploy.sh", "eval:hosted-parity": "node packages/cli/eval/run-hosted-parity.mjs", "check:supabase-types": "node scripts/check-supabase-types.mjs", + "check:links": "bash scripts/check-links.sh", "sync:templates": "node scripts/sync-templates.mjs" }, "devDependencies": { diff --git a/scripts/check-links.sh b/scripts/check-links.sh new file mode 100755 index 0000000..9f7a84f --- /dev/null +++ b/scripts/check-links.sh @@ -0,0 +1,132 @@ +#!/usr/bin/env bash +# +# scripts/check-links.sh — Verify every `helpbase.dev/` URL in the +# repo actually resolves. Catches the bug class that shipped on +# 2026-04-17 (nine `helpbase.dev/docs/byok` references, all 404 because +# the real URL is `/guides/byok`). +# +# What this checks: any URL matching `helpbase.dev/` in source +# files (md, mdx, ts, tsx, json, yml, yaml). Bare `helpbase.dev` without +# a path is skipped (brand mention, not a link). +# +# What this skips: CHANGELOG.md (historical), pnpm-lock.yaml (no +# helpbase.dev links should live there anyway), node_modules, dist, .next. +# +# Exit codes: +# 0 — every URL returned 2xx or 3xx +# 1 — at least one URL returned 4xx / 5xx +# Timeouts and DNS failures print a warning but do NOT fail — transient +# network blips shouldn't block a local run. +# +# Usage: +# pnpm check:links # check against production +# LINK_CHECK_BASE=https://staging.helpbase.dev pnpm check:links +# LINK_CHECK_TIMEOUT=20 pnpm check:links # override 10s default + +set -uo pipefail + +BASE="${LINK_CHECK_BASE:-https://helpbase.dev}" +TIMEOUT="${LINK_CHECK_TIMEOUT:-10}" + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$REPO_ROOT" + +# Colors (respect NO_COLOR / non-TTY) +if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then + R=$'\033[31m'; G=$'\033[32m'; Y=$'\033[33m'; D=$'\033[2m'; B=$'\033[1m'; N=$'\033[0m' +else + R=""; G=""; Y=""; D=""; B=""; N="" +fi + +echo "${B}Checking helpbase.dev links${N} against ${D}${BASE}${N}" +echo + +# Extract every `https://helpbase.dev/` URL from source files. +# - Scheme-ful match only — bare `helpbase.dev` in comments + display text +# isn't a clickable link, so skipping it cuts false positives cleanly. +# - Strip trailing punctuation (period, comma, paren, bracket, quote). +# - Dedupe + sort. +# - Exclude test files (negative-test fixtures point at fake URLs) and +# planning docs (drafts at repo root that may reference TBD pages). +# (Using `while read` instead of `mapfile` so this works on macOS bash 3.2.) +URLS=() +while IFS= read -r line; do + [ -n "$line" ] && URLS+=("$line") +done < <( + grep -rohE 'https://helpbase\.dev/[A-Za-z0-9/_.?=&#%~-]+' \ + --include='*.md' --include='*.mdx' \ + --include='*.ts' --include='*.tsx' \ + --include='*.js' --include='*.mjs' --include='*.cjs' \ + --include='*.json' --include='*.yml' --include='*.yaml' \ + --exclude-dir=node_modules --exclude-dir=dist --exclude-dir=.next \ + --exclude-dir=.turbo --exclude-dir=.vercel --exclude-dir=.git \ + --exclude-dir=test --exclude-dir=tests --exclude-dir=__tests__ \ + --exclude='*.test.*' --exclude='*.spec.*' \ + --exclude='CHANGELOG.md' --exclude='pnpm-lock.yaml' --exclude='package-lock.json' \ + --exclude='*_PLAN.md' --exclude='*_PROMPT.md' --exclude='NEXT_SESSION_*.md' \ + . 2>/dev/null \ + | sed -E 's|[\.\,\;\:\)\]\}\"]+$||' \ + | grep -vE '/$' \ + | sort -u +) + +TOTAL=${#URLS[@]} +if [ "$TOTAL" -eq 0 ]; then + echo "${Y}No helpbase.dev links found in source files.${N} Nothing to check." + exit 0 +fi + +FAIL=0 +WARN=0 +PASS=0 + +for url in "${URLS[@]}"; do + # Rewrite the host if LINK_CHECK_BASE overrides the default. + probe="${url/https:\/\/helpbase.dev/$BASE}" + + # HEAD first. If the server doesn't allow HEAD (some static hosts), retry GET. + status=$(curl -sIo /dev/null -w '%{http_code}' \ + --max-time "$TIMEOUT" -L \ + -A 'helpbase-link-check/1.0' \ + "$probe" 2>/dev/null || echo "000") + + if [ "$status" = "405" ] || [ "$status" = "000" ]; then + # HEAD not allowed or network blip — try GET (discard body). + status=$(curl -so /dev/null -w '%{http_code}' \ + --max-time "$TIMEOUT" -L \ + -A 'helpbase-link-check/1.0' \ + "$probe" 2>/dev/null || echo "000") + fi + + case "$status" in + 2*|3*) + printf ' %s✓%s %s %s(%s)%s\n' "$G" "$N" "$url" "$D" "$status" "$N" + PASS=$((PASS + 1)) + ;; + 401|403|405) + # URL exists but is auth-gated or rejects HEAD — not a broken link. + printf ' %s✓%s %s %s(%s, exists)%s\n' "$G" "$N" "$url" "$D" "$status" "$N" + PASS=$((PASS + 1)) + ;; + 000|5*) + printf ' %s?%s %s %s(%s, transient?)%s\n' "$Y" "$N" "$url" "$D" "$status" "$N" + WARN=$((WARN + 1)) + ;; + *) + printf ' %s✗%s %s %s(%s)%s\n' "$R" "$N" "$url" "$D" "$status" "$N" + FAIL=$((FAIL + 1)) + ;; + esac +done + +echo +echo "${B}${TOTAL}${N} checked ${G}${PASS} ok${N} ${R}${FAIL} broken${N} ${Y}${WARN} timeouts${N}" + +if [ "$FAIL" -gt 0 ]; then + echo + echo "${R}FAIL${N}: at least one helpbase.dev link returned 4xx/5xx." + echo " Fix the source files that reference these URLs, or update the target page." + exit 1 +fi + +exit 0 From 6e74c217a6823acfde1c2f6b5717c02fa97b5d6d Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Sat, 18 Apr 2026 08:38:26 +0200 Subject: [PATCH 6/8] fix(links): resolve the 6 user-facing 404s check:links surfaced MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ships the follow-up cleanup hinted at in the previous commit. Every fix targets a URL that a real user would click (README badges, CLI error hints, HELPBASE.md in scaffolded projects), not a cosmetic one. - README.md:20 — Demo badge pointed at /docs (404). Now points at /getting-started/introduction (200), which is the canonical "what helpbase is" article for a first-time visitor. - README.md:295 — "Tokens are issued from helpbase.dev/account/tokens" was aspirational (the web dashboard isn't built yet). Replaced with the real workflow: helpbase login + jq the access_token out of ~/.helpbase/auth.json, set as HELPBASE_TOKEN secret in CI. - HELPBASE.md.template + synced template — "Full reference at helpbase.dev/docs/cli" → /cli/commands (200). This file ships into every scaffolded project, so the broken link was in every new user's repo. - packages/cli/src/commands/generate.ts — 7 stale /docs/troubleshooting#* URLs in error messages. 4 had matching /errors/e-* pages (remapped: #bad-frontmatter → e-invalid-frontmatter, #gateway-errors → e-llm-gateway). 3 were generic catchalls with no matching page (printRepoError, printScrapeError, generic printGenerateError) — the "Docs:" line is removed; the error already has Reason + Fix. - packages/create-helpbase/src/index.ts:297 — scaffolder outro banner's "Docs: helpbase.dev/docs" → /getting-started/introduction. - scripts/sync-templates.mjs:435 — the DEFAULT_HELPBASE_MD generator (fallback when no .template file exists) had the same /docs reference. Tooling additions: - scripts/check-links.sh now treats 429 (rate-limited) as "exists" and supports a .linkcheckignore file for known-template-base URLs. - .linkcheckignore lists 3 known false positives: ERROR_DOC_BASE const (template base, never linked directly) and two magic-link verify placeholder strings (illustrative prompt text + React Email preview fixture). Post-fix: 22/22 links pass, 0 broken. Was 9 broken two commits ago. Typecheck green. Shared (152/152) and scaffolder (31/31) tests green. Co-Authored-By: Claude Opus 4.7 (1M context) --- .linkcheckignore | 16 ++++++++++++++ README.md | 14 ++++++++++--- packages/cli/src/commands/generate.ts | 17 +++++++-------- packages/create-helpbase/HELPBASE.md.template | 2 +- packages/create-helpbase/src/index.ts | 2 +- .../create-helpbase/templates/HELPBASE.md | 2 +- scripts/check-links.sh | 21 +++++++++++++++++-- scripts/sync-templates.mjs | 2 +- 8 files changed, 57 insertions(+), 19 deletions(-) create mode 100644 .linkcheckignore diff --git a/.linkcheckignore b/.linkcheckignore new file mode 100644 index 0000000..e48dfdc --- /dev/null +++ b/.linkcheckignore @@ -0,0 +1,16 @@ +# .linkcheckignore — URLs that the grep picks up but aren't real links. +# One exact URL per line. Lines starting with `#` are comments. +# Consumed by scripts/check-links.sh. + +# ERROR_DOC_BASE const in packages/cli/src/lib/errors.ts. Used only as +# a template base: `${ERROR_DOC_BASE}/${code}` → /errors/e-foo (real). +# The bare string is never linked directly. +https://helpbase.dev/errors + +# Placeholder text in `helpbase login --email` prompt (login.ts). The +# endpoint exists; the shown `token=` value is illustrative only. +https://helpbase.dev/api/auth/magic-link/verify?token= + +# Default prop in the React Email preview component. Never sent to real +# users; only rendered in dev preview tooling. +https://helpbase.dev/api/auth/magic-link/verify?token=preview_token_1234567890abcdef diff --git a/README.md b/README.md index 1e2f472..be47fdd 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ built on shadcn/ui.
-**[Website](https://helpbase.dev)** · **[Demo](https://helpbase.dev/docs)** · **[Registry](https://helpbase.dev/r/help-center.json)** · **[@CodeHagen](https://x.com/CodeHagen)** +**[Website](https://helpbase.dev)** · **[Demo](https://helpbase.dev/getting-started/introduction)** · **[Registry](https://helpbase.dev/r/help-center.json)** · **[@CodeHagen](https://x.com/CodeHagen)** @@ -292,8 +292,16 @@ automatically; pass `--json` or `--quiet` to guarantee composable output. | `helpbase generate` | `--url ` (or `--repo `) + `--yes` | | `helpbase new` | `--type --title "..."` (optional `--category`, `--slug`) | -Tokens are issued from `https://helpbase.dev/account/tokens`. Export -once in CI and the CLI auths non-interactively for every command. +Grab a session token by running `helpbase login` locally, then reading +it from `~/.helpbase/auth.json`: + +```bash +jq -r .access_token ~/.helpbase/auth.json +``` + +Set the value as a `HELPBASE_TOKEN` secret in your CI and the CLI auths +non-interactively for every command. (A web dashboard for token management +is not yet live — cut one from the local file for now.) ## Shell completion diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.ts index 72a27d1..905e3b9 100644 --- a/packages/cli/src/commands/generate.ts +++ b/packages/cli/src/commands/generate.ts @@ -302,7 +302,7 @@ ${"ANTHROPIC_API_KEY"} / ${"OPENAI_API_KEY"} / ${"AI_GATEWAY_API_KEY"} (BYOK, fi `\n${pc.red("✖")} Generated file has invalid frontmatter: ${plan.filePath}\n` + ` Reason: ${parseErr instanceof Error ? parseErr.message : "parse error"}\n` + ` Fix: This is a bug in articleToMdx — please file an issue with the file contents.\n` + - ` Docs: https://helpbase.dev/docs/troubleshooting#bad-frontmatter\n`, + ` Docs: https://helpbase.dev/errors/e-invalid-frontmatter\n`, ) process.exit(1) } @@ -438,7 +438,7 @@ ${"ANTHROPIC_API_KEY"} / ${"OPENAI_API_KEY"} / ${"AI_GATEWAY_API_KEY"} (BYOK, fi `\n${pc.red("✖")} Generated file has invalid frontmatter: ${plan.filePath}\n` + ` Reason: ${parseErr instanceof Error ? parseErr.message : "parse error"}\n` + ` Fix: This is a bug in articleToMdx — please file an issue with the file contents.\n` + - ` Docs: https://helpbase.dev/docs/troubleshooting#bad-frontmatter\n`, + ` Docs: https://helpbase.dev/errors/e-invalid-frontmatter\n`, ) process.exit(1) } @@ -560,7 +560,7 @@ ${"ANTHROPIC_API_KEY"} / ${"OPENAI_API_KEY"} / ${"AI_GATEWAY_API_KEY"} (BYOK, fi `\n${pc.red("✖")} Generated file has invalid frontmatter: ${plan.filePath}\n` + ` Reason: ${parseErr instanceof Error ? parseErr.message : "parse error"}\n` + ` Fix: This is a bug in articleToMdx — please file an issue with the file contents.\n` + - ` Docs: https://helpbase.dev/docs/troubleshooting#bad-frontmatter\n`, + ` Docs: https://helpbase.dev/errors/e-invalid-frontmatter\n`, ) process.exit(1) } @@ -612,8 +612,7 @@ function printRepoError(repoPath: string, err: unknown): void { console.error( `\n${pc.red("✖")} Could not read repository ${pc.cyan(repoPath)}\n` + ` Reason: ${reason}\n` + - ` Fix: Pass a local path to a directory with markdown files (e.g. ${pc.cyan("--repo .")}).\n` + - ` Docs: https://helpbase.dev/docs/troubleshooting#generate-errors\n`, + ` Fix: Pass a local path to a directory with markdown files (e.g. ${pc.cyan("--repo .")}).\n`, ) } @@ -622,8 +621,7 @@ function printScrapeError(url: string, err: unknown): void { console.error( `\n${pc.red("✖")} Could not generate articles from ${pc.cyan(url)}\n` + ` Reason: ${reason}\n` + - ` Fix: Check the URL is accessible and try again.\n` + - ` Docs: https://helpbase.dev/docs/troubleshooting#generate-errors\n`, + ` Fix: Check the URL is accessible and try again.\n`, ) } @@ -659,7 +657,7 @@ function printGenerateError(err: unknown, opts?: { url?: string; repo?: string; ` Reason: ${err.message}\n` + ` Fix: Check the model ID is valid and your Gateway quota is not exhausted.\n` + ` Try ${pc.cyan("--test")} to use a cheap fallback model, or ${pc.cyan("--model ")} to override.\n` + - ` Docs: https://helpbase.dev/docs/troubleshooting#gateway-errors\n`, + ` Docs: https://helpbase.dev/errors/e-llm-gateway\n`, ) return } @@ -668,8 +666,7 @@ function printGenerateError(err: unknown, opts?: { url?: string; repo?: string; console.error( `\n${pc.red("✖")} Could not generate articles\n` + ` Reason: ${reason}\n` + - ` Fix: Check the source and try again.\n` + - ` Docs: https://helpbase.dev/docs/troubleshooting#generate-errors\n`, + ` Fix: Check the source and try again.\n`, ) } diff --git a/packages/create-helpbase/HELPBASE.md.template b/packages/create-helpbase/HELPBASE.md.template index 97595c9..eb45f6c 100644 --- a/packages/create-helpbase/HELPBASE.md.template +++ b/packages/create-helpbase/HELPBASE.md.template @@ -74,4 +74,4 @@ and OS. ## Full reference `helpbase --help` for any command. Full reference: -. +. diff --git a/packages/create-helpbase/src/index.ts b/packages/create-helpbase/src/index.ts index fd55124..9d79e59 100644 --- a/packages/create-helpbase/src/index.ts +++ b/packages/create-helpbase/src/index.ts @@ -294,7 +294,7 @@ async function run(directory: string | undefined, opts: RunOptions) { outro( `${pc.green("Your help center is ready!")}\n` + - ` Docs: ${pc.dim("https://helpbase.dev/docs")}`, + ` Docs: ${pc.dim("https://helpbase.dev/getting-started/introduction")}`, ) // 9. Start dev server + auto-open browser on "Ready" signal. diff --git a/packages/create-helpbase/templates/HELPBASE.md b/packages/create-helpbase/templates/HELPBASE.md index 97595c9..eb45f6c 100644 --- a/packages/create-helpbase/templates/HELPBASE.md +++ b/packages/create-helpbase/templates/HELPBASE.md @@ -74,4 +74,4 @@ and OS. ## Full reference `helpbase --help` for any command. Full reference: -. +. diff --git a/scripts/check-links.sh b/scripts/check-links.sh index 9f7a84f..f9efb21 100755 --- a/scripts/check-links.sh +++ b/scripts/check-links.sh @@ -70,6 +70,22 @@ done < <( | sort -u ) +# Apply .linkcheckignore (one URL per line, exact match, # for comments). +# Lets us allow-list known template bases like ERROR_DOC_BASE const, which +# reads as a bare URL in source but only ever renders as ${base}/${code}. +if [ -f .linkcheckignore ]; then + FILTERED=() + # Build a grep pattern of ignore URLs (exact-line match). + IGNORE=$(grep -vE '^\s*(#|$)' .linkcheckignore | sed 's|[][\.^$*]|\\&|g') + for url in "${URLS[@]}"; do + if [ -n "$IGNORE" ] && echo "$url" | grep -qxE "$(echo "$IGNORE" | tr '\n' '|' | sed 's|\|$||')"; then + continue + fi + FILTERED+=("$url") + done + URLS=("${FILTERED[@]}") +fi + TOTAL=${#URLS[@]} if [ "$TOTAL" -eq 0 ]; then echo "${Y}No helpbase.dev links found in source files.${N} Nothing to check." @@ -103,8 +119,9 @@ for url in "${URLS[@]}"; do printf ' %s✓%s %s %s(%s)%s\n' "$G" "$N" "$url" "$D" "$status" "$N" PASS=$((PASS + 1)) ;; - 401|403|405) - # URL exists but is auth-gated or rejects HEAD — not a broken link. + 401|403|405|429) + # URL exists but is auth-gated, rejects HEAD, or is rate-limited — + # not a broken link. printf ' %s✓%s %s %s(%s, exists)%s\n' "$G" "$N" "$url" "$D" "$status" "$N" PASS=$((PASS + 1)) ;; diff --git a/scripts/sync-templates.mjs b/scripts/sync-templates.mjs index 7dafa4b..0261db5 100644 --- a/scripts/sync-templates.mjs +++ b/scripts/sync-templates.mjs @@ -432,7 +432,7 @@ function writeTemplatesHelpbaseMd() { const DEFAULT_HELPBASE_MD = `# helpbase -This is your help center. See https://helpbase.dev/docs for the full guide. +This is your help center. See https://helpbase.dev/getting-started/introduction for the full guide. ` function generateTemplatesGitignore() { From df49bf16e58a6070ff26cdf1567e2106c2fa20ef Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Sat, 18 Apr 2026 08:42:26 +0200 Subject: [PATCH 7/8] fix(check-links): ignore file uses fixed-string match, not regex union MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /review caught it: the .linkcheckignore filter was building a pipe-joined regex union and only escaping [, ], ., ^, $, * — leaving ?, =, +, {, }, |, (, ) as regex metacharacters. URLs with query strings like `/verify?token=` matched nothing in the ignore list, so they leaked past the filter and only appeared as "exists" because helpbase.dev rate-limited (429) those probes, which /check-links treats as PASS. If the server stopped rate-limiting, those URLs would resurface as FAIL. Silent fragility in what's supposed to be a correctness gate. Fix: `printf '%s\n' "${URLS[@]}" | grep -F -x -v -f ` — fixed strings, exact line, invert match. URLs with any metacharacter now match literally. Confirmed with a debug run: 22 → 20 checked after the fix (the two magic-link placeholders now filtered properly instead of passing on rate-limit luck). Co-Authored-By: Claude Opus 4.7 (1M context) --- scripts/check-links.sh | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/scripts/check-links.sh b/scripts/check-links.sh index f9efb21..818b654 100755 --- a/scripts/check-links.sh +++ b/scripts/check-links.sh @@ -73,17 +73,22 @@ done < <( # Apply .linkcheckignore (one URL per line, exact match, # for comments). # Lets us allow-list known template bases like ERROR_DOC_BASE const, which # reads as a bare URL in source but only ever renders as ${base}/${code}. +# +# Uses `grep -F -x -v -f` (fixed strings, exact line, invert match, file-driven) +# so URLs with regex metacharacters like `?` or `=` match literally — building +# a regex union on the fly was broken for query-string URLs. if [ -f .linkcheckignore ]; then - FILTERED=() - # Build a grep pattern of ignore URLs (exact-line match). - IGNORE=$(grep -vE '^\s*(#|$)' .linkcheckignore | sed 's|[][\.^$*]|\\&|g') - for url in "${URLS[@]}"; do - if [ -n "$IGNORE" ] && echo "$url" | grep -qxE "$(echo "$IGNORE" | tr '\n' '|' | sed 's|\|$||')"; then - continue - fi - FILTERED+=("$url") - done - URLS=("${FILTERED[@]}") + # Strip comments + blank lines into a temp file grep can consume. + IGNORE_TMP=$(mktemp) + grep -vE '^\s*(#|$)' .linkcheckignore > "$IGNORE_TMP" || true + if [ -s "$IGNORE_TMP" ]; then + FILTERED=() + while IFS= read -r line; do + [ -n "$line" ] && FILTERED+=("$line") + done < <(printf '%s\n' "${URLS[@]}" | grep -F -x -v -f "$IGNORE_TMP" || true) + URLS=("${FILTERED[@]}") + fi + rm -f "$IGNORE_TMP" fi TOTAL=${#URLS[@]} From 647271972f7bade40428869a268f308df4139235 Mon Sep 17 00:00:00 2001 From: meglerhagen Date: Sat, 18 Apr 2026 08:43:51 +0200 Subject: [PATCH 8/8] fix(generate): restore Docs: line pointing at /cli/commands MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI caught it: removing the `Docs:` line from printRepoError, printScrapeError, and the generic printGenerateError catchall broke `generate.test.ts:48` and `cli.integration.test.ts:84`, both of which enforce the "every error has problem / cause / fix / docs" contract. Restored the line. Now points at https://helpbase.dev/cli/commands (200, confirmed by check-links) — the CLI command reference is a useful landing spot for a user hit with a generic scrape / repo-read / generate error. Was pointing at /docs/troubleshooting#generate-errors, which 404ed. Co-Authored-By: Claude Opus 4.7 (1M context) --- packages/cli/src/commands/generate.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.ts index 905e3b9..c41e458 100644 --- a/packages/cli/src/commands/generate.ts +++ b/packages/cli/src/commands/generate.ts @@ -612,7 +612,8 @@ function printRepoError(repoPath: string, err: unknown): void { console.error( `\n${pc.red("✖")} Could not read repository ${pc.cyan(repoPath)}\n` + ` Reason: ${reason}\n` + - ` Fix: Pass a local path to a directory with markdown files (e.g. ${pc.cyan("--repo .")}).\n`, + ` Fix: Pass a local path to a directory with markdown files (e.g. ${pc.cyan("--repo .")}).\n` + + ` Docs: https://helpbase.dev/cli/commands\n`, ) } @@ -621,7 +622,8 @@ function printScrapeError(url: string, err: unknown): void { console.error( `\n${pc.red("✖")} Could not generate articles from ${pc.cyan(url)}\n` + ` Reason: ${reason}\n` + - ` Fix: Check the URL is accessible and try again.\n`, + ` Fix: Check the URL is accessible and try again.\n` + + ` Docs: https://helpbase.dev/cli/commands\n`, ) } @@ -666,7 +668,8 @@ function printGenerateError(err: unknown, opts?: { url?: string; repo?: string; console.error( `\n${pc.red("✖")} Could not generate articles\n` + ` Reason: ${reason}\n` + - ` Fix: Check the source and try again.\n`, + ` Fix: Check the source and try again.\n` + + ` Docs: https://helpbase.dev/cli/commands\n`, ) }