doccupine 0.0.142 → 0.0.144
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 +1 -1
- package/dist/cli.d.ts +6 -0
- package/dist/cli.js +130 -22
- package/dist/generator/api-reference-generator.d.ts +20 -0
- package/dist/generator/api-reference-generator.js +95 -0
- package/dist/generator/app-scaffolder.d.ts +19 -0
- package/dist/generator/app-scaffolder.js +54 -0
- package/dist/generator/generated-route-manager.d.ts +17 -0
- package/dist/generator/generated-route-manager.js +91 -0
- package/dist/generator/page-catalog.d.ts +17 -0
- package/dist/generator/page-catalog.js +68 -0
- package/dist/generator/page-renderer.d.ts +31 -0
- package/dist/generator/page-renderer.js +248 -0
- package/dist/generator/project-config-repository.d.ts +25 -0
- package/dist/generator/project-config-repository.js +133 -0
- package/dist/generator/public-asset-manager.d.ts +20 -0
- package/dist/generator/public-asset-manager.js +225 -0
- package/dist/generator/section-resolver.d.ts +13 -0
- package/dist/generator/section-resolver.js +150 -0
- package/dist/generator/secure-source-fs.d.ts +27 -0
- package/dist/generator/secure-source-fs.js +361 -0
- package/dist/generator/site-artifacts.d.ts +22 -0
- package/dist/generator/site-artifacts.js +159 -0
- package/dist/generator/watch-coordinator.d.ts +57 -0
- package/dist/generator/watch-coordinator.js +438 -0
- package/dist/lib/generated-artifacts.d.ts +3 -0
- package/dist/lib/generated-artifacts.js +27 -1
- package/dist/lib/layout.d.ts +1 -17
- package/dist/lib/layout.js +5 -4
- package/dist/lib/project-config.d.ts +3 -0
- package/dist/lib/project-config.js +110 -0
- package/dist/lib/structures.js +2 -0
- package/dist/lib/types.d.ts +14 -1
- package/dist/mdx-to-nextjs-generator.d.ts +7 -25
- package/dist/mdx-to-nextjs-generator.js +126 -1574
- package/dist/templates/app/api/rag/route.d.ts +1 -1
- package/dist/templates/app/api/rag/route.js +2 -1
- package/dist/templates/components/Chat.d.ts +1 -1
- package/dist/templates/components/Chat.js +2 -1
- package/dist/templates/components/MDXComponents.d.ts +1 -1
- package/dist/templates/components/MDXComponents.js +1 -1
- package/dist/templates/components/layout/Accordion.d.ts +1 -1
- package/dist/templates/components/layout/Accordion.js +2 -3
- package/dist/templates/components/layout/Space.d.ts +1 -0
- package/dist/templates/components/layout/Space.js +70 -0
- package/dist/templates/mdx/space.mdx.d.ts +1 -1
- package/dist/templates/mdx/space.mdx.js +27 -27
- package/dist/templates/next.config.js +2 -2
- package/dist/templates/package.js +2 -2
- package/dist/templates/proxy.js +1 -1
- package/dist/templates/services/mcp/server.d.ts +1 -1
- package/dist/templates/services/mcp/server.js +2 -12
- package/package.json +2 -2
|
@@ -18,19 +18,19 @@ Markdown already spaces paragraphs, headings, lists, and tables for you, and tha
|
|
|
18
18
|
|
|
19
19
|
## Space Usage
|
|
20
20
|
|
|
21
|
-
Set
|
|
21
|
+
Set \`size\` to the gap you want, in pixels.
|
|
22
22
|
|
|
23
23
|
\`\`\`html
|
|
24
24
|
Text above the gap.
|
|
25
25
|
|
|
26
|
-
<Space
|
|
26
|
+
<Space size={60} />
|
|
27
27
|
|
|
28
28
|
Text below the gap.
|
|
29
29
|
\`\`\`
|
|
30
30
|
|
|
31
31
|
Text above the gap.
|
|
32
32
|
|
|
33
|
-
<Space
|
|
33
|
+
<Space size={60} />
|
|
34
34
|
|
|
35
35
|
Text below the gap.
|
|
36
36
|
|
|
@@ -39,87 +39,87 @@ Text below the gap.
|
|
|
39
39
|
A gap that looks right on a wide screen is often too large on a phone. Each breakpoint has its own prop, so you can grow the gap as the viewport widens.
|
|
40
40
|
|
|
41
41
|
\`\`\`html
|
|
42
|
-
<Space
|
|
42
|
+
<Space size={20} md={40} xl={80} />
|
|
43
43
|
\`\`\`
|
|
44
44
|
|
|
45
45
|
That renders a 20px gap by default, 40px from the \`md\` breakpoint up, and 80px from \`xl\` up.
|
|
46
46
|
|
|
47
47
|
Every breakpoint prop is a \`min-width\` media query, so a value applies at that width and every width above it until a larger breakpoint overrides it:
|
|
48
48
|
|
|
49
|
-
| Prop
|
|
50
|
-
|
|
|
51
|
-
|
|
|
52
|
-
|
|
|
53
|
-
|
|
|
54
|
-
|
|
|
55
|
-
|
|
|
56
|
-
|
|
|
57
|
-
|
|
|
49
|
+
| Prop | Applies from |
|
|
50
|
+
| ------ | ------------ |
|
|
51
|
+
| \`xs\` | 0px |
|
|
52
|
+
| \`sm\` | 576px |
|
|
53
|
+
| \`md\` | 768px |
|
|
54
|
+
| \`lg\` | 992px |
|
|
55
|
+
| \`xl\` | 1200px |
|
|
56
|
+
| \`xxl\` | 1440px |
|
|
57
|
+
| \`xxxl\` | 1920px |
|
|
58
58
|
|
|
59
|
-
|
|
59
|
+
\`size\` sets the gap at every width. Use it alone for a constant gap, or as the base that the breakpoint props build on.
|
|
60
60
|
|
|
61
61
|
## Removing the space at a breakpoint
|
|
62
62
|
|
|
63
63
|
Pass \`"none"\` instead of a number to drop the gap entirely at that width. This is the usual way to add breathing room on desktop without wasting vertical space on a phone.
|
|
64
64
|
|
|
65
65
|
\`\`\`html
|
|
66
|
-
<Space
|
|
66
|
+
<Space size="none" lg={64} />
|
|
67
67
|
\`\`\`
|
|
68
68
|
|
|
69
69
|
Here there is no gap at all below the \`lg\` breakpoint, and a 64px gap from \`lg\` up.
|
|
70
70
|
|
|
71
71
|
## Horizontal spacing
|
|
72
72
|
|
|
73
|
-
Add
|
|
73
|
+
Add \`horizontal\` to space things apart along the inline axis instead of the block axis. The size props then control width rather than height.
|
|
74
74
|
|
|
75
75
|
It belongs inside a line of inline content, where a gap along that axis has something to sit between. Dropping one into a button widens the distance between the label and the icon by the size you give it, on top of the spacing the button already applies:
|
|
76
76
|
|
|
77
77
|
\`\`\`html
|
|
78
78
|
<Button icon="arrow-right" iconPosition="right">
|
|
79
79
|
Get started
|
|
80
|
-
<Space
|
|
80
|
+
<Space size={24} horizontal />
|
|
81
81
|
</Button>
|
|
82
82
|
\`\`\`
|
|
83
83
|
|
|
84
84
|
<Button icon="arrow-right" iconPosition="right">
|
|
85
85
|
Get started
|
|
86
|
-
<Space
|
|
86
|
+
<Space size={24} horizontal />
|
|
87
87
|
</Button>
|
|
88
88
|
|
|
89
89
|
## Properties
|
|
90
90
|
|
|
91
|
-
<Field value="
|
|
91
|
+
<Field value="size" type="number | 'none'">
|
|
92
92
|
The gap at every viewport width, in pixels. Pass \`"none"\` to render nothing.
|
|
93
93
|
</Field>
|
|
94
94
|
|
|
95
|
-
<Field value="
|
|
95
|
+
<Field value="xs" type="number | 'none'">
|
|
96
96
|
Overrides the gap from 0px up.
|
|
97
97
|
</Field>
|
|
98
98
|
|
|
99
|
-
<Field value="
|
|
99
|
+
<Field value="sm" type="number | 'none'">
|
|
100
100
|
Overrides the gap from 576px up.
|
|
101
101
|
</Field>
|
|
102
102
|
|
|
103
|
-
<Field value="
|
|
103
|
+
<Field value="md" type="number | 'none'">
|
|
104
104
|
Overrides the gap from 768px up.
|
|
105
105
|
</Field>
|
|
106
106
|
|
|
107
|
-
<Field value="
|
|
107
|
+
<Field value="lg" type="number | 'none'">
|
|
108
108
|
Overrides the gap from 992px up.
|
|
109
109
|
</Field>
|
|
110
110
|
|
|
111
|
-
<Field value="
|
|
111
|
+
<Field value="xl" type="number | 'none'">
|
|
112
112
|
Overrides the gap from 1200px up.
|
|
113
113
|
</Field>
|
|
114
114
|
|
|
115
|
-
<Field value="
|
|
115
|
+
<Field value="xxl" type="number | 'none'">
|
|
116
116
|
Overrides the gap from 1440px up.
|
|
117
117
|
</Field>
|
|
118
118
|
|
|
119
|
-
<Field value="
|
|
119
|
+
<Field value="xxxl" type="number | 'none'">
|
|
120
120
|
Overrides the gap from 1920px up.
|
|
121
121
|
</Field>
|
|
122
122
|
|
|
123
|
-
<Field value="
|
|
123
|
+
<Field value="horizontal" type="boolean">
|
|
124
124
|
Spaces along the inline axis instead of the block axis, so the size props control width. Defaults to false.
|
|
125
125
|
</Field>`;
|
|
@@ -69,11 +69,11 @@ const nextConfig: NextConfig = {
|
|
|
69
69
|
},
|
|
70
70
|
{
|
|
71
71
|
source: "/ingest/static/:path*",
|
|
72
|
-
destination:
|
|
72
|
+
destination: ${JSON.stringify(`${assetsHost}/static/:path*`)},
|
|
73
73
|
},
|
|
74
74
|
{
|
|
75
75
|
source: "/ingest/:path*",
|
|
76
|
-
destination:
|
|
76
|
+
destination: ${JSON.stringify(`${host}/:path*`)},
|
|
77
77
|
},
|
|
78
78
|
];
|
|
79
79
|
},
|
|
@@ -24,8 +24,8 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
24
24
|
minisearch: "^7.2.0",
|
|
25
25
|
next: "16.2.12",
|
|
26
26
|
"next-mdx-remote": "^6.0.0",
|
|
27
|
-
"posthog-js": "^1.
|
|
28
|
-
"posthog-node": "^5.
|
|
27
|
+
"posthog-js": "^1.409.0",
|
|
28
|
+
"posthog-node": "^5.47.0",
|
|
29
29
|
react: "19.2.8",
|
|
30
30
|
"react-dom": "19.2.8",
|
|
31
31
|
"rehype-highlight": "^7.0.2",
|
package/dist/templates/proxy.js
CHANGED
|
@@ -118,7 +118,7 @@ function resolveTrackingIdentity(req: NextRequest): TrackingIdentity {
|
|
|
118
118
|
let deviceId: string | undefined;
|
|
119
119
|
|
|
120
120
|
const phCookie = req.cookies.get(
|
|
121
|
-
|
|
121
|
+
${JSON.stringify(`ph_${analyticsConfig.posthog.key}_posthog`)},
|
|
122
122
|
)?.value;
|
|
123
123
|
if (phCookie) {
|
|
124
124
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listDocs,\n getDoc,\n getAllDocsChunks,\n DOCS_TOOLS,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, isLLMAvailable, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\n\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({ directory: z.string().max(500).optional() })\n .strict();\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built once at server startup since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n// Eagerly start building the index on server startup if LLM is configured\nif (isLLMAvailable()) {\n const initialBuild = buildDocsIndex();\n indexReady = initialBuild;\n // A failed eager build (e.g. a missing prebuilt index on a large doc set) must\n // not surface as an unhandledRejection at startup; the first request retries\n // via ensureDocsIndex and returns a real error to the client.\n void initialBuild.catch(() => {});\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n const scored = docsIndex.chunks\n .map((c) => ({\n chunk: { id: c.id, text: c.text, path: c.path, uri: c.uri },\n score: cosineFloatInt8(queryVector, c.embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit }, { signal }) => {\n const results = await searchDocs(query, limit ?? 6, signal);\n return toolResult(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n );\n },\n );\n\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n );\n },\n );\n\n // Register documentation as resources\n server.resource(\"docs://list\", \"docs://list\", async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n text: resourceText(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n ),\n },\n ],\n };\n });\n\n return server;\n}\n";
|
|
1
|
+
export declare const mcpServerTemplate = "import path from \"node:path\";\nimport fs from \"node:fs\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n listDocs,\n getDoc,\n getAllDocsChunks,\n DOCS_TOOLS,\n} from \"@/services/mcp/tools\";\nimport { getLLMConfig, createEmbeddings } from \"@/services/llm\";\nimport {\n reduceDims,\n quantizeInt8,\n decodeInt8,\n cosineFloatInt8,\n} from \"@/services/mcp/vector\";\nimport type { DocsChunk } from \"@/services/mcp/types\";\n\n/** A doc chunk with its stored int8-quantized embedding. */\ntype IndexedChunk = DocsChunk & { embedding: Int8Array };\n\nexport const MCP_MAX_REQUEST_BYTES = 64 * 1024;\nexport const MCP_MAX_TOOL_ARGUMENT_BYTES = 8 * 1024;\nexport const MCP_MAX_RESULT_BYTES = 256 * 1024;\n\nexport const searchDocsArgsSchema = z\n .object({\n query: z.string().min(1).max(2000),\n limit: z.number().int().min(1).max(20).optional(),\n })\n .strict();\n\nexport const getDocArgsSchema = z\n .object({ path: z.string().min(1).max(500) })\n .strict();\n\nexport const listDocsArgsSchema = z\n .object({ directory: z.string().max(500).optional() })\n .strict();\n\nexport function serializeMCPResult(value: unknown): {\n text: string;\n tooLarge: boolean;\n} {\n const text = JSON.stringify(value, null, 2) ?? \"null\";\n if (new TextEncoder().encode(text).byteLength <= MCP_MAX_RESULT_BYTES) {\n return { text, tooLarge: false };\n }\n return {\n text: JSON.stringify({\n error: \"Tool result exceeds the maximum response size\",\n }),\n tooLarge: true,\n };\n}\n\n/**\n * Thrown when a query arrives but no usable prebuilt embeddings index exists AND\n * the doc set is too large to embed within a single serverless request. Surfaced\n * to the client as a clear \"temporarily unavailable\" message instead of letting\n * the request hang until the platform's function timeout (the old failure mode:\n * the chat connected, streamed heartbeats, and never answered on large docs).\n */\nexport class IndexNotBuiltError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"IndexNotBuiltError\";\n }\n}\n\n/**\n * Max chunks we will embed on demand inside one request when the prebuilt index\n * is missing. Above this, embedding the whole set (one round trip per BATCH_SIZE\n * chunks) cannot finish within a serverless function's time limit, so the chat\n * would hang forever. Only enforced in production - `next dev` has no time cap,\n * so it keeps embedding on demand and works without running the build. Override\n * per deployment with RAG_RUNTIME_EMBED_MAX_CHUNKS (0 = always require a prebuilt\n * index). Parsed defensively so a bad value falls back to the default rather\n * than silently disabling the guard; note `Number(x) || 400` would drop a valid 0.\n */\nfunction resolveRuntimeEmbedMax(): number {\n const raw = process.env.RAG_RUNTIME_EMBED_MAX_CHUNKS;\n if (raw !== undefined && raw !== \"\") {\n const parsed = Number(raw);\n if (Number.isFinite(parsed) && parsed >= 0) return Math.floor(parsed);\n }\n return 400;\n}\nconst RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();\n\n/**\n * In-memory cache for document embeddings.\n * Built lazily on first use since docs are static.\n */\nlet docsIndex: {\n ready: boolean;\n building: boolean;\n chunks: IndexedChunk[];\n} = {\n ready: false,\n building: false,\n chunks: [],\n};\n\n/** Resolves when the initial index build completes */\nlet indexReady: Promise<void> | null = null;\n\n/**\n * Human-readable reason the index is unavailable, or null when healthy. Surfaced\n * by getIndexStatus (and GET /api/rag) so a missing/broken index is diagnosable\n * from outside without reading server logs.\n */\nlet indexUnavailableReason: string | null = null;\n\n/**\n * Absolute path to the embeddings index precomputed at build time by\n * scripts/build-docs-index.mts. Bundled into serverless functions via\n * outputFileTracingIncludes in next.config.ts.\n */\nconst INDEX_FILE = path.join(\n process.cwd(),\n \"services\",\n \"mcp\",\n \"docs-index.json\",\n);\n\n/**\n * Load embeddings precomputed at build time. Returns null when the file is\n * missing/empty, was built with a different provider/model/dimension than the\n * current config, or is not int8-quantized - query and document vectors must\n * come from the same embedding model and the same transform (dims + int8).\n * A null return makes the caller fall back to embedding on demand at runtime.\n */\nfunction loadPrecomputedIndex(): IndexedChunk[] | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(INDEX_FILE, \"utf8\")) as {\n provider?: string;\n embeddingModel?: string;\n dims?: number;\n quantization?: string;\n chunks?: (DocsChunk & { embedding: string })[];\n };\n if (!parsed.chunks || parsed.chunks.length === 0) return null;\n const config = getLLMConfig();\n // Guard on the exact transform: the same dims value at build and query time\n // guarantees reduceDims produces matching-length vectors on both sides.\n if (\n parsed.provider !== config.provider ||\n parsed.embeddingModel !== config.embeddingModel ||\n parsed.dims !== config.embeddingDims ||\n parsed.quantization !== \"int8\"\n ) {\n return null;\n }\n const decoded: IndexedChunk[] = [];\n let expectedLen = -1;\n for (const c of parsed.chunks) {\n const embedding = decodeInt8(c.embedding);\n // Reject a corrupt index rather than scoring against ragged vectors.\n if (expectedLen === -1) expectedLen = embedding.length;\n else if (embedding.length !== expectedLen) return null;\n decoded.push({\n id: c.id,\n text: c.text,\n path: c.path,\n uri: c.uri,\n embedding,\n });\n }\n return decoded;\n } catch {\n return null;\n }\n}\n\n/**\n * Build or rebuild the documentation index\n */\nasync function buildDocsIndex(force = false): Promise<void> {\n if (docsIndex.building) return;\n if (docsIndex.ready && !force) return;\n\n docsIndex.building = true;\n indexUnavailableReason = null;\n try {\n // Prefer embeddings precomputed at build time - avoids re-embedding the\n // entire doc set on every cold start (the main cause of slow first chats).\n if (!force) {\n const precomputed = loadPrecomputedIndex();\n if (precomputed) {\n docsIndex.chunks = precomputed;\n docsIndex.ready = true;\n return;\n }\n }\n\n const chunks = await getAllDocsChunks();\n\n if (chunks.length === 0) {\n docsIndex.chunks = [];\n docsIndex.ready = true;\n return;\n }\n\n // Reaching here means no usable prebuilt index was loaded (missing, empty,\n // or built with a different provider/model/dims). Embedding the whole set on\n // demand only completes in time for small doc sets; for large ones it runs\n // one round trip per BATCH_SIZE chunks and blows past the serverless function\n // limit, so the chat connects and then hangs forever with no answer. In\n // production, fail fast with an actionable error instead of hanging (this\n // also stops a client-forced `refresh` from burning embedding quota).\n if (\n process.env.NODE_ENV === \"production\" &&\n chunks.length > RUNTIME_EMBED_MAX_CHUNKS\n ) {\n indexUnavailableReason =\n `Prebuilt embeddings index missing; refusing to embed ${chunks.length} ` +\n `chunks at request time (limit ${RUNTIME_EMBED_MAX_CHUNKS}). Run the build ` +\n `with an embedding API key set so scripts/build-docs-index.mts writes ` +\n `services/mcp/docs-index.json, then redeploy.`;\n console.error(`[doccupine] ${indexUnavailableReason}`);\n throw new IndexNotBuiltError(\n \"The AI assistant is temporarily unavailable: its documentation search \" +\n \"index has not been built for this deployment. If you are the site \" +\n \"owner, redeploy with an embedding API key available at build time.\",\n );\n }\n\n // Small enough (or local dev): embed on demand. This still re-embeds on every\n // cold start, so a prebuilt index is strongly preferred in production.\n console.warn(\n `[doccupine] No prebuilt embeddings index found; embedding ${chunks.length} ` +\n `chunks on demand. Precompute at build time to avoid this on each cold start.`,\n );\n\n const config = getLLMConfig();\n const embeddings = createEmbeddings(config);\n\n // Process embeddings in small batches to avoid exceeding token limits.\n // Reduce + quantize to the same int8 representation as the precomputed\n // index so searchDocs scores identically on either path.\n const BATCH_SIZE = 10;\n const texts = chunks.map((c) => c.text);\n const built: IndexedChunk[] = [];\n\n for (let i = 0; i < texts.length; i += BATCH_SIZE) {\n const batch = texts.slice(i, i + BATCH_SIZE);\n const batchVectors = await embeddings.embedDocuments(batch);\n for (let j = 0; j < batchVectors.length; j++) {\n built.push({\n ...chunks[i + j],\n embedding: quantizeInt8(\n reduceDims(batchVectors[j], config.embeddingDims),\n ),\n });\n }\n }\n\n docsIndex.chunks = built;\n docsIndex.ready = true;\n } catch (error) {\n // Reset so the next call to ensureDocsIndex retries\n indexReady = null;\n throw error;\n } finally {\n docsIndex.building = false;\n }\n}\n\n/**\n * Ensure the docs index is ready.\n * On first call, triggers the build; subsequent calls wait for the same promise.\n */\nexport async function ensureDocsIndex(\n force = false,\n signal?: AbortSignal,\n): Promise<void> {\n signal?.throwIfAborted();\n if (force) {\n // Wait for any in-flight build before starting a forced rebuild\n if (docsIndex.building && indexReady) {\n await indexReady.catch(() => {});\n }\n docsIndex.ready = false;\n docsIndex.chunks = [];\n indexReady = buildDocsIndex(true);\n } else if (!indexReady) {\n indexReady = buildDocsIndex();\n }\n\n const build = indexReady;\n if (!signal) return build;\n\n // Embedding clients do not expose AbortSignal parameters. Keep the shared\n // index build alive for other requests, but stop this caller waiting as soon\n // as its request is cancelled.\n await new Promise<void>((resolve, reject) => {\n const abort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n void build.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", abort);\n });\n });\n signal.throwIfAborted();\n}\n\nfunction throwIfCancelled(signal?: AbortSignal): void {\n signal?.throwIfAborted();\n}\n\nasync function embedQuery(\n query: string,\n signal?: AbortSignal,\n): Promise<number[]> {\n throwIfCancelled(signal);\n // LangChain's provider-neutral Embeddings interface has no signal option.\n const vector = await getEmbeddings().embedQuery(query);\n throwIfCancelled(signal);\n return vector;\n}\n\nfunction normalizeSearchLimit(limit: number): number {\n if (!Number.isFinite(limit)) return 6;\n return Math.max(1, Math.min(20, Math.floor(limit)));\n}\n\nfunction toolResult(value: unknown) {\n const serialized = serializeMCPResult(value);\n return {\n content: [{ type: \"text\" as const, text: serialized.text }],\n ...(serialized.tooLarge ? { isError: true as const } : {}),\n };\n}\n\nfunction toolError(message: string) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: JSON.stringify({ error: message }),\n },\n ],\n isError: true as const,\n };\n}\n\nfunction resourceText(value: unknown): string {\n return serializeMCPResult(value).text;\n}\n\n/** Cached embeddings instance for search queries */\nlet cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;\n\nfunction getEmbeddings() {\n if (!cachedEmbeddings) {\n cachedEmbeddings = createEmbeddings(getLLMConfig());\n }\n return cachedEmbeddings;\n}\n\n/**\n * Search documents using semantic similarity\n */\nexport async function searchDocs(\n query: string,\n limit = 6,\n signal?: AbortSignal,\n): Promise<{ chunk: DocsChunk; score: number }[]> {\n await ensureDocsIndex(false, signal);\n throwIfCancelled(signal);\n\n // Reduce the query vector with the exact same transform used at index time so\n // dimensions line up. Scoring runs directly against the int8 vectors - cosine\n // is scale-invariant, so no dequantization is needed.\n const rawQueryVector = await embedQuery(query, signal);\n const queryVector = reduceDims(rawQueryVector, getLLMConfig().embeddingDims);\n\n const scored = docsIndex.chunks\n .map((c) => ({\n chunk: { id: c.id, text: c.text, path: c.path, uri: c.uri },\n score: cosineFloatInt8(queryVector, c.embedding),\n }))\n .sort((a, b) => b.score - a.score)\n .slice(0, normalizeSearchLimit(limit));\n\n return scored;\n}\n\n/**\n * Get the current index status\n */\nexport function getIndexStatus(): {\n ready: boolean;\n chunkCount: number;\n reason: string | null;\n} {\n return {\n ready: docsIndex.ready,\n chunkCount: docsIndex.chunks.length,\n reason: indexUnavailableReason,\n };\n}\n\n/**\n * Create and configure the MCP server with documentation tools\n */\nexport function createMCPServer(): McpServer {\n const server = new McpServer({\n name: \"docs-server\",\n version: \"1.0.0\",\n });\n\n // Register the search_docs tool\n server.registerTool(\n \"search_docs\",\n {\n description: DOCS_TOOLS[0].description,\n inputSchema: searchDocsArgsSchema,\n },\n async ({ query, limit }, { signal }) => {\n const results = await searchDocs(query, limit ?? 6, signal);\n return toolResult(\n results.map(({ chunk, score }) => ({\n path: chunk.path,\n uri: chunk.uri,\n score: score.toFixed(3),\n text: chunk.text,\n })),\n );\n },\n );\n\n // Register the get_doc tool\n server.registerTool(\n \"get_doc\",\n {\n description: DOCS_TOOLS[1].description,\n inputSchema: getDocArgsSchema,\n },\n async ({ path }, { signal }) => {\n signal.throwIfAborted();\n const doc = await getDoc({ path });\n signal.throwIfAborted();\n if (!doc) {\n return toolError(\"Document not found\");\n }\n return toolResult(doc);\n },\n );\n\n // Register the list_docs tool\n server.registerTool(\n \"list_docs\",\n {\n description: DOCS_TOOLS[2].description,\n inputSchema: listDocsArgsSchema,\n },\n async ({ directory }, { signal }) => {\n signal.throwIfAborted();\n const docs = await listDocs({ directory });\n signal.throwIfAborted();\n return toolResult(\n docs.map((d) => ({\n name: d.name,\n path: d.path,\n uri: d.uri,\n })),\n );\n },\n );\n\n // Register documentation as resources\n server.resource(\"docs://list\", \"docs://list\", async () => {\n const docs = await listDocs();\n return {\n contents: [\n {\n uri: \"docs://list\",\n text: resourceText(\n docs.map((d) => ({ name: d.name, path: d.path, uri: d.uri })),\n ),\n },\n ],\n };\n });\n\n return server;\n}\n";
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
getAllDocsChunks,
|
|
9
9
|
DOCS_TOOLS,
|
|
10
10
|
} from "@/services/mcp/tools";
|
|
11
|
-
import { getLLMConfig,
|
|
11
|
+
import { getLLMConfig, createEmbeddings } from "@/services/llm";
|
|
12
12
|
import {
|
|
13
13
|
reduceDims,
|
|
14
14
|
quantizeInt8,
|
|
@@ -91,7 +91,7 @@ const RUNTIME_EMBED_MAX_CHUNKS = resolveRuntimeEmbedMax();
|
|
|
91
91
|
|
|
92
92
|
/**
|
|
93
93
|
* In-memory cache for document embeddings.
|
|
94
|
-
* Built
|
|
94
|
+
* Built lazily on first use since docs are static.
|
|
95
95
|
*/
|
|
96
96
|
let docsIndex: {
|
|
97
97
|
ready: boolean;
|
|
@@ -349,16 +349,6 @@ function resourceText(value: unknown): string {
|
|
|
349
349
|
return serializeMCPResult(value).text;
|
|
350
350
|
}
|
|
351
351
|
|
|
352
|
-
// Eagerly start building the index on server startup if LLM is configured
|
|
353
|
-
if (isLLMAvailable()) {
|
|
354
|
-
const initialBuild = buildDocsIndex();
|
|
355
|
-
indexReady = initialBuild;
|
|
356
|
-
// A failed eager build (e.g. a missing prebuilt index on a large doc set) must
|
|
357
|
-
// not surface as an unhandledRejection at startup; the first request retries
|
|
358
|
-
// via ensureDocsIndex and returns a real error to the client.
|
|
359
|
-
void initialBuild.catch(() => {});
|
|
360
|
-
}
|
|
361
|
-
|
|
362
352
|
/** Cached embeddings instance for search queries */
|
|
363
353
|
let cachedEmbeddings: ReturnType<typeof createEmbeddings> | null = null;
|
|
364
354
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "doccupine",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.144",
|
|
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": {
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"type": "module",
|
|
10
10
|
"engines": {
|
|
11
|
-
"node": ">=22"
|
|
11
|
+
"node": ">=22.12.0"
|
|
12
12
|
},
|
|
13
13
|
"packageManager": "pnpm@11.18.0",
|
|
14
14
|
"scripts": {
|