doccupine 0.0.160 → 0.0.162

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -309,7 +309,7 @@ If `LLM_PROVIDER` is not set, the chat component is hidden automatically.
309
309
  ### Optional overrides
310
310
 
311
311
  ```env
312
- LLM_CHAT_MODEL=gpt-4.1-mini # Override the default chat model
312
+ LLM_CHAT_MODEL=gpt-6-luna # Override the default chat model
313
313
  LLM_EMBEDDING_MODEL=text-embedding-3-small # Override the default embedding model
314
314
  LLM_TEMPERATURE=0 # Set temperature (default: 0; "default" sends none)
315
315
  LLM_EMBEDDING_DIMS=512 # Dimensions for the prebuilt search index (default: 512)
@@ -317,7 +317,7 @@ RAG_RUNTIME_EMBED_MAX_CHUNKS=400 # Max chunks embedded on demand in
317
317
  # RAG_API_KEY=... # Optional bearer auth for direct /api/rag requests
318
318
  ```
319
319
 
320
- `LLM_TEMPERATURE` accepts 0 to 1 for Anthropic and 0 to 2 for OpenAI and Google; an invalid value is ignored with a warning. OpenAI's reasoning models (`o3`, `o4-mini`) and its GPT-5 models onwards reject a custom temperature, so none is sent to them.
320
+ `LLM_TEMPERATURE` accepts 0 to 2; an invalid value is ignored with a warning. It only applies to models that still take a custom temperature, such as `gpt-4.1` or `gemini-2.5-flash`, so none of the default models gets one. No temperature is sent to Anthropic, whose current API version rejects it on every model, to OpenAI's reasoning models (`o3`, `o4-mini`) and its GPT-5 models onwards, or to Gemini 3.5 models onwards, which ignore it.
321
321
 
