doccupine 0.0.163 → 0.0.164

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
@@ -11,356 +11,61 @@
11
11
 
12
12
  # Doccupine
13
13
 
14
- [Doccupine](https://doccupine.com) is an open-source CLI that turns a directory of MDX files into a full-featured Next.js documentation website. Write your docs in Markdown, and Doccupine watches for changes, generates pages, and starts a live dev server automatically.
15
-
16
- ## Features
17
-
18
- - **Live preview** - watches your MDX files and regenerates pages on every save
19
- - **Auto-generated navigation** - sidebar built from frontmatter (`category`, `order`)
20
- - **Sections** - organize docs into tabbed sections via frontmatter or `sections.json`
21
- - **API reference** - point at an OpenAPI spec to generate interactive endpoint pages with a live playground
22
- - **Subscribable changelogs** - pages using the `Update` component publish an RSS feed at `{page-url}/rss.xml`
23
- - **Theming** - dark/light mode with customizable theme via `theme.json`
24
- - **AI chat assistant** - built-in RAG-powered chat (OpenAI, Anthropic, or Google)
25
- - **MCP server** - exposes `search_docs`, `get_doc`, and `list_docs` tools for AI agents
26
- - **Custom fonts** - Google Fonts or local fonts via `fonts.json`
27
- - **Static assets** - `public/` directory is watched and synced to the generated app
28
- - **Lean icons** - only the Lucide glyphs your pages, navigation, footer links, and components use are bundled; an unknown icon name warns when the site is generated and renders nothing
29
- - **Password protection** - gate the whole site behind a shared password with `SITE_PASSWORD`
30
- - **Zero config to start** - `npx doccupine` scaffolds everything and starts the server
31
-
32
- ## Quick Start
33
-
34
- Make sure you have [Node.js](https://nodejs.org) (v22.12.0+) installed.
14
+ Turn a folder of MDX files into a fast, good-looking documentation site, with AI chat and an MCP server built in. One command, no config to start.
35
15
 
36
16
  ```bash
37
17
  npx doccupine
38
18
  ```
39
19
 
40
- Doccupine will prompt you for:
41
-
42
- 1. A directory to store your MDX files (default: `docs`)
43
- 2. An output directory for the generated Next.js app (default: `nextjs-app`)
44
- 3. An optional path to an OpenAPI spec for an API reference (blank to skip)
45
-
46
- It then scaffolds the app, installs dependencies, and starts the dev server. Open http://localhost:3000 to view your docs.
47
-
48
- The source and output directories must not overlap. To prevent accidental data loss, Doccupine only claims an empty output directory, one containing harmless local metadata such as `.DS_Store` or `.env.local`, or an existing Doccupine-generated app. Run `doccupine config --reset` if an older configuration no longer passes validation.
49
-
50
- ## CLI Commands
20
+ Doccupine asks where your MDX files live (default `docs`) and where to put the generated Next.js app (default `nextjs-app`), then installs everything and starts a live preview at http://localhost:3000. Edit a file, and the page updates. Requires [Node.js](https://nodejs.org) 22.12 or later.
21
+
22
+ **[Read the full documentation →](https://docs.doccupine.com)**
23
+
24
+ ## What you get
25
+
26
+ - **Live preview.** Pages regenerate on every save.
27
+ - [Commands](https://docs.doccupine.com/commands)
28
+ - **Navigation and sections.** The sidebar comes from your frontmatter, and sections split the docs into tabs.
29
+ - [Navigation](https://docs.doccupine.com/navigation) · [Sections](https://docs.doccupine.com/sections)
30
+ - **Components.** Callouts, tabs, steps, cards, code blocks, Mermaid diagrams and more, ready to use in MDX.
31
+ - [Components](https://docs.doccupine.com/components)
32
+ - **API reference.** Point it at an OpenAPI spec and get a page per endpoint with a live playground.
33
+ - [API Playground](https://docs.doccupine.com/api-playground)
34
+ - **AI chat assistant.** Visitors ask questions and get answers from your docs, using OpenAI, Anthropic or Google.
35
+ - [AI Assistant](https://docs.doccupine.com/ai-assistant)
36
+ - **MCP server.** AI tools like Claude, Cursor and VS Code can search your docs directly.
37
+ - [Model Context Protocol](https://docs.doccupine.com/model-context-protocol)
38
+ - **Languages and versions.** Translate your docs and keep older releases online.
39
+ - [Languages](https://docs.doccupine.com/languages) · [Versions](https://docs.doccupine.com/versions)
40
+ - **Theming.** Light and dark mode, your colors and fonts.
41
+ - [Theme](https://docs.doccupine.com/theme) · [Fonts](https://docs.doccupine.com/fonts)
42
+ - **Password protection.** Gate the whole site behind a shared password.
43
+ - [Authentication](https://docs.doccupine.com/authentication)
44
+ - **Built for search engines and AI.** Sitemap, `robots.txt`, `llms.txt` and a Markdown copy of every page are generated for you.
45
+ - **Changelogs with RSS.** Publish release notes that readers can subscribe to.
46
+ - [Update component](https://docs.doccupine.com/update)
47
+
48
+ ## Commands
51
49
 
52
50
  ```bash
53
- doccupine watch [options] # Default. Watch MDX files and start dev server
54
- doccupine build [options] # Generate the site without installing or serving it
55
- doccupine generate [options] # Alias for build
56
- doccupine config --show # Show current configuration
57
- doccupine config --reset # Re-prompt for configuration
58
- ```
59
-
60
- ### Options
61
-
62
- `watch` (default):
63
-
64
- | Flag | Description |
65
- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
66
- | `--port <port>` | Port for the dev server (default: `3000`). Auto-increments if taken. |
67
- | `--verbose` | Show all Next.js output including compilation details |
68
- | `--reset` | Re-prompt for watch/output directories |
69
- | `--skip-install` | Generate and serve without running the dependency installer (installs are skipped automatically when `package.json` is unchanged) |
70
- | `--package-manager <name>` | Package manager for the generated app: `pnpm` or `npm` (default: auto-detect). Overrides the `packageManager` field in `doccupine.json`. |
71
-
72
- `build`:
73
-
74
- | Flag | Description |
75
- | --------- | -------------------------------------- |
76
- | `--reset` | Re-prompt for watch/output directories |
77
-
78
- `config`:
79
-
80
- | Flag | Description |
81
- | --------- | ---------------------------------------- |
82
- | `--show` | Print the current configuration and exit |
83
- | `--reset` | Re-prompt for watch/output directories |
84
-
85
- ## MDX Frontmatter
86
-
87
- Each MDX file supports these frontmatter fields:
88
-
89
- ```yaml
90
- ---
91
- title: "Page Title"
92
- description: "Page description for SEO"
93
- category: "Getting Started"
94
- categoryOrder: 0 # Sort order for the category group
95
- order: 1 # Sort order within the category
96
- navIcon: "book-open" # Lucide icon name shown next to the page in the sidebar
97
- categoryIcon: "rocket" # Lucide icon name shown next to the category group
98
- name: "My Docs" # Override site name in title suffix
99
- icon: "https://..." # Page favicon URL
100
- image: "https://..." # OpenGraph image URL
101
- date: "2025-01-01" # Page date metadata
102
- updated: "2025-02-01" # Last-modified date (JSON-LD dateModified)
103
- section: "API Reference" # Section this page belongs to
104
- sectionOrder: 1 # Sort order for the section in the tab bar
105
- openapi: "GET /users/{id}" # Embed an API playground for this endpoint (see API Reference)
106
- rss: true # Show an RSS button linking to the page's feed (pages with Update components)
107
- ---
108
- ```
109
-
110
- Navigation is auto-generated from `category`, `categoryOrder`, and `order`. Pages without a category appear ungrouped.
111
-
112
- Use `sectionLabel` on your root `index.mdx` to rename the default "Docs" tab:
113
-
114
- ```yaml
115
- ---
116
- title: "Welcome"
117
- sectionLabel: "Guides"
118
- ---
119
- ```
120
-
121
- ## Sections
122
-
123
- Sections let you split your docs into separate tabbed groups (e.g. "Docs", "API Reference", "SDKs"). There are two ways to configure them:
124
-
125
- ### Via frontmatter
126
-
127
- Add a `section` field to your MDX files. The section slug is derived from the label automatically. Use `sectionOrder` to control tab order (lower numbers appear first):
128
-
129
- ```yaml
130
- ---
131
- title: "Authentication"
132
- section: "API Reference"
133
- sectionOrder: 1
134
- ---
135
- ```
136
-
137
- Pages without a `section` field stay at the root URL under the default "Docs" tab.
138
-
139
- ### Via `sections.json`
140
-
141
- For full control, create a `sections.json` file in your project root:
142
-
143
- ```json
144
- [
145
- { "label": "Docs", "slug": "" },
146
- { "label": "API Reference", "slug": "api" },
147
- { "label": "SDKs", "slug": "sdks" }
148
- ]
149
- ```
150
-
151
- Each entry has:
152
-
153
- - `label` - display name shown in the section bar
154
- - `slug` - URL prefix for this section (use `""` for the root section)
155
- - `directory` (optional) - subdirectory containing this section's MDX files, only needed when the directory name differs from the slug
156
-
157
- ```json
158
- [
159
- { "label": "Guides", "slug": "", "directory": "guides" },
160
- { "label": "API Reference", "slug": "api", "directory": "api-reference" }
161
- ]
162
- ```
163
-
164
- ## Languages
165
-
166
- Translate your docs by adding a `languages.json` file in your project root and one folder per language inside the docs directory. The default language stays at the docs root with unprefixed URLs; every other language lives in a folder named after its code, which is also its URL prefix:
167
-
168
- ```json
169
- [
170
- { "code": "en", "label": "English", "default": true },
171
- { "code": "de", "label": "Deutsch" }
172
- ]
173
- ```
174
-
175
- ```text
176
- docs/
177
- guides/intro.mdx -> /guides/intro
178
- de/guides/intro.mdx -> /de/guides/intro
179
- ```
180
-
181
- - `code` - a lowercase URL segment (`en`, `de`, `pt-br`); the folder name, the URL prefix, and the `lang`/`hreflang` value
182
- - `label` - the name shown in the sidebar's language dropdown, on the footer row with the focus-mode and theme toggles
183
- - `default` - exactly one entry; its pages live at the docs root
184
- - `strings` (optional) - overrides for the generated site's own labels in that language (search box, sidebar, "On this page", previous/next, action bar, code blocks, AI chat, footer); the key list is documented on the generated site's Languages page
185
-
186
- Only translated pages exist in a language (an untranslated page is a 404 under that prefix, and the switcher falls back to the language's home). The sidebar, search, AI chat, and `llms.txt` are scoped to the current language; translated pages carry `hreflang` alternates with an `x-default`, and the sitemap lists them. A language code must not collide with a section slug, a version slug, or the reserved segments `api`, `gate`, `mcp`, and `ingest`.
187
-
188
- ## Versions
189
-
190
- Keep older releases online by adding a `versions.json` file in your project root and one folder per older version. The default version is the docs root; every other version is a folder named after its slug holding a full copy of the docs as they were:
191
-
192
- ```json
193
- [
194
- { "label": "v2.0", "default": true },
195
- { "slug": "v1", "label": "v1.0" }
196
- ]
197
- ```
198
-
199
- ```text
200
- docs/
201
- guides/intro.mdx -> /guides/intro
202
- v1/guides/intro.mdx -> /v1/guides/intro
203
- de/v1/guides/intro.mdx -> /de/v1/guides/intro
51
+ doccupine # watch your docs and run the live preview (same as `doccupine watch`)
52
+ doccupine build # generate the site once, for CI or deployment
53
+ doccupine config --show # show the saved configuration
54
+ doccupine config --reset # reset the saved configuration
204
55
  ```
205
56
 
206
- The default entry has no `slug`. Versions combine with languages; the language folder comes first. The sidebar shows a version dropdown on the footer row with the focus-mode and theme toggles, and the sidebar, search, AI chat, and `llms.txt` are scoped to the current version. The API reference generated from an OpenAPI spec is published in the default language and version only.
57
+ All options are in the [Commands](https://docs.doccupine.com/commands) docs.
207
58
 
208
- For both features, `navigation.json` in object form is keyed by URL prefix: `""`, `"api"`, `"de"`, `"de/api"`, `"v1"`, `"de/v1/api"`. Existing files keyed by section slug keep working.
209
-
210
- ## API Reference
211
-
212
- Point Doccupine at an OpenAPI document (`.json`, `.yaml`, or `.yml`, OpenAPI 3.0/3.1) and it generates an interactive API reference: a directory at `/api-reference` linking every operation, plus one page per operation with a live playground for sending requests. Set the `openapi` field in `doccupine.json`:
213
-
214
- ```json
215
- {
216
- "openapi": "openapi.json"
217
- }
218
- ```
219
-
220
- The endpoint pages are grouped into their own "API Reference" tab, and your hand-written docs move under a "Documentation" tab. The spec file is watched, so edits regenerate the reference live.
221
-
222
- You can pass multiple specs as an array of paths, or name them explicitly:
223
-
224
- ```json
225
- {
226
- "openapi": [
227
- { "name": "Public API", "file": "openapi.json" },
228
- { "name": "Admin API", "file": "admin-openapi.yaml" }
229
- ]
230
- }
231
- ```
232
-
233
- To embed a single endpoint's playground inline within a hand-written page, add an `openapi` frontmatter field set to `"METHOD /path"` (or the operation's `operationId`):
234
-
235
- ```yaml
236
- ---
237
- title: "Fetch a User"
238
- openapi: "GET /users/{id}"
239
- ---
240
- ```
241
-
242
- ## Configuration Files
243
-
244
- Place these JSON files in your project root (where you run `doccupine`). They are auto-copied to the generated app and watched for changes.
245
-
246
- | File | Purpose |
247
- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
248
- | `doccupine.json` | CLI config (`watchDir`, `outputDir`, `port`, `packageManager`, `openapi`). Auto-generated on first run. Paths are stored relative to the project root, so the file is safe to commit. |
249
- | `config.json` | Site metadata: `name`, `description`, `icon`, `image`, `url` (public site URL for sitemap/robots) |
250
- | `theme.json` | Theme overrides for [cherry-styled-components](https://github.com/cherry-design-system/styled-components) |
251
- | `navigation.json` | Manual navigation structure (overrides auto-generated) |
252
- | `links.json` | Static header/footer links |
253
- | `fonts.json` | Font configuration (Google Fonts or local) |
254
- | `sections.json` | Section definitions for tabbed doc groups (see [Sections](#sections)) |
255
- | `languages.json` | Languages and their folders (see [Languages](#languages)) |
256
- | `versions.json` | Documentation versions and their folders (see [Versions](#versions)) |
257
- | `analytics.json` | Analytics provider configuration (PostHog supported) |
258
-
259
- ## Public Directory
260
-
261
- Place static assets (images, favicons, etc.) in a `public/` directory at your project root. Doccupine copies it to the generated Next.js app on startup and watches for changes, so added, modified, or deleted files are synced automatically.
262
-
263
- ## Sitemap and robots.txt
264
-
265
- Doccupine generates `robots.ts` automatically for every site. When you set a `url` in `config.json`, it also generates `sitemap.ts` covering every page (across all sections) and links the sitemap from `robots.txt`.
266
-
267
- ```json
268
- {
269
- "name": "My Docs",
270
- "url": "https://docs.example.com"
271
- }
272
- ```
273
-
274
- You can override the URL at deploy time by setting the `NEXT_PUBLIC_SITE_URL` environment variable. When no URL is configured, `/sitemap.xml` is still served but stays empty, and `robots.txt` omits its sitemap reference until a public URL is available. The variable is baked in at build time, so changing it needs a redeploy.
275
-
276
- ## llms.txt
277
-
278
- Doccupine generates [llms.txt](https://llmstxt.org) artifacts so AI agents can discover and ingest your docs. On every regeneration, the following files are written to the generated app's `public/` directory:
279
-
280
- | File | Contents |
281
- | ------------------ | --------------------------------------------------------------------------------------- |
282
- | `llms.txt` | Index of every page (title, description, URL), grouped by section and category |
283
- | `llms-full.txt` | Full-text bundle: every page's body concatenated for one-shot ingestion |
284
- | `public/<slug>.md` | Per-page Markdown mirror of each MDX page, suitable for direct fetching at `/<slug>.md` |
285
-
286
- With [languages](#languages) or [versions](#versions) configured, the root `llms.txt` and `llms-full.txt` describe the default language and version and link to the other variants, each of which has its own pair under its URL prefix (`/de/llms.txt`, `/v1/llms-full.txt`).
287
-
288
- The site name and description used in `llms.txt` come from `config.json` (`name`, `description`). Page URLs are absolute when `url` is set in `config.json` (or via `NEXT_PUBLIC_SITE_URL`), and root-relative otherwise.
289
-
290
- A `.doccupine-artifacts.json` file in the generated app tracks generated route ownership and per-page mirrors so renamed or deleted sources clean up only their own outputs. Don't commit this file; it is regenerated automatically.
291
-
292
- ## AI Chat Setup
293
-
294
- The generated app includes an AI chat assistant. To enable it, create a `.env` file in the generated app directory:
295
-
296
- ```env
297
- LLM_PROVIDER=openai # openai | anthropic | google
298
-
299
- # API Keys (set the one matching your provider)
300
- OPENAI_API_KEY=sk-...
301
- ANTHROPIC_API_KEY=sk-ant-...
302
- GOOGLE_API_KEY=...
303
- ```
304
-
305
- If `LLM_PROVIDER` is not set, the chat component is hidden automatically.
306
-
307
- > **Note:** Anthropic does not provide an embeddings API. When using `anthropic` as your provider, you must also set `OPENAI_API_KEY` for embeddings to work.
308
-
309
- ### Optional overrides
310
-
311
- ```env
312
- LLM_CHAT_MODEL=gpt-6-luna # Override the default chat model
313
- LLM_EMBEDDING_MODEL=text-embedding-3-small # Override the default embedding model
314
- LLM_TEMPERATURE=0 # Set temperature (default: 0; "default" sends none)
315
- LLM_EMBEDDING_DIMS=512 # Dimensions for the prebuilt search index (default: 512)
316
- RAG_RUNTIME_EMBED_MAX_CHUNKS=400 # Max chunks embedded on demand in production (default: 400; 0 requires a prebuilt index)
317
- # RAG_API_KEY=... # Optional bearer auth for direct /api/rag requests
318
- ```
319
-
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
-
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
-
324
- Public documentation leaves browser chat available by default. Setting `RAG_API_KEY` requires a bearer token for `/api/rag` and is intended for server-to-server use; the built-in browser cannot safely hold that secret. Use `SITE_PASSWORD` instead when authenticated browser visitors should retain chat access.
325
-
326
- Default models per provider:
327
-
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
-
334
- ## MCP Server
335
-
336
- The generated app exposes an MCP endpoint at `/api/mcp` with three tools:
337
-
338
- - `search_docs` - semantic search across all documentation
339
- - `get_doc` - retrieve a specific document by path
340
- - `list_docs` - list all available documents
341
-
342
- The endpoint serves both the stateless MCP `2026-07-28` revision and 2025-era clients that open with the `initialize` handshake, built on `@modelcontextprotocol/server`.
343
-
344
- This lets AI agents (Claude, ChatGPT, etc.) query your docs programmatically. Semantic `search_docs` requires the AI setup above for embeddings; `get_doc` and `list_docs` work from the generated content manifest without an embedding provider. On a site with [languages](#languages) or [versions](#versions), `search_docs` and `list_docs` accept optional `language` and `version` parameters and default to the default language and version; the `docs://list` resource lists every variant.
345
-
346
- ## Password Protection
347
-
348
- Gate your entire documentation site behind a shared password by setting `SITE_PASSWORD` in the generated app's environment - add it to `.env` for local development, or your host's environment variables in production:
349
-
350
- ```env
351
- SITE_PASSWORD=choose-a-strong-shared-password
352
- ```
59
+ ## Deploy
353
60
 
354
- When set, every visitor sees a login screen until they enter the password. Protection is enforced across three layers:
61
+ The generated app is a standard Next.js project, so it runs anywhere Next.js does. See [Deployment & Hosting](https://docs.doccupine.com/deployment-and-hosting).
355
62
 
356
- - **Pages** are gated behind the login screen.
357
- - **Content APIs** (`/api/rag` chat, `/api/search`, and the `/api/playground` proxy) return `401` without a valid session, so the docs can't be scraped and the proxy can't relay anonymous requests around the login. Each route re-checks the session itself, not just the middleware.
358
- - **Search engines and crawlers** are blocked: `robots.txt` disallows everything, pages carry a `noindex, nofollow` tag, and responses include an `X-Robots-Tag` header.
63
+ Prefer not to host it yourself? [Doccupine](https://doccupine.com) builds, hosts and updates your docs site for you.
359
64
 
360
- A successful login sets a signed, `httpOnly` cookie that lasts 30 days. The cookie stores an HMAC of the password, never the password itself. Leave `SITE_PASSWORD` unset (the default) to keep the site fully public. Documentation pages stay statically rendered either way - the gate is enforced in middleware.
65
+ ## Contributing
361
66
 
362
- > **Note:** The [MCP endpoint](#mcp-server) uses `DOCS_API_KEY` bearer authentication when configured. Without an API key, a password-protected site requires the normal gate session for MCP as well.
67
+ Bug reports and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md), and report security issues as described in [SECURITY.md](SECURITY.md).
363
68
 
364
69
  ## License
365
70
 
366
- This project is licensed under a modified MIT license with a SaaS restriction. See [LICENSE](LICENSE) for details.
71
+ Modified MIT license with a SaaS restriction. See [LICENSE](LICENSE).
@@ -1 +1 @@
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
+ 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## Never Mention the Context\nThe context is retrieved behind the scenes; the user never sees it and does not know it exists. Speak as if you simply know the documentation.\n- Never refer to \"the context\", \"the provided context\", \"the excerpts\", \"the chunks\", \"the sources I was given\" or similar. Phrases like \"The context also describes...\" or \"Based on the provided context...\" are forbidden.\n- Never comment on what you were or were not given, how the information reached you, or how you work internally.\n- Refer to the material as \"the documentation\" or \"the docs\", or just state the facts directly.\n- When something isn't covered, say \"The documentation doesn't cover that\" rather than \"That isn't in the context\".\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";
@@ -66,6 +66,13 @@ const systemContext = \`You are AI Assistant, a documentation assistant for \${p
66
66
  2. If the answer isn't in the context, say so clearly and suggest relevant sections or pages the user might check.
67
67
  3. If the question is ambiguous, ask a brief clarifying question before answering.
68
68
 
69
+ ## Never Mention the Context
70
+ The context is retrieved behind the scenes; the user never sees it and does not know it exists. Speak as if you simply know the documentation.
71
+ - Never refer to "the context", "the provided context", "the excerpts", "the chunks", "the sources I was given" or similar. Phrases like "The context also describes..." or "Based on the provided context..." are forbidden.
72
+ - Never comment on what you were or were not given, how the information reached you, or how you work internally.
73
+ - Refer to the material as "the documentation" or "the docs", or just state the facts directly.
74
+ - When something isn't covered, say "The documentation doesn't cover that" rather than "That isn't in the context".
75
+
69
76
  ## Response Style
70
77
  - Be concise and direct. Lead with the answer, then provide details if needed.
71
78
  - Use code examples from the context when relevant.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doccupine",
3
- "version": "0.0.163",
3
+ "version": "0.0.164",
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": {