322
322
  `LLM_EMBEDDING_DIMS` Matryoshka-truncates document vectors so the prebuilt search index stays small; lower values shrink the index at a slight cost to recall. `RAG_RUNTIME_EMBED_MAX_CHUNKS` caps how many chunks the chat will embed on demand in production before requiring a prebuilt index (it's unlimited under `next dev`).
323
323
 
@@ -325,11 +325,11 @@ Public documentation leaves browser chat available by default. Setting `RAG_API_
325
325
 
326
326
  Default models per provider:
327
327
 
328
- | Provider | Chat model | Embedding model |
329
- | --------- | ---------------------------- | ------------------------ |
330
- | OpenAI | `gpt-4.1-mini` | `text-embedding-3-small` |
331
- | Anthropic | `claude-sonnet-4-5-20250929` | OpenAI fallback |
332
- | Google | `gemini-2.5-flash-lite` | `gemini-embedding-001` |
328
+ | Provider | Chat model | Embedding model |
329
+ | --------- | ----------------------- | ------------------------ |
330
+ | OpenAI | `gpt-6-luna` | `text-embedding-3-small` |
331
+ | Anthropic | `claude-haiku-5-5` | OpenAI fallback |
332
+ | Google | `gemini-3.5-flash-lite` | `gemini-embedding-001` |
333
333
 
334
334
  ## MCP Server
335
335
 
@@ -85,6 +85,7 @@ import { docsContentStubTemplate } from "../templates/services/mcp/docsContentSt
85
85
  import { llmConfigTemplate } from "../templates/services/llm/config.js";
86
86
  import { llmFactoryTemplate } from "../templates/services/llm/factory.js";
87
87
  import { llmIndexTemplate } from "../templates/services/llm/index.js";
88
+ import { llmStreamTemplate } from "../templates/services/llm/stream.js";
88
89
  import { llmTypesTemplate } from "../templates/services/llm/types.js";
89
90
  import { buildDocsIndexScriptTemplate } from "../templates/scripts/build-docs-index.js";
90
91
  import { posthogServerTemplate } from "../templates/lib/posthog.js";
@@ -202,6 +203,7 @@ export const appStructure = {
202
203
  "services/llm/config.ts": llmConfigTemplate,
203
204
  "services/llm/factory.ts": llmFactoryTemplate,
204
205
  "services/llm/index.ts": llmIndexTemplate,
206
+ "services/llm/stream.ts": llmStreamTemplate,
205
207
  "services/llm/types.ts": llmTypesTemplate,
206
208
  "services/openapi/playground-allowlist.json": playgroundAllowlistStubTemplate,
207
209
  "scripts/build-docs-index.mts": buildDocsIndexScriptTemplate,
@@ -1 +1 @@
1
- export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { resolveDocsFilter } from \"@/services/mcp/tools\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// Covers the schema's worst-case UTF-8 payload while retaining a hard cap.\nconst MAX_RAG_REQUEST_BYTES = 512 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\n\n// A language code or version slug is a lowercase URL segment.\nconst variantTokenSchema = z\n .string()\n .regex(/^[a-z0-9-]{1,32}$/)\n .optional();\n\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n locale: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history, locale, version } = parsed.data;\n // Retrieval stays inside the language/version the reader is looking at.\n const docsFilter = resolveDocsFilter({ language: locale, version });\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal, docsFilter);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunk?.content || \"\";\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
1
+ export declare const ragRoutesTemplate = "import { NextResponse } from \"next/server\";\nimport { z } from \"zod\";\nimport { getLLMConfig, createChatModel, chunkText } from \"@/services/llm\";\nimport {\n searchDocs,\n ensureDocsIndex,\n getIndexStatus,\n} from \"@/services/mcp/server\";\nimport { resolveDocsFilter } from \"@/services/mcp/tools\";\nimport { rateLimit } from \"@/utils/rateLimit\";\nimport { config } from \"@/utils/config\";\nimport { isSiteRequestAuthorized } from \"@/lib/access\";\nimport { timingSafeEqual } from \"@/lib/siteGate\";\nimport { readJsonBody, RequestTooLargeError } from \"@/utils/requestBody\";\n\n// Covers the schema's worst-case UTF-8 payload while retaining a hard cap.\nconst MAX_RAG_REQUEST_BYTES = 512 * 1024;\n\nconst messageSchema = z\n .object({\n role: z.enum([\"user\", \"assistant\"]),\n content: z.string().max(4000),\n })\n .strict();\n\n// A language code or version slug is a lowercase URL segment.\nconst variantTokenSchema = z\n .string()\n .regex(/^[a-z0-9-]{1,32}$/)\n .optional();\n\nconst ragSchema = z\n .object({\n question: z.string().min(1).max(2000),\n history: z.array(messageSchema).max(20).optional(),\n locale: variantTokenSchema,\n version: variantTokenSchema,\n })\n .strict();\n\nfunction bearerToken(req: Request): string | null {\n const authorization = req.headers.get(\"authorization\");\n return authorization?.startsWith(\"Bearer \")\n ? authorization.slice(\"Bearer \".length)\n : null;\n}\n\nasync function isRagRequestAuthorized(req: Request): Promise<boolean> {\n const siteAuthorized = await isSiteRequestAuthorized();\n if (process.env.SITE_PASSWORD && siteAuthorized) return true;\n\n const apiKey = process.env.RAG_API_KEY;\n if (apiKey) {\n const token = bearerToken(req);\n return token !== null && timingSafeEqual(token, apiKey);\n }\n return siteAuthorized;\n}\n\nconst projectName = config.name || \"Doccupine\";\n\nconst systemContext = `You are AI Assistant, a documentation assistant for ${projectName}, Your name is ${projectName} AI Assistant.\n\n## Core Rules\n1. Answer ONLY from the provided context. Never fabricate information.\n2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.\n3. If the question is ambiguous, ask a brief clarifying question before answering.\n\n## Response Style\n- Be concise and direct. Lead with the answer, then provide details if needed.\n- Use code examples from the context when relevant.\n- Match the technical level of the user's question.\n\n## MDX/Code Formatting\nWhen including code blocks in your response:\n- Never nest fenced code blocks (triple backticks) inside other fenced code blocks.\n- If you need to show MDX source that itself contains code blocks, use indented code blocks or escape the inner backticks.\n- All output must be valid MDX that renders correctly.\n\n## Internal Links\nEach context chunk includes a \"URL:\" line with the pre-computed page URL. Use it directly when linking:\n- Format links as markdown: [Page Title](/slug/).\n- Never expose raw file paths like \"/app/.../page.tsx\" to the user.\n- Never include route group segments in parentheses, like \"(site)\", in any link - they are internal directory names and do not exist in real URLs. Use \"/code/\" not \"/(site)/code/\".\n- Do NOT add a \"Related Pages\" section at the end - sources are shown separately by the UI.\n\n## Greetings & Small Talk\nIf the user sends a greeting or non-documentation question, respond briefly and ask how you can help with the documentation.`;\n\n// Maps provider/stream failures to fixed visitor-safe messages. Raw provider\n// errors can include API-key fragments, org ids, and billing URLs, so only\n// these strings ever reach the client; the full error goes to the server log.\nfunction friendlyLLMError(error: unknown): string {\n const raw = error instanceof Error ? error.message : String(error);\n if (/\\b401\\b|api.?key|authenticat|unauthorized/i.test(raw)) {\n return \"The assistant's model provider rejected its API key. If you are the site owner, check the server logs and your API key configuration.\";\n }\n if (/\\b429\\b|quota|rate.?limit|billing/i.test(raw)) {\n return \"The assistant's model provider is rate limiting requests right now. Please try again in a moment.\";\n }\n if (\n /timed?.?out|ETIMEDOUT|ECONNRESET|ENOTFOUND|fetch failed|network/i.test(raw)\n ) {\n return \"The assistant could not reach its model provider. Please try again.\";\n }\n return \"The assistant hit an unexpected error. Please try again.\";\n}\n\n// LangChain + the MCP SDK require the Node.js runtime (not edge).\nexport const runtime = \"nodejs\";\n// Safety net for the streaming function (Vercel-only; ignored elsewhere).\n// The heartbeat below, not this value, is what prevents proxy 524 timeouts.\nexport const maxDuration = 60;\n\nexport async function POST(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const { allowed, retryAfter } = rateLimit(req);\n if (!allowed) {\n return NextResponse.json(\n { error: \"Too many requests\" },\n { status: 429, headers: { \"Retry-After\": String(retryAfter) } },\n );\n }\n\n // Validate the request up front so genuine client/config errors still return\n // real status codes before we commit to a 200 streaming response.\n let body: unknown;\n try {\n body = await readJsonBody(req, MAX_RAG_REQUEST_BYTES);\n } catch (error: unknown) {\n if (req.signal.aborted) throw error;\n if (error instanceof RequestTooLargeError) {\n return NextResponse.json(\n { error: \"Request body too large\" },\n { status: 413 },\n );\n }\n return NextResponse.json({ error: \"Invalid JSON body\" }, { status: 400 });\n }\n\n const parsed = ragSchema.safeParse(body);\n if (!parsed.success) {\n return NextResponse.json(\n { error: \"Invalid input\", details: parsed.error.issues },\n { status: 400 },\n );\n }\n const { question, history, locale, version } = parsed.data;\n // Retrieval stays inside the language/version the reader is looking at.\n const docsFilter = resolveDocsFilter({ language: locale, version });\n\n let llmConfig;\n try {\n llmConfig = getLLMConfig();\n } catch (error: unknown) {\n // Setup details (provider names, env var names) stay in the server log.\n console.error(\"[doccupine] LLM configuration error:\", error);\n return NextResponse.json(\n {\n error:\n \"The AI assistant is not configured on this site. If you are the site owner, check the server logs.\",\n },\n { status: 500 },\n );\n }\n\n const encoder = new TextEncoder();\n let heartbeat: ReturnType<typeof setInterval> | null = null;\n let streamClosed = false;\n const workController = new AbortController();\n const abortWork = () => workController.abort(req.signal.reason);\n req.signal.addEventListener(\"abort\", abortWork, { once: true });\n if (req.signal.aborted) abortWork();\n const { signal } = workController;\n\n // Return the streaming response immediately and do ALL slow work (indexing,\n // search, model streaming) inside start(). This flushes headers + a first\n // byte right away so edge proxies never hit their time-to-first-byte timeout.\n const readableStream = new ReadableStream({\n async start(controller) {\n const safeEnqueue = (payload: string) => {\n if (streamClosed) return;\n try {\n controller.enqueue(encoder.encode(payload));\n } catch {\n // Stream already closed or cancelled - stop emitting.\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n }\n };\n\n // Keep the connection alive while the index and model warm up.\n heartbeat = setInterval(() => safeEnqueue(`: keep-alive\\n\\n`), 15000);\n\n try {\n // First byte, before any slow work - satisfies the proxy TTFB window.\n safeEnqueue(`: connected\\n\\n`);\n\n // Ensure docs are indexed (loads precomputed embeddings when present).\n await ensureDocsIndex(false, signal);\n signal.throwIfAborted();\n\n // Use MCP search_docs tool to find relevant documentation\n const searchResults = await searchDocs(question, 6, signal, docsFilter);\n signal.throwIfAborted();\n\n // Build context from search results\n const context = searchResults\n .map(({ chunk, score }) => {\n const slug = chunk.uri.replace(\"docs://\", \"\").replace(/^\\/+/, \"\");\n const url = slug ? `/${slug}/` : \"/\";\n return `File: ${chunk.path}\\nURL: ${url}\\nScore: ${score.toFixed(3)}\\n----\\n${chunk.text}`;\n })\n .join(\"\\n\\n================\\n\\n\");\n\n // Build metadata from MCP search results and send it before the answer.\n const indexStatus = getIndexStatus();\n const metadata = {\n sources: searchResults.map(({ chunk, score }) => ({\n id: chunk.id,\n path: chunk.path,\n uri: chunk.uri,\n score,\n })),\n chunkCount: indexStatus.chunkCount,\n };\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"metadata\", data: metadata })}\\n\\n`,\n );\n\n // Assemble the prompt, including conversation history for multi-turn.\n const prompt: {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n }[] = [\n {\n role: \"system\" as const,\n content: systemContext,\n },\n ];\n if (history && history.length > 0) {\n for (const msg of history) {\n prompt.push({\n role: msg.role,\n content: msg.content,\n });\n }\n }\n prompt.push({\n role: \"user\" as const,\n content: `Question: ${question}\\n\\nContext:\\n${context}`,\n });\n\n // Create chat model and stream the response.\n const llm = createChatModel(llmConfig);\n const stream = await llm.stream(prompt, { signal });\n for await (const chunk of stream) {\n signal.throwIfAborted();\n const content = chunkText(chunk);\n if (content) {\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"content\", data: content })}\\n\\n`,\n );\n }\n }\n\n signal.throwIfAborted();\n safeEnqueue(`data: ${JSON.stringify({ type: \"done\" })}\\n\\n`);\n } catch (error: unknown) {\n if (signal.aborted) return;\n console.error(\"[doccupine] RAG stream error:\", error);\n safeEnqueue(\n `data: ${JSON.stringify({ type: \"error\", data: friendlyLLMError(error) })}\\n\\n`,\n );\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n streamClosed = true;\n req.signal.removeEventListener(\"abort\", abortWork);\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n }\n },\n cancel() {\n streamClosed = true;\n workController.abort();\n if (heartbeat) clearInterval(heartbeat);\n },\n });\n\n return new Response(readableStream, {\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n },\n });\n}\n\nexport async function GET(req: Request) {\n if (!(await isRagRequestAuthorized(req))) {\n return NextResponse.json({ error: \"Unauthorized\" }, { status: 401 });\n }\n\n const status = getIndexStatus();\n return NextResponse.json({\n ready: status.ready,\n chunks: status.chunkCount,\n reason: status.reason,\n });\n}\n";
@@ -1,6 +1,6 @@
1
1
  export const ragRoutesTemplate = `import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
- import { getLLMConfig, createChatModel } from "@/services/llm";
3
+ import { getLLMConfig, createChatModel, chunkText } from "@/services/llm";
4
4
  import {
5
5
  searchDocs,
6
6
  ensureDocsIndex,
@@ -260,7 +260,7 @@ export async function POST(req: Request) {
260
260
  const stream = await llm.stream(prompt, { signal });
261
261
  for await (const chunk of stream) {
262
262
  signal.throwIfAborted();
263
- const content = chunk?.content || "";
263
+ const content = chunkText(chunk);
264
264
  if (content) {
265
265
  safeEnqueue(
266
266
  \`data: \${JSON.stringify({ type: "content", data: content })}\\n\\n\`,
@@ -1 +1 @@
1
- export declare const docsComponentsTemplate = "\"use client\";\nimport React, { createContext } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport {\n Button,\n resetButton,\n styledSmall,\n styledStrong,\n styledText,\n useChat,\n} from \"cherry-styled-components\";\nimport Link from \"next/link\";\nimport { mq, Theme } from \"@/app/theme\";\nimport {\n focusModeColumn,\n focusModeHide,\n sidePanelOffset,\n styledAnchor,\n styledTable,\n stylesLists,\n} from \"@/components/layout/SharedStyled\";\nimport { Badge } from \"@/components/layout/Badge\";\nimport { useVariant } from \"@/components/useVariant\";\nimport { joinVariantSlug } from \"@/utils/variants\";\n\nconst SectionBarContext = createContext(false);\n\nfunction SectionBarProvider({\n hasSectionBar,\n children,\n}: {\n hasSectionBar: boolean;\n children: React.ReactNode;\n}) {\n return (\n <SectionBarContext.Provider value={hasSectionBar}>\n {children}\n </SectionBarContext.Provider>\n );\n}\n\ninterface DocsProps {\n children: React.ReactNode;\n}\n\nconst StyledDocsWrapper = styled.div<{ theme: Theme }>`\n position: relative;\n`;\n\nconst StyledDocsSidebar = styled.div<{ theme: Theme }>`\n clear: both;\n`;\n\n// The <main> landmark wraps only the article content: the sidebar, footer,\n// and nav render outside it so content extractors and assistive tech start at\n// the article.\nconst StyledDocsContainer = styled.main<{\n theme: Theme;\n $isChatOpen?: boolean;\n}>`\n position: relative;\n padding: 0 20px 100px 20px;\n width: 100%;\n ${({ theme }) => styledText(theme)};\n transition: all 0.3s ease;\n\n ${mq(\"lg\")} {\n padding: 0 300px 80px 300px;\n\n ${({ $isChatOpen }) =>\n $isChatOpen &&\n css`\n padding: 0 440px 80px 300px;\n `}\n }\n\n ${sidePanelOffset};\n ${({ $isChatOpen }) => !$isChatOpen && focusModeColumn};\n\n & p {\n color: ${({ theme }) => theme.colors.grayDark};\n hyphens: auto;\n }\n\n & pre {\n max-width: 100%;\n }\n\n ${styledAnchor};\n ${stylesLists};\n ${styledTable};\n\n & img,\n & video,\n & iframe {\n max-width: 100%;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n }\n\n & code:not([class]),\n & kbd {\n max-width: max-content;\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n overflow-wrap: anywhere;\n }\n\n & .lucide {\n color: ${({ theme }) => theme.colors.primary};\n }\n\n & .aspect-video {\n aspect-ratio: 16 / 9;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n }\n`;\n\nexport const StyledMarkdownContainer = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n flex: 1;\n max-width: 640px;\n margin: auto;\n`;\n\ninterface Props {\n theme?: Theme;\n $isActive?: boolean;\n $isOpen?: boolean;\n $hasSectionBar?: boolean;\n}\n\nexport const StyledSidebar = styled.nav<Props>`\n position: fixed;\n overflow-y: auto;\n max-height: calc(\n 100dvh - ${({ $hasSectionBar }) => ($hasSectionBar ? 104 : 62)}px\n );\n width: 100%;\n z-index: 99;\n top: ${({ $hasSectionBar }) => ($hasSectionBar ? 104 : 62)}px;\n height: 100%;\n padding: 20px;\n opacity: 0;\n pointer-events: none;\n visibility: hidden;\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0.3s;\n transform: translateY(30px);\n left: 0;\n background: ${({ theme }) => theme.colors.light};\n -webkit-overflow-scrolling: touch;\n display: flex;\n flex-direction: column;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${mq(\"lg\")} {\n border-right: solid 1px ${({ theme }) => theme.colors.grayLight};\n transition: none;\n max-height: 100dvh;\n padding: 82px 20px 20px 20px;\n opacity: 1;\n pointer-events: all;\n visibility: visible;\n transform: translateY(0);\n /* Mixed over the page background rather than transparent so the panel\n reads as a filled surface in both modes. */\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 8%, ${theme.colors.light})`};\n top: 0;\n width: 280px;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n transform: translateY(0);\n opacity: 1;\n pointer-events: all;\n visibility: visible;\n transition-delay: 0s;\n `}\n\n ${focusModeHide(\"left\")};\n\n ${mq(\"lg\")} {\n html[data-focus-mode] & {\n visibility: hidden;\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0.3s;\n }\n }\n`;\n\n// One row of 30px controls: the focus-mode toggle, the language and version\n// switchers, then the theme toggle. The focus toggle is fixed rather than a\n// child (it outlives the sidebar in focus mode), so on the rail the row's own\n// padding leaves its 30px plus a gap free at the left.\nexport const StyledSidebarFooter = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 22px 20px;\n position: sticky;\n border-top: 1px solid ${({ theme }) => theme.colors.grayLight};\n /* Same opaque mix as the sidebar panel so the sticky footer blends into it\n while still masking the list scrolling underneath. */\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 8%, ${theme.colors.light})`};\n margin: 0 -20px -20px;\n bottom: -20px;\n\n ${mq(\"lg\")} {\n padding: 16px 20px 16px 58px;\n }\n`;\n\n// The theme toggle's slot takes whatever the switchers leave, so the toggle\n// stays beside them in the mobile menu and holds the right end of the rail.\n// A plain flex row rather than Cherry's Flex: the slot has to grow, which is a\n// property of the child, and styled(Flex) would swallow Flex's own $-prefixed\n// props on the way through.\nexport const StyledSidebarFooterToggle = styled.div`\n display: flex;\n flex: 1;\n justify-content: flex-start;\n\n /* On the rail the switchers claim the free width when both are configured,\n so the toggle keeps its own size and is pushed to the right end. */\n ${mq(\"lg\")} {\n flex: 0 0 auto;\n margin-left: auto;\n }\n`;\n\nexport const StyledIndexSidebar = styled.ul<{ theme: Theme }>`\n display: none;\n list-style: none;\n margin: 0;\n padding: 0;\n position: fixed;\n top: 0;\n right: 0;\n width: 280px;\n height: 100dvh;\n overflow-y: auto;\n z-index: 1;\n padding: 82px 20px 20px 20px;\n background: ${({ theme }) => theme.colors.light};\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n -webkit-overflow-scrolling: touch;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${mq(\"lg\")} {\n display: block;\n }\n\n & li {\n padding: 5px 0;\n }\n\n ${focusModeHide(\"right\")};\n\n ${mq(\"lg\")} {\n html[data-focus-mode] & {\n visibility: hidden;\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0.3s;\n }\n }\n`;\n\nexport const StyledIndexSidebarLabel = styled.span<{ theme: Theme }>`\n ${({ theme }) => styledSmall(theme)};\n color: ${({ theme }) => theme.colors.grayDark};\n`;\n\nexport const StyledIndexSidebarLi = styled.li<{\n theme: Theme;\n $isActive: boolean;\n}>`\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n left: 0;\n height: 20px;\n width: 1px;\n background: transparent;\n transition: all 0.3s ease;\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n &::before {\n background: ${theme.colors.primary};\n }\n `}\n`;\n\nexport const StyledIndexSidebarLink = styled.a<{\n theme: Theme;\n $isActive: boolean;\n}>`\n ${({ theme }) => styledSmall(theme)};\n color: ${({ theme, $isActive }) =>\n $isActive ? theme.colors.primary : theme.colors.dark};\n font-weight: ${({ $isActive }) => ($isActive ? \"600\" : \"400\")};\n text-decoration: none;\n transition: all 0.3s ease;\n\n &:hover {\n color: ${({ theme }) => theme.colors.primary};\n }\n`;\n\nexport const StyledSidebarList = styled.ul`\n list-style: none;\n margin: 0;\n padding: 0;\n\n &:last-of-type {\n margin-bottom: auto;\n }\n`;\n\nexport const StyledStrong = styled.strong<{ theme: Theme }>`\n font-weight: 600;\n ${({ theme }) => styledStrong(theme)};\n color: ${({ theme }) => theme.colors.accentStrong};\n display: inline-flex;\n align-items: center;\n gap: 8px;\n\n & svg {\n flex-shrink: 0;\n }\n`;\n\nexport const StyledSidebarListItem = styled.li`\n display: flex;\n gap: 10px;\n clear: both;\n`;\n\n// Shared appearance for every sidebar row - leaf links AND nested group\n// headers - so hover, active state, and the left rail read identically.\nconst sidebarRowStyles = css<Props>`\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: 1.6;\n color: ${({ theme }) => theme.colors.accentMuted};\n padding: 5px 0 5px 20px;\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-width: 0;\n transition: all 0.3s ease;\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n\n & svg {\n flex-shrink: 0;\n }\n\n &:hover {\n color: ${({ theme }) => theme.colors.accent};\n border-color: ${({ theme }) => theme.colors.primary};\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n color: ${theme.colors.accentStrong};\n border-color: ${theme.colors.primary};\n font-weight: 600;\n `};\n`;\n\n// The collapse chevron points right when closed and rotates to point down\n// when the group is open.\nconst sidebarChevron = css<Props>`\n & .lucide-chevron-right {\n margin-left: auto;\n transition: transform 0.3s ease;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n transform: rotate(90deg);\n `}\n }\n`;\n\nexport const StyledSidebarListItemLink = styled(Link)<Props>`\n ${sidebarRowStyles};\n`;\n\n// Compact HTTP-method label shown before a generated API endpoint link, colored\n// by verb so endpoints are scannable in the sidebar. Only rendered when a link\n// carries an `httpMethod` (endpoint pages do; hand-written pages do not).\n// The look is Badge's mono variation (tinted, solid when active); only\n// sidebar metrics are adjusted here.\nexport const StyledSidebarMethodTag = styled(Badge)`\n flex-shrink: 0;\n font-size: 9px;\n letter-spacing: 0.02em;\n padding: 1px 4px;\n border: none;\n`;\n\n// Nested navigation group. The header shares the link appearance/hover; a\n// non-navigable group is a single toggle button, while a group that is also a\n// page pairs a link with a chevron toggle. Children live in\n// StyledSidebarGroupContent, which animates open/closed via height 0 <-> auto\n// (enabled by interpolate-size in GlobalStyles, same as the Accordion).\nexport const StyledSidebarGroupButton = styled(Button)<Props>`\n ${resetButton};\n ${sidebarRowStyles};\n ${sidebarChevron};\n width: 100%;\n height: auto;\n min-height: 0;\n text-align: left;\n\n /* Buttons aren't covered by the global a:focus-visible ring, so this\n nav-row toggle carries its own copy of it. */\n &:focus-visible {\n outline: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n`;\n\nexport const StyledSidebarGroupRow = styled.div<Props>`\n ${sidebarRowStyles};\n ${sidebarChevron};\n\n /* The row is a plain div, so it never matches :focus-visible itself. Ring the\n whole row when its inner link or chevron takes keyboard focus instead, to\n match the leaf-row focus treatment. */\n &:has(:focus-visible) {\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n`;\n\nexport const StyledSidebarGroupLink = styled(Link)`\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-width: 0;\n color: inherit;\n text-decoration: none;\n\n & svg {\n flex-shrink: 0;\n }\n\n /* Ring is drawn on the parent row via :has(:focus-visible); suppress the\n global a:focus-visible glow so it isn't drawn twice. */\n &:focus-visible {\n outline: none;\n box-shadow: none;\n }\n`;\n\nexport const StyledSidebarGroupChevron = styled(Button)`\n ${resetButton};\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n width: auto;\n height: auto;\n min-height: 0;\n padding: 0;\n border: 0;\n background: none;\n color: inherit;\n cursor: pointer;\n\n /* Ring is drawn on the parent row via :has(:focus-visible). */\n &:focus-visible {\n outline: none;\n }\n`;\n\nexport const StyledSidebarGroupContent = styled.ul.attrs<Props>(\n ({ $isOpen }) => ({\n \"aria-hidden\": !$isOpen,\n inert: !$isOpen,\n }),\n)<Props>`\n list-style: none;\n margin: 0;\n padding: 0;\n height: 0;\n overflow: clip;\n visibility: hidden;\n transition:\n height 0.3s ease,\n visibility 0s linear 0.3s;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n height: auto;\n visibility: visible;\n transition-delay: 0s;\n `}\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n`;\n\nexport const StyleMobileBar = styled(Button)<Props>`\n ${resetButton};\n position: fixed;\n z-index: 999;\n bottom: 0;\n right: 20px;\n font-size: ${({ theme }) => theme.fontSizes.strong.lg};\n line-height: ${({ theme }) => theme.fontSizes.strong.lg};\n box-shadow: ${({ theme }) => theme.shadows.sm};\n background: ${({ theme }) => theme.colors.primary};\n color: ${({ theme }) => theme.colors.surface};\n backdrop-filter: blur(10px);\n -webkit-backdrop-filter: blur(10px);\n padding: 10px;\n border-radius: 100px;\n margin: 0 0 20px 0;\n font-weight: 600;\n display: flex;\n justify-content: flex-start;\n width: auto;\n height: auto;\n min-height: 0;\n\n ${mq(\"lg\")} {\n display: none;\n }\n\n ${({ $isActive }) => $isActive && `position: fixed;`};\n`;\n\nexport const StyledMobileBurger = styled.span<Props>`\n display: block;\n margin: auto 0;\n width: 18px;\n height: 18px;\n position: relative;\n overflow: hidden;\n background: transparent;\n position: relative;\n transform: scale(0.8);\n\n &::before,\n &::after {\n content: \"\";\n display: block;\n position: absolute;\n width: 18px;\n height: 3px;\n border-radius: 3px;\n background: ${({ theme }) => theme.colors.surface};\n transition: all 0.3s ease;\n }\n\n &::before {\n top: 3px;\n }\n\n &::after {\n bottom: 3px;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n &::before {\n transform: translateY(5px) rotate(45deg);\n }\n\n &::after {\n transform: translateY(-4px) rotate(-45deg);\n }\n `};\n`;\n\n// Visually hidden but present for crawlers and agents: points at llms.txt and\n// the .md mirrors. Rendered as the first element of the site layout.\nconst StyledLlmsDirective = styled.div`\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n border: 0;\n`;\n\nfunction LlmsDirective() {\n // Every language and version has its own llms.txt under its URL prefix.\n const { prefix } = useVariant();\n const indexHref = \"/\" + joinVariantSlug(prefix, \"llms.txt\");\n const fullHref = \"/\" + joinVariantSlug(prefix, \"llms-full.txt\");\n return (\n <StyledLlmsDirective data-markdown-ignore>\n <a href={indexHref}>Documentation index for AI agents (llms.txt)</a>.\n Markdown versions of every page are available by appending .md to the page\n URL. The full corpus is at <a href={fullHref}>{fullHref}</a>.\n </StyledLlmsDirective>\n );\n}\n\ninterface DocsWrapperProps {\n children: React.ReactNode;\n}\n\nfunction DocsWrapper({ children }: DocsWrapperProps) {\n return <StyledDocsWrapper>{children}</StyledDocsWrapper>;\n}\n\nfunction DocsSidebar({ children }: DocsProps) {\n return <StyledDocsSidebar>{children}</StyledDocsSidebar>;\n}\n\nfunction DocsContainer({ children, lang }: DocsProps & { lang?: string }) {\n const { isOpen } = useChat();\n\n return (\n <StyledDocsContainer $isChatOpen={isOpen} lang={lang}>\n {children}\n </StyledDocsContainer>\n );\n}\n\nexport {\n DocsWrapper,\n DocsSidebar,\n DocsContainer,\n LlmsDirective,\n SectionBarContext,\n SectionBarProvider,\n};\n";
1
+ export declare const docsComponentsTemplate = "\"use client\";\nimport React, { createContext } from \"react\";\nimport styled, { css } from \"styled-components\";\nimport {\n Button,\n resetButton,\n styledSmall,\n styledStrong,\n styledText,\n useChat,\n} from \"cherry-styled-components\";\nimport Link from \"next/link\";\nimport { mq, Theme } from \"@/app/theme\";\nimport {\n focusModeColumn,\n focusModeHide,\n sidePanelOffset,\n styledAnchor,\n styledTable,\n stylesLists,\n} from \"@/components/layout/SharedStyled\";\nimport { Badge } from \"@/components/layout/Badge\";\nimport { useVariant } from \"@/components/useVariant\";\nimport { joinVariantSlug } from \"@/utils/variants\";\n\nconst SectionBarContext = createContext(false);\n\nfunction SectionBarProvider({\n hasSectionBar,\n children,\n}: {\n hasSectionBar: boolean;\n children: React.ReactNode;\n}) {\n return (\n <SectionBarContext.Provider value={hasSectionBar}>\n {children}\n </SectionBarContext.Provider>\n );\n}\n\ninterface DocsProps {\n children: React.ReactNode;\n}\n\nconst StyledDocsWrapper = styled.div<{ theme: Theme }>`\n position: relative;\n`;\n\nconst StyledDocsSidebar = styled.div<{ theme: Theme }>`\n clear: both;\n`;\n\n// The <main> landmark wraps only the article content: the sidebar, footer,\n// and nav render outside it so content extractors and assistive tech start at\n// the article.\nconst StyledDocsContainer = styled.main<{\n theme: Theme;\n $isChatOpen?: boolean;\n}>`\n position: relative;\n padding: 0 20px 100px 20px;\n width: 100%;\n ${({ theme }) => styledText(theme)};\n transition: all 0.3s ease;\n\n ${mq(\"lg\")} {\n padding: 0 300px 80px 300px;\n\n ${({ $isChatOpen }) =>\n $isChatOpen &&\n css`\n padding: 0 440px 80px 300px;\n `}\n }\n\n ${sidePanelOffset};\n ${({ $isChatOpen }) => !$isChatOpen && focusModeColumn};\n\n & p {\n color: ${({ theme }) => theme.colors.grayDark};\n hyphens: auto;\n }\n\n & pre {\n max-width: 100%;\n }\n\n ${styledAnchor};\n ${stylesLists};\n ${styledTable};\n\n & img,\n & video,\n & iframe {\n max-width: 100%;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n }\n\n & code:not([class]),\n & kbd {\n max-width: max-content;\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 20%, transparent)`};\n color: ${({ theme }) => theme.colors.dark};\n padding: 2px 4px;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n overflow-wrap: anywhere;\n }\n\n & .lucide {\n color: ${({ theme }) => theme.colors.primary};\n }\n\n & .aspect-video {\n aspect-ratio: 16 / 9;\n border-radius: ${({ theme }) => theme.spacing.radius.lg};\n }\n`;\n\nexport const StyledMarkdownContainer = styled.div`\n display: flex;\n flex-direction: column;\n gap: 20px;\n flex: 1;\n max-width: 640px;\n margin: auto;\n`;\n\ninterface Props {\n theme?: Theme;\n $isActive?: boolean;\n $isOpen?: boolean;\n $hasSectionBar?: boolean;\n}\n\nexport const StyledSidebar = styled.nav<Props>`\n position: fixed;\n overflow-y: auto;\n max-height: calc(\n 100dvh - ${({ $hasSectionBar }) => ($hasSectionBar ? 104 : 62)}px\n );\n width: 100%;\n z-index: 99;\n top: ${({ $hasSectionBar }) => ($hasSectionBar ? 104 : 62)}px;\n height: 100%;\n padding: 20px;\n opacity: 0;\n pointer-events: none;\n visibility: hidden;\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0.3s;\n transform: translateY(30px);\n left: 0;\n background: ${({ theme }) => theme.colors.light};\n -webkit-overflow-scrolling: touch;\n display: flex;\n flex-direction: column;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${mq(\"lg\")} {\n border-right: solid 1px ${({ theme }) => theme.colors.grayLight};\n transition: none;\n max-height: 100dvh;\n padding: 82px 20px 20px 20px;\n opacity: 1;\n pointer-events: all;\n visibility: visible;\n transform: translateY(0);\n /* Mixed over the page background rather than transparent so the panel\n reads as a filled surface in both modes. */\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 8%, ${theme.colors.light})`};\n top: 0;\n width: 280px;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n transform: translateY(0);\n opacity: 1;\n pointer-events: all;\n visibility: visible;\n transition-delay: 0s;\n `}\n\n ${focusModeHide(\"left\")};\n\n ${mq(\"lg\")} {\n html[data-focus-mode] & {\n visibility: hidden;\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0.3s;\n }\n }\n`;\n\n// One row of 30px controls: the focus-mode toggle, the language and version\n// switchers, then the theme toggle. The focus toggle is fixed rather than a\n// child (it outlives the sidebar in focus mode), so on the rail the row's own\n// padding leaves its 30px plus a gap free at the left.\nexport const StyledSidebarFooter = styled.div`\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 22px 20px;\n position: sticky;\n border-top: 1px solid ${({ theme }) => theme.colors.grayLight};\n /* Same opaque mix as the sidebar panel so the sticky footer blends into it\n while still masking the list scrolling underneath. */\n background: ${({ theme }) =>\n `color-mix(in srgb, ${theme.colors.primaryLight} 8%, ${theme.colors.light})`};\n margin: 0 -20px -20px;\n bottom: -20px;\n\n ${mq(\"lg\")} {\n padding: 16px 20px 16px 58px;\n }\n`;\n\n// The theme toggle's slot takes whatever the switchers leave, so the toggle\n// stays beside them in the mobile menu and holds the right end of the rail.\n// A plain flex row rather than Cherry's Flex: the slot has to grow, which is a\n// property of the child, and styled(Flex) would swallow Flex's own $-prefixed\n// props on the way through.\nexport const StyledSidebarFooterToggle = styled.div`\n display: flex;\n flex: 1;\n justify-content: flex-start;\n\n /* On the rail the switchers claim the free width when both are configured,\n so the toggle keeps its own size and is pushed to the right end. */\n ${mq(\"lg\")} {\n flex: 0 0 auto;\n margin-left: auto;\n }\n`;\n\nexport const StyledIndexSidebar = styled.ul<{ theme: Theme }>`\n display: none;\n list-style: none;\n margin: 0;\n padding: 0;\n position: fixed;\n top: 0;\n right: 0;\n width: 280px;\n height: 100dvh;\n overflow-y: auto;\n z-index: 1;\n padding: 82px 20px 20px 20px;\n background: ${({ theme }) => theme.colors.light};\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n -webkit-overflow-scrolling: touch;\n\n &::-webkit-scrollbar {\n display: none;\n }\n\n ${mq(\"lg\")} {\n display: block;\n }\n\n & li {\n padding: 5px 0;\n }\n\n ${focusModeHide(\"right\")};\n\n ${mq(\"lg\")} {\n html[data-focus-mode] & {\n visibility: hidden;\n transition:\n transform 0.3s ease,\n opacity 0.3s ease,\n visibility 0s linear 0.3s;\n }\n }\n`;\n\nexport const StyledIndexSidebarLabel = styled.span<{ theme: Theme }>`\n ${({ theme }) => styledSmall(theme)};\n color: ${({ theme }) => theme.colors.grayDark};\n`;\n\nexport const StyledIndexSidebarLi = styled.li<{\n theme: Theme;\n $isActive: boolean;\n}>`\n &::before {\n content: \"\";\n display: block;\n position: absolute;\n left: 0;\n height: 20px;\n width: 1px;\n background: transparent;\n transition: all 0.3s ease;\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n &::before {\n background: ${theme.colors.primary};\n }\n `}\n`;\n\nexport const StyledIndexSidebarLink = styled.a<{\n theme: Theme;\n $isActive: boolean;\n}>`\n ${({ theme }) => styledSmall(theme)};\n color: ${({ theme, $isActive }) =>\n $isActive ? theme.colors.primary : theme.colors.dark};\n font-weight: ${({ $isActive }) => ($isActive ? \"600\" : \"400\")};\n text-decoration: none;\n transition: all 0.3s ease;\n\n &:hover {\n color: ${({ theme }) => theme.colors.primary};\n }\n`;\n\nexport const StyledSidebarList = styled.ul`\n list-style: none;\n margin: 0;\n padding: 0;\n\n &:last-of-type {\n margin-bottom: auto;\n }\n`;\n\nexport const StyledStrong = styled.strong<{ theme: Theme }>`\n font-weight: 600;\n ${({ theme }) => styledStrong(theme)};\n color: ${({ theme }) => theme.colors.accentStrong};\n display: inline-flex;\n align-items: center;\n gap: 8px;\n\n & svg {\n flex-shrink: 0;\n }\n`;\n\nexport const StyledSidebarListItem = styled.li`\n display: flex;\n gap: 10px;\n clear: both;\n`;\n\nconst sidebarRowLineHeight = 1.6;\n\n// Shared appearance for every sidebar row - leaf links AND nested group\n// headers - so hover, active state, and the left rail read identically.\nconst sidebarRowStyles = css<Props>`\n text-decoration: none;\n font-size: ${({ theme }) => theme.fontSizes.small.lg};\n line-height: ${sidebarRowLineHeight};\n color: ${({ theme }) => theme.colors.accentMuted};\n padding: 5px 0 5px 20px;\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-width: 0;\n transition: all 0.3s ease;\n border-left: solid 1px ${({ theme }) => theme.colors.grayLight};\n\n & svg {\n flex-shrink: 0;\n }\n\n &:hover {\n color: ${({ theme }) => theme.colors.accent};\n border-color: ${({ theme }) => theme.colors.primary};\n }\n\n ${({ $isActive, theme }) =>\n $isActive &&\n css`\n color: ${theme.colors.accentStrong};\n border-color: ${theme.colors.primary};\n font-weight: 600;\n `};\n`;\n\n// The collapse chevron points right when closed and rotates to point down\n// when the group is open.\nconst sidebarChevron = css<Props>`\n & .lucide-chevron-right {\n margin-left: auto;\n transition: transform 0.3s ease;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n transform: rotate(90deg);\n `}\n }\n`;\n\nexport const StyledSidebarListItemLink = styled(Link)<Props>`\n ${sidebarRowStyles};\n`;\n\n// Compact HTTP-method label shown before a generated API endpoint link, colored\n// by verb so endpoints are scannable in the sidebar. Only rendered when a link\n// carries an `httpMethod` (endpoint pages do; hand-written pages do not).\n// The look is Badge's mono variation (tinted, solid when active); only\n// sidebar metrics are adjusted here. The tag stays on the title's first line\n// when the title wraps, so its top offset centers it within one line box. The\n// min-width fits the longest verb (OPTIONS), so every title starts on one edge.\nconst sidebarMethodTagHeight = 18;\n\nconst sidebarMethodTagOffset = ({ theme }: { theme: Theme }) =>\n `calc((${theme.fontSizes.small.lg} * ${sidebarRowLineHeight} - ${sidebarMethodTagHeight}px) / 2)`;\n\nexport const StyledSidebarMethodTag = styled(Badge)<{ theme: Theme }>`\n flex-shrink: 0;\n align-self: flex-start;\n justify-content: center;\n min-width: 48px;\n height: ${sidebarMethodTagHeight}px;\n margin-top: ${sidebarMethodTagOffset};\n font-size: 9px;\n letter-spacing: 0.02em;\n padding: 1px 4px;\n border: none;\n`;\n\n// Nested navigation group. The header shares the link appearance/hover; a\n// non-navigable group is a single toggle button, while a group that is also a\n// page pairs a link with a chevron toggle. Children live in\n// StyledSidebarGroupContent, which animates open/closed via height 0 <-> auto\n// (enabled by interpolate-size in GlobalStyles, same as the Accordion).\nexport const StyledSidebarGroupButton = styled(Button)<Props>`\n ${resetButton};\n ${sidebarRowStyles};\n ${sidebarChevron};\n width: 100%;\n height: auto;\n min-height: 0;\n text-align: left;\n\n /* Buttons aren't covered by the global a:focus-visible ring, so this\n nav-row toggle carries its own copy of it. */\n &:focus-visible {\n outline: none;\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n`;\n\nexport const StyledSidebarGroupRow = styled.div<Props>`\n ${sidebarRowStyles};\n ${sidebarChevron};\n\n /* The row is a plain div, so it never matches :focus-visible itself. Ring the\n whole row when its inner link or chevron takes keyboard focus instead, to\n match the leaf-row focus treatment. */\n &:has(:focus-visible) {\n border-radius: ${({ theme }) => theme.spacing.radius.xs};\n box-shadow: 0 0 0 2px ${({ theme }) => theme.colors.primaryLight};\n }\n`;\n\nexport const StyledSidebarGroupLink = styled(Link)`\n display: flex;\n align-items: center;\n gap: 8px;\n flex: 1;\n min-width: 0;\n color: inherit;\n text-decoration: none;\n\n & svg {\n flex-shrink: 0;\n }\n\n /* Ring is drawn on the parent row via :has(:focus-visible); suppress the\n global a:focus-visible glow so it isn't drawn twice. */\n &:focus-visible {\n outline: none;\n box-shadow: none;\n }\n`;\n\nexport const StyledSidebarGroupChevron = styled(Button)`\n ${resetButton};\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex-shrink: 0;\n width: auto;\n height: auto;\n min-height: 0;\n padding: 0;\n border: 0;\n background: none;\n color: inherit;\n cursor: pointer;\n\n /* Ring is drawn on the parent row via :has(:focus-visible). */\n &:focus-visible {\n outline: none;\n }\n`;\n\nexport const StyledSidebarGroupContent = styled.ul.attrs<Props>(\n ({ $isOpen }) => ({\n \"aria-hidden\": !$isOpen,\n inert: !$isOpen,\n }),\n)<Props>`\n list-style: none;\n margin: 0;\n padding: 0;\n height: 0;\n overflow: clip;\n visibility: hidden;\n transition:\n height 0.3s ease,\n visibility 0s linear 0.3s;\n\n ${({ $isOpen }) =>\n $isOpen &&\n css`\n height: auto;\n visibility: visible;\n transition-delay: 0s;\n `}\n\n @media (prefers-reduced-motion: reduce) {\n transition: none;\n }\n`;\n\nexport const StyleMobileBar = styled(Button)<Props>`\n ${resetButton};\n position: fixed;\n z-index: 999;\n bottom: 0;\n right: 20px;\n font-size: ${({ theme }) => theme.fontSizes.strong.lg};\n line-height: ${({ theme }) => theme.fontSizes.strong.lg};\n box-shadow: ${({ theme }) => theme.shadows.sm};\n background: ${({ theme }) => theme.colors.primary};\n color: ${({ theme }) => theme.colors.surface};\n backdrop-filter: blur(10px);\n -webkit-backdrop-filter: blur(10px);\n padding: 10px;\n border-radius: 100px;\n margin: 0 0 20px 0;\n font-weight: 600;\n display: flex;\n justify-content: flex-start;\n width: auto;\n height: auto;\n min-height: 0;\n\n ${mq(\"lg\")} {\n display: none;\n }\n\n ${({ $isActive }) => $isActive && `position: fixed;`};\n`;\n\nexport const StyledMobileBurger = styled.span<Props>`\n display: block;\n margin: auto 0;\n width: 18px;\n height: 18px;\n position: relative;\n overflow: hidden;\n background: transparent;\n position: relative;\n transform: scale(0.8);\n\n &::before,\n &::after {\n content: \"\";\n display: block;\n position: absolute;\n width: 18px;\n height: 3px;\n border-radius: 3px;\n background: ${({ theme }) => theme.colors.surface};\n transition: all 0.3s ease;\n }\n\n &::before {\n top: 3px;\n }\n\n &::after {\n bottom: 3px;\n }\n\n ${({ $isActive }) =>\n $isActive &&\n css`\n &::before {\n transform: translateY(5px) rotate(45deg);\n }\n\n &::after {\n transform: translateY(-4px) rotate(-45deg);\n }\n `};\n`;\n\n// Visually hidden but present for crawlers and agents: points at llms.txt and\n// the .md mirrors. Rendered as the first element of the site layout.\nconst StyledLlmsDirective = styled.div`\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip: rect(0 0 0 0);\n white-space: nowrap;\n border: 0;\n`;\n\nfunction LlmsDirective() {\n // Every language and version has its own llms.txt under its URL prefix.\n const { prefix } = useVariant();\n const indexHref = \"/\" + joinVariantSlug(prefix, \"llms.txt\");\n const fullHref = \"/\" + joinVariantSlug(prefix, \"llms-full.txt\");\n return (\n <StyledLlmsDirective data-markdown-ignore>\n <a href={indexHref}>Documentation index for AI agents (llms.txt)</a>.\n Markdown versions of every page are available by appending .md to the page\n URL. The full corpus is at <a href={fullHref}>{fullHref}</a>.\n </StyledLlmsDirective>\n );\n}\n\ninterface DocsWrapperProps {\n children: React.ReactNode;\n}\n\nfunction DocsWrapper({ children }: DocsWrapperProps) {\n return <StyledDocsWrapper>{children}</StyledDocsWrapper>;\n}\n\nfunction DocsSidebar({ children }: DocsProps) {\n return <StyledDocsSidebar>{children}</StyledDocsSidebar>;\n}\n\nfunction DocsContainer({ children, lang }: DocsProps & { lang?: string }) {\n const { isOpen } = useChat();\n\n return (\n <StyledDocsContainer $isChatOpen={isOpen} lang={lang}>\n {children}\n </StyledDocsContainer>\n );\n}\n\nexport {\n DocsWrapper,\n DocsSidebar,\n DocsContainer,\n LlmsDirective,\n SectionBarContext,\n SectionBarProvider,\n};\n";
@@ -361,12 +361,14 @@ export const StyledSidebarListItem = styled.li\`
361
361
  clear: both;
362
362
  \`;
363
363
 
364
+ const sidebarRowLineHeight = 1.6;
365
+
364
366
  // Shared appearance for every sidebar row - leaf links AND nested group
365
367
  // headers - so hover, active state, and the left rail read identically.
366
368
  const sidebarRowStyles = css<Props>\`
367
369
  text-decoration: none;
368
370
  font-size: \${({ theme }) => theme.fontSizes.small.lg};
369
- line-height: 1.6;
371
+ line-height: \${sidebarRowLineHeight};
370
372
  color: \${({ theme }) => theme.colors.accentMuted};
371
373
  padding: 5px 0 5px 20px;
372
374
  display: flex;
@@ -418,9 +420,21 @@ export const StyledSidebarListItemLink = styled(Link)<Props>\`
418
420
  // by verb so endpoints are scannable in the sidebar. Only rendered when a link
419
421
  // carries an \`httpMethod\` (endpoint pages do; hand-written pages do not).
420
422
  // The look is Badge's mono variation (tinted, solid when active); only
421
- // sidebar metrics are adjusted here.
422
- export const StyledSidebarMethodTag = styled(Badge)\`
423
+ // sidebar metrics are adjusted here. The tag stays on the title's first line
424
+ // when the title wraps, so its top offset centers it within one line box. The
425
+ // min-width fits the longest verb (OPTIONS), so every title starts on one edge.
426
+ const sidebarMethodTagHeight = 18;
427
+
428
+ const sidebarMethodTagOffset = ({ theme }: { theme: Theme }) =>
429
+ \`calc((\${theme.fontSizes.small.lg} * \${sidebarRowLineHeight} - \${sidebarMethodTagHeight}px) / 2)\`;
430
+
431
+ export const StyledSidebarMethodTag = styled(Badge)<{ theme: Theme }>\`
423
432
  flex-shrink: 0;
433
+ align-self: flex-start;
434
+ justify-content: center;
435
+ min-width: 48px;
436
+ height: \${sidebarMethodTagHeight}px;
437
+ margin-top: \${sidebarMethodTagOffset};
424
438
  font-size: 9px;
425
439
  letter-spacing: 0.02em;
426
440
  padding: 1px 4px;
@@ -1 +1 @@
1
- export declare const envExampleTemplate = "# Public Site URL\n# Used by sitemap.xml and robots.txt. Overrides `url` in config.json when set.\n# NEXT_PUBLIC_SITE_URL=https://docs.example.com\n\n# Password Protection (optional)\n# Set a shared password to gate the whole site behind a login screen. When set,\n# pages require the password, the content APIs (chat + search) return 401\n# without it, and the site is hidden from search engines and crawlers. Leave\n# unset (or remove) to keep the site public.\n# SITE_PASSWORD=choose-a-strong-shared-password\n\n# Paid API Access (recommended for public deployments with AI enabled)\n# Public documentation remains intentionally public by default. Set RAG_API_KEY\n# to require Authorization: Bearer <key> for /api/rag and prevent anonymous LLM\n# spend. The browser chat cannot safely hold this server secret; use\n# SITE_PASSWORD instead when authenticated browser chat is required.\n# RAG_API_KEY=generate-a-long-random-secret\n# Set DOCS_API_KEY to require bearer authentication for /api/mcp. If omitted,\n# MCP follows the site access mode and remains public on an intentionally public\n# documentation site.\n# DOCS_API_KEY=generate-another-long-random-secret\n\n# Remote Dev Access (optional, dev server only)\n# Hostnames (besides localhost) allowed to load the Next.js dev server's\n# resources, for when you browse the dev server over a LAN IP or a\n# Tailscale/VPN hostname. Without this, Next blocks the dev HMR socket for\n# such hosts and the page renders but never becomes interactive. Ignored by\n# production builds. Comma-separate multiple hostnames.\n# ALLOWED_DEV_ORIGINS=my-machine.tailnet-name.ts.net\n\n# LLM Provider Configuration\n# Choose your preferred LLM provider: openai, anthropic, or google\nLLM_PROVIDER=openai\n\n# API Keys (set the one matching your provider)\nOPENAI_API_KEY=your_openai_api_key_here\nANTHROPIC_API_KEY=your_anthropic_api_key_here\nGOOGLE_API_KEY=your_google_api_key_here\n\n# Optional: Override default chat model\n# See available models at your provider's docs:\n# OpenAI: https://platform.openai.com/docs/models\n# Anthropic: https://docs.anthropic.com/claude/docs/models-overview\n# Google: https://ai.google.dev/models/gemini\n# LLM_CHAT_MODEL=\n\n# Optional: Override default embedding model\n# See available embedding models at your provider's docs:\n# OpenAI: https://platform.openai.com/docs/guides/embeddings\n# Google: https://ai.google.dev/gemini-api/docs/embeddings\n# Note: Anthropic doesn't provide embeddings, will fallback to OpenAI\n# LLM_EMBEDDING_MODEL=\n\n# Optional: Set temperature (0-1 for Anthropic, 0-2 for OpenAI and Google, default: 0)\n# Use \"default\" to send none and keep the model's own default\n# LLM_TEMPERATURE=0\n\n# Optional: Embedding dimensions for the prebuilt search index (default: 512)\n# Doc vectors are Matryoshka-truncated to this many dimensions and stored as\n# int8, which keeps services/mcp/docs-index.json small (~20x smaller than raw\n# floats) so large doc sets don't stall the AI chat on serverless cold starts.\n# Lower = smaller index, slightly lower recall. Values >= the model's native\n# dimension keep full precision. Rebuild after changing this.\n# LLM_EMBEDDING_DIMS=512\n";
1
+ export declare const envExampleTemplate = "# Public Site URL\n# Used by sitemap.xml and robots.txt. Overrides `url` in config.json when set.\n# NEXT_PUBLIC_SITE_URL=https://docs.example.com\n\n# Password Protection (optional)\n# Set a shared password to gate the whole site behind a login screen. When set,\n# pages require the password, the content APIs (chat + search) return 401\n# without it, and the site is hidden from search engines and crawlers. Leave\n# unset (or remove) to keep the site public.\n# SITE_PASSWORD=choose-a-strong-shared-password\n\n# Paid API Access (recommended for public deployments with AI enabled)\n# Public documentation remains intentionally public by default. Set RAG_API_KEY\n# to require Authorization: Bearer <key> for /api/rag and prevent anonymous LLM\n# spend. The browser chat cannot safely hold this server secret; use\n# SITE_PASSWORD instead when authenticated browser chat is required.\n# RAG_API_KEY=generate-a-long-random-secret\n# Set DOCS_API_KEY to require bearer authentication for /api/mcp. If omitted,\n# MCP follows the site access mode and remains public on an intentionally public\n# documentation site.\n# DOCS_API_KEY=generate-another-long-random-secret\n\n# Remote Dev Access (optional, dev server only)\n# Hostnames (besides localhost) allowed to load the Next.js dev server's\n# resources, for when you browse the dev server over a LAN IP or a\n# Tailscale/VPN hostname. Without this, Next blocks the dev HMR socket for\n# such hosts and the page renders but never becomes interactive. Ignored by\n# production builds. Comma-separate multiple hostnames.\n# ALLOWED_DEV_ORIGINS=my-machine.tailnet-name.ts.net\n\n# LLM Provider Configuration\n# Choose your preferred LLM provider: openai, anthropic, or google\nLLM_PROVIDER=openai\n\n# API Keys (set the one matching your provider)\nOPENAI_API_KEY=your_openai_api_key_here\nANTHROPIC_API_KEY=your_anthropic_api_key_here\nGOOGLE_API_KEY=your_google_api_key_here\n\n# Optional: Override default chat model\n# See available models at your provider's docs:\n# OpenAI: https://platform.openai.com/docs/models\n# Anthropic: https://docs.anthropic.com/claude/docs/models-overview\n# Google: https://ai.google.dev/models/gemini\n# LLM_CHAT_MODEL=\n\n# Optional: Override default embedding model\n# See available embedding models at your provider's docs:\n# OpenAI: https://platform.openai.com/docs/guides/embeddings\n# Google: https://ai.google.dev/gemini-api/docs/embeddings\n# Note: Anthropic doesn't provide embeddings, will fallback to OpenAI\n# LLM_EMBEDDING_MODEL=\n\n# Optional: Set temperature (0-2, default: 0) for models that accept one\n# Not sent to Anthropic, GPT-5 onwards, or Gemini 3.5 onwards, so the default\n# models get none. Use \"default\" to send none to any model\n# LLM_TEMPERATURE=0\n\n# Optional: Embedding dimensions for the prebuilt search index (default: 512)\n# Doc vectors are Matryoshka-truncated to this many dimensions and stored as\n# int8, which keeps services/mcp/docs-index.json small (~20x smaller than raw\n# floats) so large doc sets don't stall the AI chat on serverless cold starts.\n# Lower = smaller index, slightly lower recall. Values >= the model's native\n# dimension keep full precision. Rebuild after changing this.\n# LLM_EMBEDDING_DIMS=512\n";
@@ -51,8 +51,9 @@ GOOGLE_API_KEY=your_google_api_key_here
51
51
  # Note: Anthropic doesn't provide embeddings, will fallback to OpenAI
52
52
  # LLM_EMBEDDING_MODEL=
53
53
 
54
- # Optional: Set temperature (0-1 for Anthropic, 0-2 for OpenAI and Google, default: 0)
55
- # Use "default" to send none and keep the model's own default
54
+ # Optional: Set temperature (0-2, default: 0) for models that accept one
55
+ # Not sent to Anthropic, GPT-5 onwards, or Gemini 3.5 onwards, so the default
56
+ # models get none. Use "default" to send none to any model
56
57
  # LLM_TEMPERATURE=0
57
58
 
58
59
  # Optional: Embedding dimensions for the prebuilt search index (default: 512)
@@ -1 +1 @@
1
- export declare const aiAssistantMdxTemplate = "---\ntitle: \"AI Assistant\"\ndescription: \"Integrate AI capabilities into your Doccupine documentation using OpenAI, Anthropic, or Google Gemini.\"\ndate: \"2026-02-19\"\ncategory: \"AI & Integrations\"\ncategoryOrder: 3\ncategoryIcon: \"sparkles\"\norder: 1\n---\n# AI Assistant\n\nDoccupine supports AI integration to enhance your documentation experience. You can use OpenAI, Anthropic, or Google Gemini to power AI features in your documentation site. The AI assistant uses your documentation content as context, allowing users to ask questions about your docs and receive accurate answers based on the documentation.\n\n## Opening the Assistant\n\nOnce a provider is configured, an assistant button appears in the header. You can open and close the assistant from anywhere on the site by pressing <kbd>Command</kbd> + <kbd>I</kbd> (<kbd>Ctrl</kbd> + <kbd>I</kbd> on Windows). Press the same shortcut again to dismiss it.\n\n<Callout type=\"note\">\n The keyboard shortcut is only active once you have configured an LLM provider, as described below.\n</Callout>\n\nOn a site with [languages](/languages) or [versions](/versions), the assistant answers from the pages of the language and version the reader is on.\n\n## Setup\n\nTo enable AI features, create an `.env` file in the directory where your website is generated. By default, this is the `nextjs-app/` directory.\n\n## Configuration\n\nCreate an `.env` file with the following configuration options:\n\n```env\n# LLM Provider Configuration\n# Choose your preferred LLM provider: openai, anthropic, or google\nLLM_PROVIDER=openai\n\n# API Keys (set the one matching your provider)\nOPENAI_API_KEY=your_openai_api_key_here\nANTHROPIC_API_KEY=your_anthropic_api_key_here\nGOOGLE_API_KEY=your_google_api_key_here\n\n# Optional: Require a bearer token for direct /api/rag requests on a public site\n# RAG_API_KEY=generate-a-long-random-secret\n\n# Optional: Override default chat model (see your provider's docs for available models)\n# LLM_CHAT_MODEL=your-model-id\n\n# Optional: Override default embedding model (see your provider's docs for available models)\n# Note: Anthropic doesn't provide embeddings, will fallback to OpenAI\n# LLM_EMBEDDING_MODEL=your-embedding-model-id\n\n# Optional: Set temperature (0-1 for Anthropic, 0-2 for OpenAI and Google, default: 0)\n# Use \"default\" to send none and keep the model's own default\n# LLM_TEMPERATURE=0\n\n# Optional: Embedding dimensions for the prebuilt search index (default: 512)\n# Doc vectors are truncated to this many dimensions and stored as int8 to keep\n# the search index small. Lower = smaller index, slightly lower recall.\n# Rebuild after changing this.\n# LLM_EMBEDDING_DIMS=512\n```\n\n## Provider Selection\n\nSet `LLM_PROVIDER` to one of the following values:\n\n- `openai` - Use OpenAI's models\n- `anthropic` - Use Anthropic's models\n- `google` - Use Google's models\n\n## API Keys\n\nYou need to set the API key that matches your chosen provider:\n\n- For OpenAI: Set `OPENAI_API_KEY`\n- For Anthropic: Set `ANTHROPIC_API_KEY`\n- For Google: Set `GOOGLE_API_KEY`\n\n<Callout type=\"warning\">\n Keep your API keys secure. Never commit your `.env` file to version control.\n</Callout>\n\n<Callout type=\"note\">\n Doccupine ignores every `.env*` variant except the non-secret\n `.env.example`, helping prevent development, test, and production credentials\n from being committed accidentally.\n</Callout>\n\n## Protecting model spend\n\nPublic documentation intentionally leaves the browser assistant available by default. For a public deployment where only server-to-server clients should call the paid RAG endpoint, set `RAG_API_KEY` and require `Authorization: Bearer <key>` on `/api/rag`.\n\n<Callout type=\"warning\">\n The built-in browser assistant cannot safely store a server API key. Setting\n `RAG_API_KEY` on an otherwise public site disables anonymous browser chat. Use\n `SITE_PASSWORD` instead when signed-in browser visitors should keep using the\n assistant, or leave `RAG_API_KEY` unset when public chat is intentional.\n</Callout>\n\n## Using Anthropic with OpenAI\n\nIf you want to use Anthropic as your LLM provider, you must also have an OpenAI API key set. Here's why:\n\n### The Situation\n\nAnthropic (Claude) does not provide an embeddings API. They only offer chat/completion models, not text embeddings.\n\nYour RAG (Retrieval-Augmented Generation) system has two components:\n\n- **Chat/Completion** - Generates answers, works with Anthropic.\n- **Embeddings** - Creates vector representations of text for search, Anthropic doesn't provide this.\n\nWhen using Anthropic as your `LLM_PROVIDER`, Doccupine will use Anthropic for chat/completion tasks, but will automatically fallback to OpenAI for embeddings. This means you need both API keys configured:\n\n```env\nLLM_PROVIDER=anthropic\nANTHROPIC_API_KEY=your_anthropic_api_key_here\nOPENAI_API_KEY=your_openai_api_key_here\n```\n\nThis hybrid approach allows you to leverage Anthropic's powerful chat models while still having access to embeddings functionality through OpenAI.\n\n## Default models\n\n| Provider | Chat model | Embedding model |\n| --------- | ---------------------------- | ------------------------ |\n| OpenAI | `gpt-4.1-mini` | `text-embedding-3-small` |\n| Anthropic | `claude-sonnet-4-5-20250929` | OpenAI fallback |\n| Google | `gemini-2.5-flash-lite` | `gemini-embedding-001` |\n\n## Optional Settings\n\n### Chat Model\n\nOverride the default chat model by uncommenting and setting `LLM_CHAT_MODEL`. You can use any available model from your chosen provider. For a complete list of available models, refer to the official documentation:\n\n- [OpenAI Models](https://platform.openai.com/docs/models)\n- [Anthropic Models](https://docs.anthropic.com/claude/docs/models-overview)\n- [Google Gemini Models](https://ai.google.dev/models/gemini)\n\n### Embedding Model\n\nOverride the default embedding model by uncommenting and setting `LLM_EMBEDDING_MODEL`. For a complete list of available embedding models, refer to the official documentation:\n\n- [OpenAI Embeddings](https://platform.openai.com/docs/guides/embeddings)\n- [Google Gemini Embeddings](https://ai.google.dev/gemini-api/docs/embeddings)\n- **Anthropic**: Anthropic doesn't provide embeddings. If you use Anthropic as your provider, Doccupine will fallback to OpenAI for embeddings.\n\n### Temperature\n\nControl the randomness of AI responses by setting `LLM_TEMPERATURE`. Anthropic accepts a value from 0 to 1, OpenAI and Google from 0 to 2:\n\n- `0` - More deterministic and focused responses (default)\n- `1` - More creative and varied responses\n- `default` - Send no temperature and keep the model's own default\n\nSome models do not accept a custom temperature: OpenAI's reasoning models (such as `o3` and `o4-mini`) and its GPT-5 models onwards. For those, Doccupine sends no temperature and ignores `LLM_TEMPERATURE` with a warning in the server logs. A value outside the provider's range is ignored the same way, and the default is used instead.\n\n### Embedding Dimensions\n\nControl the size of the prebuilt search index by setting `LLM_EMBEDDING_DIMS` (default: 512). Doc vectors are truncated to this many dimensions and stored as int8, keeping `services/mcp/docs-index.json` small so large doc sets don't stall the AI chat on serverless cold starts.\n\n- Lower values produce a smaller index with slightly lower search recall.\n- Values greater than or equal to the model's native dimension keep full precision.\n\nThis value must match between build time and runtime. A mismatch forces Doccupine to re-embed your docs at runtime, so rebuild or redeploy your site after changing it.";
1
+ export declare const aiAssistantMdxTemplate = "---\ntitle: \"AI Assistant\"\ndescription: \"Integrate AI capabilities into your Doccupine documentation using OpenAI, Anthropic, or Google Gemini.\"\ndate: \"2026-02-19\"\ncategory: \"AI & Integrations\"\ncategoryOrder: 3\ncategoryIcon: \"sparkles\"\norder: 1\n---\n# AI Assistant\n\nDoccupine supports AI integration to enhance your documentation experience. You can use OpenAI, Anthropic, or Google Gemini to power AI features in your documentation site. The AI assistant uses your documentation content as context, allowing users to ask questions about your docs and receive accurate answers based on the documentation.\n\n## Opening the Assistant\n\nOnce a provider is configured, an assistant button appears in the header. You can open and close the assistant from anywhere on the site by pressing <kbd>Command</kbd> + <kbd>I</kbd> (<kbd>Ctrl</kbd> + <kbd>I</kbd> on Windows). Press the same shortcut again to dismiss it.\n\n<Callout type=\"note\">\n The keyboard shortcut is only active once you have configured an LLM provider, as described below.\n</Callout>\n\nOn a site with [languages](/languages) or [versions](/versions), the assistant answers from the pages of the language and version the reader is on.\n\n## Setup\n\nTo enable AI features, create an `.env` file in the directory where your website is generated. By default, this is the `nextjs-app/` directory.\n\n## Configuration\n\nCreate an `.env` file with the following configuration options:\n\n```env\n# LLM Provider Configuration\n# Choose your preferred LLM provider: openai, anthropic, or google\nLLM_PROVIDER=openai\n\n# API Keys (set the one matching your provider)\nOPENAI_API_KEY=your_openai_api_key_here\nANTHROPIC_API_KEY=your_anthropic_api_key_here\nGOOGLE_API_KEY=your_google_api_key_here\n\n# Optional: Require a bearer token for direct /api/rag requests on a public site\n# RAG_API_KEY=generate-a-long-random-secret\n\n# Optional: Override default chat model (see your provider's docs for available models)\n# LLM_CHAT_MODEL=your-model-id\n\n# Optional: Override default embedding model (see your provider's docs for available models)\n# Note: Anthropic doesn't provide embeddings, will fallback to OpenAI\n# LLM_EMBEDDING_MODEL=your-embedding-model-id\n\n# Optional: Set temperature (0-2, default: 0) for models that accept one\n# Not sent to Anthropic, GPT-5 onwards, or Gemini 3.5 onwards, so the default\n# models get none. Use \"default\" to send none to any model\n# LLM_TEMPERATURE=0\n\n# Optional: Embedding dimensions for the prebuilt search index (default: 512)\n# Doc vectors are truncated to this many dimensions and stored as int8 to keep\n# the search index small. Lower = smaller index, slightly lower recall.\n# Rebuild after changing this.\n# LLM_EMBEDDING_DIMS=512\n```\n\n## Provider Selection\n\nSet `LLM_PROVIDER` to one of the following values:\n\n- `openai` - Use OpenAI's models\n- `anthropic` - Use Anthropic's models\n- `google` - Use Google's models\n\n## API Keys\n\nYou need to set the API key that matches your chosen provider:\n\n- For OpenAI: Set `OPENAI_API_KEY`\n- For Anthropic: Set `ANTHROPIC_API_KEY`\n- For Google: Set `GOOGLE_API_KEY`\n\n<Callout type=\"warning\">\n Keep your API keys secure. Never commit your `.env` file to version control.\n</Callout>\n\n<Callout type=\"note\">\n Doccupine ignores every `.env*` variant except the non-secret\n `.env.example`, helping prevent development, test, and production credentials\n from being committed accidentally.\n</Callout>\n\n## Protecting model spend\n\nPublic documentation intentionally leaves the browser assistant available by default. For a public deployment where only server-to-server clients should call the paid RAG endpoint, set `RAG_API_KEY` and require `Authorization: Bearer <key>` on `/api/rag`.\n\n<Callout type=\"warning\">\n The built-in browser assistant cannot safely store a server API key. Setting\n `RAG_API_KEY` on an otherwise public site disables anonymous browser chat. Use\n `SITE_PASSWORD` instead when signed-in browser visitors should keep using the\n assistant, or leave `RAG_API_KEY` unset when public chat is intentional.\n</Callout>\n\n## Using Anthropic with OpenAI\n\nIf you want to use Anthropic as your LLM provider, you must also have an OpenAI API key set. Here's why:\n\n### The Situation\n\nAnthropic (Claude) does not provide an embeddings API. They only offer chat/completion models, not text embeddings.\n\nYour RAG (Retrieval-Augmented Generation) system has two components:\n\n- **Chat/Completion** - Generates answers, works with Anthropic.\n- **Embeddings** - Creates vector representations of text for search, Anthropic doesn't provide this.\n\nWhen using Anthropic as your `LLM_PROVIDER`, Doccupine will use Anthropic for chat/completion tasks, but will automatically fallback to OpenAI for embeddings. This means you need both API keys configured:\n\n```env\nLLM_PROVIDER=anthropic\nANTHROPIC_API_KEY=your_anthropic_api_key_here\nOPENAI_API_KEY=your_openai_api_key_here\n```\n\nThis hybrid approach allows you to leverage Anthropic's powerful chat models while still having access to embeddings functionality through OpenAI.\n\n## Default models\n\n| Provider | Chat model | Embedding model |\n| --------- | ----------------------- | ------------------------ |\n| OpenAI | `gpt-6-luna` | `text-embedding-3-small` |\n| Anthropic | `claude-haiku-5-5` | OpenAI fallback |\n| Google | `gemini-3.5-flash-lite` | `gemini-embedding-001` |\n\n## Optional Settings\n\n### Chat Model\n\nOverride the default chat model by uncommenting and setting `LLM_CHAT_MODEL`. You can use any available model from your chosen provider. For a complete list of available models, refer to the official documentation:\n\n- [OpenAI Models](https://platform.openai.com/docs/models)\n- [Anthropic Models](https://docs.anthropic.com/claude/docs/models-overview)\n- [Google Gemini Models](https://ai.google.dev/models/gemini)\n\n### Embedding Model\n\nOverride the default embedding model by uncommenting and setting `LLM_EMBEDDING_MODEL`. For a complete list of available embedding models, refer to the official documentation:\n\n- [OpenAI Embeddings](https://platform.openai.com/docs/guides/embeddings)\n- [Google Gemini Embeddings](https://ai.google.dev/gemini-api/docs/embeddings)\n- **Anthropic**: Anthropic doesn't provide embeddings. If you use Anthropic as your provider, Doccupine will fallback to OpenAI for embeddings.\n\n### Temperature\n\nControl the randomness of AI responses by setting `LLM_TEMPERATURE` to a value from 0 to 2:\n\n- `0` - More deterministic and focused responses (default)\n- `1` - More creative and varied responses\n- `default` - Send no temperature and keep the model's own default\n\nMany models do not accept a custom temperature, including all three default models: Anthropic's models (its current API version rejects one on every model), OpenAI's reasoning models (such as `o3` and `o4-mini`) and its GPT-5 models onwards, and Google's Gemini 3.5 models onwards. For those, Doccupine sends no temperature and ignores `LLM_TEMPERATURE` with a warning in the server logs. The setting applies to models that still take one, such as `gpt-4.1` or `gemini-2.5-flash`. A value outside 0 to 2 is ignored with a warning, and the default is used instead.\n\n### Embedding Dimensions\n\nControl the size of the prebuilt search index by setting `LLM_EMBEDDING_DIMS` (default: 512). Doc vectors are truncated to this many dimensions and stored as int8, keeping `services/mcp/docs-index.json` small so large doc sets don't stall the AI chat on serverless cold starts.\n\n- Lower values produce a smaller index with slightly lower search recall.\n- Values greater than or equal to the model's native dimension keep full precision.\n\nThis value must match between build time and runtime. A mismatch forces Doccupine to re-embed your docs at runtime, so rebuild or redeploy your site after changing it.";
@@ -49,8 +49,9 @@ GOOGLE_API_KEY=your_google_api_key_here
49
49
  # Note: Anthropic doesn't provide embeddings, will fallback to OpenAI
50
50
  # LLM_EMBEDDING_MODEL=your-embedding-model-id
51
51
 
52
- # Optional: Set temperature (0-1 for Anthropic, 0-2 for OpenAI and Google, default: 0)
53
- # Use "default" to send none and keep the model's own default
52
+ # Optional: Set temperature (0-2, default: 0) for models that accept one
53
+ # Not sent to Anthropic, GPT-5 onwards, or Gemini 3.5 onwards, so the default
54
+ # models get none. Use "default" to send none to any model
54
55
  # LLM_TEMPERATURE=0
55
56
 
56
57
  # Optional: Embedding dimensions for the prebuilt search index (default: 512)
@@ -122,11 +123,11 @@ This hybrid approach allows you to leverage Anthropic's powerful chat models whi
122
123
 
123
124
  ## Default models
124
125
 
125
- | Provider | Chat model | Embedding model |
126
- | --------- | ---------------------------- | ------------------------ |
127
- | OpenAI | \`gpt-4.1-mini\` | \`text-embedding-3-small\` |
128
- | Anthropic | \`claude-sonnet-4-5-20250929\` | OpenAI fallback |
129
- | Google | \`gemini-2.5-flash-lite\` | \`gemini-embedding-001\` |
126
+ | Provider | Chat model | Embedding model |
127
+ | --------- | ----------------------- | ------------------------ |
128
+ | OpenAI | \`gpt-6-luna\` | \`text-embedding-3-small\` |
129
+ | Anthropic | \`claude-haiku-5-5\` | OpenAI fallback |
130
+ | Google | \`gemini-3.5-flash-lite\` | \`gemini-embedding-001\` |
130
131
 
131
132
  ## Optional Settings
132
133
 
@@ -148,13 +149,13 @@ Override the default embedding model by uncommenting and setting \`LLM_EMBEDDING
148
149
 
149
150
  ### Temperature
150
151
 
151
- Control the randomness of AI responses by setting \`LLM_TEMPERATURE\`. Anthropic accepts a value from 0 to 1, OpenAI and Google from 0 to 2:
152
+ Control the randomness of AI responses by setting \`LLM_TEMPERATURE\` to a value from 0 to 2:
152
153
 
153
154
  - \`0\` - More deterministic and focused responses (default)
154
155
  - \`1\` - More creative and varied responses
155
156
  - \`default\` - Send no temperature and keep the model's own default
156
157
 
157
- Some models do not accept a custom temperature: OpenAI's reasoning models (such as \`o3\` and \`o4-mini\`) and its GPT-5 models onwards. For those, Doccupine sends no temperature and ignores \`LLM_TEMPERATURE\` with a warning in the server logs. A value outside the provider's range is ignored the same way, and the default is used instead.
158
+ Many models do not accept a custom temperature, including all three default models: Anthropic's models (its current API version rejects one on every model), OpenAI's reasoning models (such as \`o3\` and \`o4-mini\`) and its GPT-5 models onwards, and Google's Gemini 3.5 models onwards. For those, Doccupine sends no temperature and ignores \`LLM_TEMPERATURE\` with a warning in the server logs. The setting applies to models that still take one, such as \`gpt-4.1\` or \`gemini-2.5-flash\`. A value outside 0 to 2 is ignored with a warning, and the default is used instead.
158
159
 
159
160
  ### Embedding Dimensions
160
161
 
@@ -1 +1 @@
1
- export declare const languagesMdxTemplate = "---\ntitle: \"Languages\"\ndescription: \"Publish your documentation in several languages from one project, with a language switcher, hreflang tags, and scoped search.\"\ndate: \"2026-09-08\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 4\n---\n# Languages\n\nTranslate your documentation by adding a `languages.json` file and one folder per language. Each language gets its own URL prefix, its own sidebar, a switcher in the sidebar, `hreflang` tags for search engines, and search and AI chat that stay inside the language the reader is looking at.\n\n<Callout type=\"note\">\n Languages are entirely opt-in. Without a `languages.json` file nothing changes: your docs live at the root of the docs folder and publish exactly as before.\n</Callout>\n\n## Configuration\n\nCreate `languages.json` in your project root, next to `doccupine.json`:\n\n```json\n[\n { \"code\": \"en\", \"label\": \"English\", \"default\": true },\n { \"code\": \"de\", \"label\": \"Deutsch\" }\n]\n```\n\n- **code**: a lowercase URL segment (letters, digits, and hyphens, such as `en`, `de`, or `pt-br`). It is the folder name, the URL prefix, and the value of the page's `lang` and `hreflang` attributes.\n- **label**: the name shown in the language switcher.\n- **default**: exactly one entry must be the default. Its pages live at the docs root and keep unprefixed URLs.\n- **strings** (optional): overrides for the site's own interface text in that language. See [Interface strings](#interface-strings).\n\nThe order of the entries is the order of the switcher.\n\n## Folder layout\n\nThe default language lives at the root of the docs folder. Every other language lives in a folder named after its code, mirroring the default layout:\n\n```text\ndocs/\n index.mdx -> /\n guides/\n intro.mdx -> /guides/intro\n de/\n index.mdx -> /de\n guides/\n intro.mdx -> /de/guides/intro\n```\n\nA page is the translation of another when it sits at the same path inside its language folder. Only translated pages exist in a language: a page you have not translated yet returns a 404 under that language's prefix, and the switcher takes readers to that language's home page instead.\n\nA language folder without an `index.mdx` gets a generated home page that redirects to its first page.\n\n## What the generated site does\n\n- **Switcher**: the sidebar footer row, between the focus-mode and theme toggles, shows a language dropdown when at least two languages are configured: a 30px pill carrying the current language that opens a menu of every language above it (the same dropdown the Doccupine platform uses), with the arrow keys, Escape, and a click outside to close it. When a version switcher shares the row, the two pills grow from their labels' widths to fill the sidebar's free width, and on the narrow desktop rail each shows its short form: the language's code and the version's own label. Switching goes to the same page in the chosen language when it exists, otherwise to that language's home.\n- **Sidebar and sections**: the sidebar lists only the pages of the current language. [Sections](/sections) work inside every language; a section tab is hidden in a language that has no pages in it.\n- **Search and AI chat**: results and answers come from the current language only. The MCP server's `search_docs` and `list_docs` tools accept a `language` parameter and default to the default language.\n- **SEO**: every translated page carries `alternates.languages` (`hreflang`) links to its other languages, an `x-default` pointing at the default language, and an Open Graph locale. The sitemap lists the same alternates. The `<main>` element carries the page's `lang` attribute; the `<html lang>` attribute is the default language server-side and is corrected from the URL before the first paint.\n- **Agents**: each language has its own `llms.txt` and `llms-full.txt` under its prefix (`/de/llms.txt`), and the root files link to them.\n\n## Navigation\n\nFrontmatter navigation is built per language automatically. To define a language's sidebar by hand, key `navigation.json` by URL prefix: `\"de\"` for the German root, `\"de/api\"` for the German API section. See [Navigation](/navigation).\n\n## Interface strings\n\nThe generated site's own labels (the search box, \"On this page\", the previous and next links, the action bar, the footer) are English by default. Override any of them per language with a `strings` object:\n\n```json\n[\n { \"code\": \"en\", \"label\": \"English\", \"default\": true },\n {\n \"code\": \"de\",\n \"label\": \"Deutsch\",\n \"strings\": {\n \"searchPlaceholder\": \"Dokumentation durchsuchen...\",\n \"onThisPage\": \"Auf dieser Seite\",\n \"previous\": \"Zur\u00FCck\",\n \"next\": \"Weiter\"\n }\n }\n]\n```\n\nKeys you leave out keep their default. The known keys are `searchButton`, `searchDialog`, `searchPlaceholder`, `searchResults`, `searching`, `noResults`, `resultsAvailable` (with a `{count}` placeholder), `resultAvailable`, `askAi`, `askAiAssistant`, `closeSearch`, `onThisPage`, `previous`, `next`, `openNavigation`, `closeNavigation`, `expandGroup` and `collapseGroup` (both with a `{title}` placeholder), `enterFocusMode`, `exitFocusMode`, `focusMode`, `copyContent`, `copied`, `copyCode`, `codeVariants`, `rss`, `rssFeed`, `viewAsMarkdown`, `toggleView`, `poweredBy`, `githubLink`, `aiAssistant`, `resetChat`, `chatGreeting`, `chatPlaceholder`, `chatInputLabel`, `chatAnswering`, `chatError`, `language`, and `version`. An unknown key is reported when the site is generated and ignored.\n\n## Rules\n\n- A language code must not be the slug of a [section](/sections), the first folder of a section's `directory`, a [version](/versions) slug, or one of the reserved segments `api`, `gate`, `mcp`, and `ingest`. The build stops with a message naming the file when it is.\n- The default language has no folder: a `docs/en/` folder on a site whose default is `en` stops the build.\n- When [versions](/versions) are configured too, the language folder comes first: `docs/de/v1/`.\n- The API reference generated from an OpenAPI spec is published in the default language only.\n";
1
+ export declare const languagesMdxTemplate = "---\ntitle: \"Languages\"\ndescription: \"Publish your documentation in several languages from one project, with a language switcher, hreflang tags, and scoped search.\"\ndate: \"2026-09-08\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 4\n---\n# Languages\n\nTranslate your documentation by adding a `languages.json` file and one folder per language. Each language gets its own URL prefix, its own sidebar, a switcher in the sidebar, `hreflang` tags for search engines, and search and AI chat that stay inside the language the reader is looking at.\n\n<Callout type=\"note\">\n Languages are entirely opt-in. Without a `languages.json` file nothing changes: your docs live at the root of the docs folder and publish exactly as before.\n</Callout>\n\n## Configuration\n\nCreate `languages.json` in your project root, next to `doccupine.json`:\n\n```json\n[\n { \"code\": \"en\", \"label\": \"English\", \"default\": true },\n { \"code\": \"de\", \"label\": \"Deutsch\" }\n]\n```\n\n- **code**: a lowercase URL segment (letters, digits, and hyphens, such as `en`, `de`, or `pt-br`). It is the folder name, the URL prefix, and the value of the page's `lang` and `hreflang` attributes.\n- **label**: the name shown in the language switcher.\n- **default**: exactly one entry must be the default. Its pages live at the docs root and keep unprefixed URLs.\n- **strings** (optional): overrides for the site's own interface text in that language. See [Interface strings](#interface-strings).\n\nThe order of the entries is the order of the switcher.\n\n## Folder layout\n\nThe default language lives at the root of the docs folder. Every other language lives in a folder named after its code, mirroring the default layout:\n\n<FileTree>\n\n- docs/\n - index.mdx\n - guides/\n - intro.mdx\n - de/\n - index.mdx\n - guides/\n - intro.mdx\n\n</FileTree>\n\nThese files publish at `/`, `/guides/intro`, `/de`, and `/de/guides/intro`.\n\nA page is the translation of another when it sits at the same path inside its language folder. Only translated pages exist in a language: a page you have not translated yet returns a 404 under that language's prefix, and the switcher takes readers to that language's home page instead.\n\nA language folder without an `index.mdx` gets a generated home page that redirects to its first page.\n\n## What the generated site does\n\n- **Switcher**: the sidebar footer row, between the focus-mode and theme toggles, shows a language dropdown when at least two languages are configured: a 30px pill carrying the current language that opens a menu of every language above it (the same dropdown the Doccupine platform uses), with the arrow keys, Escape, and a click outside to close it. When a version switcher shares the row, the two pills grow from their labels' widths to fill the sidebar's free width, and on the narrow desktop rail each shows its short form: the language's code and the version's own label. Switching goes to the same page in the chosen language when it exists, otherwise to that language's home.\n- **Sidebar and sections**: the sidebar lists only the pages of the current language. [Sections](/sections) work inside every language; a section tab is hidden in a language that has no pages in it.\n- **Search and AI chat**: results and answers come from the current language only. The MCP server's `search_docs` and `list_docs` tools accept a `language` parameter and default to the default language.\n- **SEO**: every translated page carries `alternates.languages` (`hreflang`) links to its other languages, an `x-default` pointing at the default language, and an Open Graph locale. The sitemap lists the same alternates. The `<main>` element carries the page's `lang` attribute; the `<html lang>` attribute is the default language server-side and is corrected from the URL before the first paint.\n- **Agents**: each language has its own `llms.txt` and `llms-full.txt` under its prefix (`/de/llms.txt`), and the root files link to them.\n\n## Navigation\n\nFrontmatter navigation is built per language automatically. To define a language's sidebar by hand, key `navigation.json` by URL prefix: `\"de\"` for the German root, `\"de/api\"` for the German API section. See [Navigation](/navigation).\n\n## Interface strings\n\nThe generated site's own labels (the search box, \"On this page\", the previous and next links, the action bar, the footer) are English by default. Override any of them per language with a `strings` object:\n\n```json\n[\n { \"code\": \"en\", \"label\": \"English\", \"default\": true },\n {\n \"code\": \"de\",\n \"label\": \"Deutsch\",\n \"strings\": {\n \"searchPlaceholder\": \"Dokumentation durchsuchen...\",\n \"onThisPage\": \"Auf dieser Seite\",\n \"previous\": \"Zur\u00FCck\",\n \"next\": \"Weiter\"\n }\n }\n]\n```\n\nKeys you leave out keep their default. The known keys are `searchButton`, `searchDialog`, `searchPlaceholder`, `searchResults`, `searching`, `noResults`, `resultsAvailable` (with a `{count}` placeholder), `resultAvailable`, `askAi`, `askAiAssistant`, `closeSearch`, `onThisPage`, `previous`, `next`, `openNavigation`, `closeNavigation`, `expandGroup` and `collapseGroup` (both with a `{title}` placeholder), `enterFocusMode`, `exitFocusMode`, `focusMode`, `copyContent`, `copied`, `copyCode`, `codeVariants`, `rss`, `rssFeed`, `viewAsMarkdown`, `toggleView`, `poweredBy`, `githubLink`, `aiAssistant`, `resetChat`, `chatGreeting`, `chatPlaceholder`, `chatInputLabel`, `chatAnswering`, `chatError`, `language`, and `version`. An unknown key is reported when the site is generated and ignored.\n\n## Rules\n\n- A language code must not be the slug of a [section](/sections), the first folder of a section's `directory`, a [version](/versions) slug, or one of the reserved segments `api`, `gate`, `mcp`, and `ingest`. The build stops with a message naming the file when it is.\n- The default language has no folder: a `docs/en/` folder on a site whose default is `en` stops the build.\n- When [versions](/versions) are configured too, the language folder comes first: `docs/de/v1/`.\n- The API reference generated from an OpenAPI spec is published in the default language only.\n";
@@ -36,16 +36,20 @@ The order of the entries is the order of the switcher.
36
36
 
37
37
  The default language lives at the root of the docs folder. Every other language lives in a folder named after its code, mirroring the default layout:
38
38
 
39
- \`\`\`text
40
- docs/
41
- index.mdx -> /
42
- guides/
43
- intro.mdx -> /guides/intro
44
- de/
45
- index.mdx -> /de
46
- guides/
47
- intro.mdx -> /de/guides/intro
48
- \`\`\`
39
+ <FileTree>
40
+
41
+ - docs/
42
+ - index.mdx
43
+ - guides/
44
+ - intro.mdx
45
+ - de/
46
+ - index.mdx
47
+ - guides/
48
+ - intro.mdx
49
+
50
+ </FileTree>
51
+
52
+ These files publish at \`/\`, \`/guides/intro\`, \`/de\`, and \`/de/guides/intro\`.
49
53
 
50
54
  A page is the translation of another when it sits at the same path inside its language folder. Only translated pages exist in a language: a page you have not translated yet returns a 404 under that language's prefix, and the switcher takes readers to that language's home page instead.
51
55
 
@@ -12,47 +12,47 @@ export const packageJsonTemplate = JSON.stringify({
12
12
  "type-check": "tsgo --noEmit",
13
13
  },
14
14
  dependencies: {
15
- "@langchain/anthropic": "^1.5.12",
16
- "@langchain/core": "^1.2.14",
17
- "@langchain/google-genai": "^2.3.2",
18
- "@langchain/openai": "^1.6.2",
15
+ "@langchain/anthropic": "^1.6.5",
16
+ "@langchain/core": "^1.4.1",
17
+ "@langchain/google-genai": "^2.3.6",
18
+ "@langchain/openai": "^1.8.4",
19
19
  "@mdx-js/react": "^3.1.1",
20
- "@modelcontextprotocol/sdk": "^1.32.1",
20
+ "@modelcontextprotocol/sdk": "^1.32.2",
21
21
  "beautiful-mermaid": "^1.1.3",
22
- "cherry-styled-components": "^0.2.17",
23
- langchain: "^1.5.15",
24
- "lucide-react": "^1.52.0",
22
+ "cherry-styled-components": "^0.2.22",
23
+ langchain: "^1.6.6",
24
+ "lucide-react": "^1.73.0",
25
25
  minisearch: "^7.2.0",
26
- next: "16.3.8",
26
+ next: "16.4.6",
27
27
  "next-mdx-remote": "^6.0.0",
28
- "posthog-js": "^1.436.1",
29
- "posthog-node": "^5.55.0",
30
- react: "19.3.0",
31
- "react-dom": "19.3.0",
28
+ "posthog-js": "^1.449.2",
29
+ "posthog-node": "^5.73.1",
30
+ react: "19.3.1",
31
+ "react-dom": "19.3.1",
32
32
  "rehype-highlight": "^7.0.2",
33
33
  "rehype-parse": "^9.0.1",
34
34
  "rehype-stringify": "^10.0.1",
35
35
  "remark-gfm": "^4.0.1",
36
- "styled-components": "^6.5.3",
36
+ "styled-components": "^6.6.0",
37
37
  unified: "^11.0.5",
38
- zod: "^4.6.5",
38
+ zod: "^4.6.7",
39
39
  },
40
40
  devDependencies: {
41
- "@next/env": "16.3.8",
42
- "@next/eslint-plugin-next": "16.3.8",
41
+ "@next/env": "16.4.6",
42
+ "@next/eslint-plugin-next": "16.4.6",
43
43
  "@types/node": "^26",
44
44
  "@types/react": "^19",
45
45
  "@types/react-dom": "^19",
46
- "@typescript-eslint/eslint-plugin": "^8.71.1",
47
- "@typescript-eslint/parser": "^8.71.1",
46
+ "@typescript-eslint/eslint-plugin": "^8.72.2",
47
+ "@typescript-eslint/parser": "^8.72.2",
48
48
  "@typescript/native-preview": "^7.0.0-dev.20260707.2",
49
49
  eslint: "^10",
50
50
  "eslint-plugin-import": "^2.32.0",
51
51
  "eslint-plugin-jsx-a11y": "^6.10.2",
52
52
  "eslint-plugin-react": "^7.37.5",
53
53
  "eslint-plugin-react-hooks": "^7.1.1",
54
- globals: "^17.13.0",
55
- prettier: "^3.9.9",
54
+ globals: "^17.14.0",
55
+ prettier: "^3.10.1",
56
56
  tsx: "^4.23.15",
57
57
  typescript: "npm:@typescript/typescript6@^6.0.2",
58
58
  },
@@ -1 +1 @@
1
- export declare const llmConfigTemplate = "import type {\n LLMConfig,\n LLMProvider,\n ProviderDefaults,\n} from \"@/services/llm/types\";\nconst PROVIDER_DEFAULTS: ProviderDefaults = {\n openai: {\n chat: \"gpt-4.1-mini\",\n embedding: \"text-embedding-3-small\",\n },\n anthropic: {\n chat: \"claude-sonnet-4-5-20250929\",\n embedding: \"text-embedding-3-small\", // Fallback to OpenAI\n },\n google: {\n chat: \"gemini-2.5-flash-lite\",\n embedding: \"gemini-embedding-001\",\n },\n};\n// Used when LLM_TEMPERATURE is unset, for models that accept a temperature.\nconst DEFAULT_TEMPERATURE = 0;\nconst MAX_TEMPERATURE: Record<LLMProvider, number> = {\n openai: 2,\n anthropic: 1,\n google: 2,\n};\n// OpenAI's reasoning models (o1, o3, o4-mini) and its GPT-5 line onwards reject\n// a custom temperature, some of them any temperature at all. A vendor prefix\n// such as OpenRouter's \"openai/\" is ignored.\nconst NO_TEMPERATURE_MODEL = /^(?:[\\w-]+\\/)?(?:gpt-(?:[5-9]|\\d{2,})|o\\d)/;\nconst warnings = new Set<string>();\nfunction warnOnce(message: string): void {\n if (warnings.has(message)) return;\n warnings.add(message);\n console.warn(message);\n}\nfunction acceptsTemperature(provider: LLMProvider, chatModel: string): boolean {\n return provider !== \"openai\" || !NO_TEMPERATURE_MODEL.test(chatModel);\n}\n// Returns undefined when no temperature should be sent, leaving the model on\n// its own default: LLM_TEMPERATURE=default, or a model that rejects one.\nfunction resolveTemperature(\n provider: LLMProvider,\n chatModel: string,\n): number | undefined {\n const raw = process.env.LLM_TEMPERATURE?.trim() ?? \"\";\n if (raw.toLowerCase() === \"default\") return undefined;\n const accepted = acceptsTemperature(provider, chatModel);\n if (raw === \"\") return accepted ? DEFAULT_TEMPERATURE : undefined;\n const value = Number(raw);\n const max = MAX_TEMPERATURE[provider];\n if (!Number.isFinite(value) || value < 0 || value > max) {\n warnOnce(\n `Ignoring LLM_TEMPERATURE=\"${raw}\": ${provider} accepts a number from 0 to ${max}, or \"default\".`,\n );\n return accepted ? DEFAULT_TEMPERATURE : undefined;\n }\n if (!accepted) {\n warnOnce(\n `Ignoring LLM_TEMPERATURE: ${chatModel} does not accept a custom temperature.`,\n );\n return undefined;\n }\n return value;\n}\nfunction validateAPIKeys(provider: LLMProvider): void {\n const requiredKeys: Record<LLMProvider, string> = {\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n google: \"GOOGLE_API_KEY\",\n };\n const keyName = requiredKeys[provider];\n const keyValue = process.env[keyName];\n if (!keyValue) {\n throw new Error(\n `Missing API key for ${provider}. Please set ${keyName} in your environment variables.`,\n );\n }\n if (provider === \"anthropic\" && !process.env.OPENAI_API_KEY) {\n throw new Error(\n \"Anthropic provider requires OPENAI_API_KEY for embeddings. Please set OPENAI_API_KEY in your environment variables.\",\n );\n }\n}\nexport function isLLMAvailable(): boolean {\n const provider = (process.env.LLM_PROVIDER || \"openai\") as LLMProvider;\n const requiredKeys: Record<LLMProvider, string> = {\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n google: \"GOOGLE_API_KEY\",\n };\n const keyName = requiredKeys[provider];\n if (!keyName || !process.env[keyName]) return false;\n if (provider === \"anthropic\" && !process.env.OPENAI_API_KEY) return false;\n return true;\n}\nexport function getLLMConfig(): LLMConfig {\n const provider = (process.env.LLM_PROVIDER || \"openai\") as LLMProvider;\n if (![\"openai\", \"anthropic\", \"google\"].includes(provider)) {\n throw new Error(\n `Invalid LLM_PROVIDER: ${provider}. Must be one of: openai, anthropic, google`,\n );\n }\n validateAPIKeys(provider);\n const defaults = PROVIDER_DEFAULTS[provider];\n // Vectors are Matryoshka-truncated to this many dimensions before being\n // stored as int8, keeping the prebuilt search index small. Must match between\n // build time and runtime; a mismatch forces a re-embed. Values >= the model's\n // native dimension keep full precision (default: 512).\n const rawDims = process.env.LLM_EMBEDDING_DIMS;\n let embeddingDims = 512;\n if (rawDims !== undefined && rawDims !== \"\") {\n const parsed = parseInt(rawDims, 10);\n if (Number.isFinite(parsed) && parsed >= 0) embeddingDims = parsed;\n }\n const chatModel = process.env.LLM_CHAT_MODEL || defaults.chat;\n return {\n provider,\n chatModel,\n embeddingModel: process.env.LLM_EMBEDDING_MODEL || defaults.embedding,\n embeddingDims,\n temperature: resolveTemperature(provider, chatModel),\n };\n}\n";
1
+ export declare const llmConfigTemplate = "import type {\n LLMConfig,\n LLMProvider,\n ProviderDefaults,\n} from \"@/services/llm/types\";\nconst PROVIDER_DEFAULTS: ProviderDefaults = {\n openai: {\n chat: \"gpt-6-luna\",\n embedding: \"text-embedding-3-small\",\n },\n anthropic: {\n chat: \"claude-haiku-5-5\",\n embedding: \"text-embedding-3-small\", // Fallback to OpenAI\n },\n google: {\n chat: \"gemini-3.5-flash-lite\",\n embedding: \"gemini-embedding-001\",\n },\n};\n// Used when LLM_TEMPERATURE is unset, for models that accept a temperature.\nconst DEFAULT_TEMPERATURE = 0;\n// OpenAI and Google both accept 0 to 2.\nconst MAX_TEMPERATURE = 2;\n// OpenAI's reasoning models (o1, o3, o4-mini) and its GPT-5 line onwards reject\n// a custom temperature, some of them any temperature at all.\nconst OPENAI_NO_TEMPERATURE = /^(?:[\\w-]+\\/)?(?:gpt-(?:[5-9]|\\d{2,})|o\\d)/;\n// Gemini 3.5 models onwards ignore a temperature, and Google says later\n// generations will reject it.\nconst GOOGLE_NO_TEMPERATURE = /^(?:[\\w-]+\\/)?gemini-(?:3\\.[5-9]|[4-9]|\\d{2,})/;\nconst warnings = new Set<string>();\nfunction warnOnce(message: string): void {\n if (warnings.has(message)) return;\n warnings.add(message);\n console.warn(message);\n}\n// A vendor prefix such as OpenRouter's \"openai/\" or Google's \"models/\" is\n// ignored.\nfunction acceptsTemperature(provider: LLMProvider, chatModel: string): boolean {\n switch (provider) {\n // The Anthropic SDK sends API version 2026-10-21, which rejects a\n // temperature on every model.\n case \"anthropic\":\n return false;\n case \"openai\":\n return !OPENAI_NO_TEMPERATURE.test(chatModel);\n case \"google\":\n return !GOOGLE_NO_TEMPERATURE.test(chatModel);\n }\n}\n// Returns undefined when no temperature should be sent, leaving the model on\n// its own default: LLM_TEMPERATURE=default, or a model that rejects one.\nfunction resolveTemperature(\n provider: LLMProvider,\n chatModel: string,\n): number | undefined {\n const raw = process.env.LLM_TEMPERATURE?.trim() ?? \"\";\n if (raw.toLowerCase() === \"default\") return undefined;\n if (!acceptsTemperature(provider, chatModel)) {\n if (raw !== \"\") {\n warnOnce(\n `Ignoring LLM_TEMPERATURE: ${chatModel} does not accept a custom temperature.`,\n );\n }\n return undefined;\n }\n if (raw === \"\") return DEFAULT_TEMPERATURE;\n const value = Number(raw);\n if (!Number.isFinite(value) || value < 0 || value > MAX_TEMPERATURE) {\n warnOnce(\n `Ignoring LLM_TEMPERATURE=\"${raw}\": use a number from 0 to ${MAX_TEMPERATURE}, or \"default\".`,\n );\n return DEFAULT_TEMPERATURE;\n }\n return value;\n}\nfunction validateAPIKeys(provider: LLMProvider): void {\n const requiredKeys: Record<LLMProvider, string> = {\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n google: \"GOOGLE_API_KEY\",\n };\n const keyName = requiredKeys[provider];\n const keyValue = process.env[keyName];\n if (!keyValue) {\n throw new Error(\n `Missing API key for ${provider}. Please set ${keyName} in your environment variables.`,\n );\n }\n if (provider === \"anthropic\" && !process.env.OPENAI_API_KEY) {\n throw new Error(\n \"Anthropic provider requires OPENAI_API_KEY for embeddings. Please set OPENAI_API_KEY in your environment variables.\",\n );\n }\n}\nexport function isLLMAvailable(): boolean {\n const provider = (process.env.LLM_PROVIDER || \"openai\") as LLMProvider;\n const requiredKeys: Record<LLMProvider, string> = {\n openai: \"OPENAI_API_KEY\",\n anthropic: \"ANTHROPIC_API_KEY\",\n google: \"GOOGLE_API_KEY\",\n };\n const keyName = requiredKeys[provider];\n if (!keyName || !process.env[keyName]) return false;\n if (provider === \"anthropic\" && !process.env.OPENAI_API_KEY) return false;\n return true;\n}\nexport function getLLMConfig(): LLMConfig {\n const provider = (process.env.LLM_PROVIDER || \"openai\") as LLMProvider;\n if (![\"openai\", \"anthropic\", \"google\"].includes(provider)) {\n throw new Error(\n `Invalid LLM_PROVIDER: ${provider}. Must be one of: openai, anthropic, google`,\n );\n }\n validateAPIKeys(provider);\n const defaults = PROVIDER_DEFAULTS[provider];\n // Vectors are Matryoshka-truncated to this many dimensions before being\n // stored as int8, keeping the prebuilt search index small. Must match between\n // build time and runtime; a mismatch forces a re-embed. Values >= the model's\n // native dimension keep full precision (default: 512).\n const rawDims = process.env.LLM_EMBEDDING_DIMS;\n let embeddingDims = 512;\n if (rawDims !== undefined && rawDims !== \"\") {\n const parsed = parseInt(rawDims, 10);\n if (Number.isFinite(parsed) && parsed >= 0) embeddingDims = parsed;\n }\n const chatModel = process.env.LLM_CHAT_MODEL || defaults.chat;\n return {\n provider,\n chatModel,\n embeddingModel: process.env.LLM_EMBEDDING_MODEL || defaults.embedding,\n embeddingDims,\n temperature: resolveTemperature(provider, chatModel),\n };\n}\n";
@@ -5,37 +5,47 @@ export const llmConfigTemplate = `import type {
5
5
  } from "@/services/llm/types";
6
6
  const PROVIDER_DEFAULTS: ProviderDefaults = {
7
7
  openai: {
8
- chat: "gpt-4.1-mini",
8
+ chat: "gpt-6-luna",
9
9
  embedding: "text-embedding-3-small",
10
10
  },
11
11
  anthropic: {
12
- chat: "claude-sonnet-4-5-20250929",
12
+ chat: "claude-haiku-5-5",
13
13
  embedding: "text-embedding-3-small", // Fallback to OpenAI
14
14
  },
15
15
  google: {
16
- chat: "gemini-2.5-flash-lite",
16
+ chat: "gemini-3.5-flash-lite",
17
17
  embedding: "gemini-embedding-001",
18
18
  },
19
19
  };
20
20
  // Used when LLM_TEMPERATURE is unset, for models that accept a temperature.
21
21
  const DEFAULT_TEMPERATURE = 0;
22
- const MAX_TEMPERATURE: Record<LLMProvider, number> = {
23
- openai: 2,
24
- anthropic: 1,
25
- google: 2,
26
- };
22
+ // OpenAI and Google both accept 0 to 2.
23
+ const MAX_TEMPERATURE = 2;
27
24
  // OpenAI's reasoning models (o1, o3, o4-mini) and its GPT-5 line onwards reject
28
- // a custom temperature, some of them any temperature at all. A vendor prefix
29
- // such as OpenRouter's "openai/" is ignored.
30
- const NO_TEMPERATURE_MODEL = /^(?:[\\w-]+\\/)?(?:gpt-(?:[5-9]|\\d{2,})|o\\d)/;
25
+ // a custom temperature, some of them any temperature at all.
26
+ const OPENAI_NO_TEMPERATURE = /^(?:[\\w-]+\\/)?(?:gpt-(?:[5-9]|\\d{2,})|o\\d)/;
27
+ // Gemini 3.5 models onwards ignore a temperature, and Google says later
28
+ // generations will reject it.
29
+ const GOOGLE_NO_TEMPERATURE = /^(?:[\\w-]+\\/)?gemini-(?:3\\.[5-9]|[4-9]|\\d{2,})/;
31
30
  const warnings = new Set<string>();
32
31
  function warnOnce(message: string): void {
33
32
  if (warnings.has(message)) return;
34
33
  warnings.add(message);
35
34
  console.warn(message);
36
35
  }
36
+ // A vendor prefix such as OpenRouter's "openai/" or Google's "models/" is
37
+ // ignored.
37
38
  function acceptsTemperature(provider: LLMProvider, chatModel: string): boolean {
38
- return provider !== "openai" || !NO_TEMPERATURE_MODEL.test(chatModel);
39
+ switch (provider) {
40
+ // The Anthropic SDK sends API version 2026-10-21, which rejects a
41
+ // temperature on every model.
42
+ case "anthropic":
43
+ return false;
44
+ case "openai":
45
+ return !OPENAI_NO_TEMPERATURE.test(chatModel);
46
+ case "google":
47
+ return !GOOGLE_NO_TEMPERATURE.test(chatModel);
48
+ }
39
49
  }
40
50
  // Returns undefined when no temperature should be sent, leaving the model on
41
51
  // its own default: LLM_TEMPERATURE=default, or a model that rejects one.
@@ -45,21 +55,21 @@ function resolveTemperature(
45
55
  ): number | undefined {
46
56
  const raw = process.env.LLM_TEMPERATURE?.trim() ?? "";
47
57
  if (raw.toLowerCase() === "default") return undefined;
48
- const accepted = acceptsTemperature(provider, chatModel);
49
- if (raw === "") return accepted ? DEFAULT_TEMPERATURE : undefined;
50
- const value = Number(raw);
51
- const max = MAX_TEMPERATURE[provider];
52
- if (!Number.isFinite(value) || value < 0 || value > max) {
53
- warnOnce(
54
- \`Ignoring LLM_TEMPERATURE="\${raw}": \${provider} accepts a number from 0 to \${max}, or "default".\`,
55
- );
56
- return accepted ? DEFAULT_TEMPERATURE : undefined;
58
+ if (!acceptsTemperature(provider, chatModel)) {
59
+ if (raw !== "") {
60
+ warnOnce(
61
+ \`Ignoring LLM_TEMPERATURE: \${chatModel} does not accept a custom temperature.\`,
62
+ );
63
+ }
64
+ return undefined;
57
65
  }
58
- if (!accepted) {
66
+ if (raw === "") return DEFAULT_TEMPERATURE;
67
+ const value = Number(raw);
68
+ if (!Number.isFinite(value) || value < 0 || value > MAX_TEMPERATURE) {
59
69
  warnOnce(
60
- \`Ignoring LLM_TEMPERATURE: \${chatModel} does not accept a custom temperature.\`,
70
+ \`Ignoring LLM_TEMPERATURE="\${raw}": use a number from 0 to \${MAX_TEMPERATURE}, or "default".\`,
61
71
  );
62
- return undefined;
72
+ return DEFAULT_TEMPERATURE;
63
73
  }
64
74
  return value;
65
75
  }
@@ -1 +1 @@
1
- export declare const llmIndexTemplate = "export * from \"@/services/llm/types\";\nexport * from \"@/services/llm/config\";\nexport * from \"@/services/llm/factory\";\n";
1
+ export declare const llmIndexTemplate = "export * from \"@/services/llm/types\";\nexport * from \"@/services/llm/config\";\nexport * from \"@/services/llm/factory\";\nexport * from \"@/services/llm/stream\";\n";
@@ -1,4 +1,5 @@
1
1
  export const llmIndexTemplate = `export * from "@/services/llm/types";
2
2
  export * from "@/services/llm/config";
3
3
  export * from "@/services/llm/factory";
4
+ export * from "@/services/llm/stream";
4
5
  `;
@@ -0,0 +1 @@
1
+ export declare const llmStreamTemplate = "import type { AIMessageChunk } from \"@langchain/core/messages\";\n\n/**\n * The answer text in a streamed chat chunk. A chunk's content can also hold\n * reasoning, thinking signature, or tool blocks, which must never reach the\n * reader, so only text blocks are kept.\n */\nexport function chunkText(chunk: AIMessageChunk | undefined): string {\n return chunk?.text ?? \"\";\n}\n";
@@ -0,0 +1,11 @@
1
+ export const llmStreamTemplate = `import type { AIMessageChunk } from "@langchain/core/messages";
2
+
3
+ /**
4
+ * The answer text in a streamed chat chunk. A chunk's content can also hold
5
+ * reasoning, thinking signature, or tool blocks, which must never reach the
6
+ * reader, so only text blocks are kept.
7
+ */
8
+ export function chunkText(chunk: AIMessageChunk | undefined): string {
9
+ return chunk?.text ?? "";
10
+ }
11
+ `;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doccupine",
3
- "version": "0.0.160",
3
+ "version": "0.0.162",
4
4
  "description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -10,7 +10,7 @@
10
10
  "engines": {
11
11
  "node": ">=22.12.0"
12
12
  },
13
- "packageManager": "pnpm@12.9.1",
13
+ "packageManager": "pnpm@12.18.0",
14
14
  "scripts": {
15
15
  "clean": "node scripts/clean.mjs",
16
16
  "build": "pnpm clean && tsc",
@@ -42,25 +42,26 @@
42
42
  "author": "Luan Gjokaj",
43
43
  "license": "SEE LICENSE IN LICENSE",
44
44
  "dependencies": {
45
- "@readme/openapi-parser": "^9.0.0",
45
+ "@readme/openapi-parser": "^10.0.0",
46
46
  "chalk": "^6.0.1",
47
- "chokidar": "^5.0.0",
48
- "commander": "^15.0.0",
47
+ "chokidar": "^6.0.0",
48
+ "commander": "^15.1.0",
49
49
  "fs-extra": "^11.4.1",
50
50
  "gray-matter": "^4.0.3",
51
- "lucide-react": "^1.52.0",
52
- "next": "^16.3.8",
51
+ "lucide-react": "^1.73.0",
52
+ "next": "^16.4.6",
53
53
  "prompts": "^2.4.2",
54
- "react": "^19.3.0",
55
- "react-dom": "^19.3.0"
54
+ "react": "^19.3.1",
55
+ "react-dom": "^19.3.1"
56
56
  },
57
57
  "devDependencies": {
58
+ "@langchain/core": "^1.4.1",
58
59
  "@types/fs-extra": "^11.0.4",
59
- "@types/node": "^26.6.4",
60
+ "@types/node": "^26.6.6",
60
61
  "@types/prompts": "^2.4.9",
61
- "prettier": "^3.9.9",
62
+ "prettier": "^3.10.1",
62
63
  "typescript": "^7.0.2",
63
- "vitest": "^5.0.3"
64
+ "vitest": "^5.1.0"
64
65
  },
65
66
  "files": [
66
67
  "dist/**/*"