Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(agent): stop overflowing the model context, and cut token cost
Sidwebworks00cc32abc9bf
diff --git a/.claude/rules/agent-knowledge-base.md b/.claude/rules/agent-knowledge-base.mdindex 944f6ebc80..af178185db 100644--- a/.claude/rules/agent-knowledge-base.md+++ b/.claude/rules/agent-knowledge-base.md@@ -44,9 +44,26 @@ All three machine-readable consumers strip MDX through the one `stripComponents``apps/erp/app/modules/agent/agent.kb.ts` answers `search_docs` with `createDocSearch` from`@carbon/ee/mcp` (`packages/ee/src/mcp/doc-search.ts`) — the MCP `search_tools` engine-(zbsearch BM25 + prefix, `SEARCH_ALIASES` and `stemInflection` stems via `expandQueryTerm`, one-edit typo retry) over-title/keywords/headings/description/body. It stays in `packages/ee` on purpose: the licence-split is kept, so `@carbon/content` holds the corpus and ee holds the ranking. Pinned against-the real corpus by `agent.kb.test.ts`. `read_doc` returns a page by its public URL-(`https://docs.carbon.ms/<slug>`). The agent only ever sees URLs — slugs/file paths are never-surfaced to the user.+(zbsearch BM25 + prefix, `SEARCH_ALIASES` and `stemInflection` stems via `expandQueryTerm`,+one-edit typo retry). It indexes SECTIONS (`splitSections`, `@carbon/content/corpus`: a page+split at its `##`/`###` headings), not pages; each page's intro is weighted ×2 so its+overview leads over troubleshooting sections that merely repeat the term, and at most two+sections per page are returned. A hit is `{ title, section, url (with #anchor), snippet }`.+It stays in `packages/ee` on purpose: the licence split is kept, so `@carbon/content` holds+the corpus and ee holds the ranking.++Everything the agent reads stays bounded, because every tool result is re-sent on every+later step. `read_doc` returns one section for a `#anchor` url, a short page whole+(≤ 12k chars), and a long page as its intro plus section links. Section anchors are the+site's own (`headingAnchor`, github-slugger rules incl. `-1` suffixes), pinned by+`links.test.ts`; the size bound on every page and section read is pinned by+`agent.kb.test.ts`. `read_doc` and `search_docs` results from EARLIER turns are compacted to+titles and urls before each request (`compactEarlierToolOutputs`, `agent.history.ts`).++The model is `agentChatModel` in `packages/utils/src/llm.ts` (`gpt-4.1-mini`). It was plain+`gpt-4` — an 8k-token window — and a single long page overflowed it+(`context_length_exceeded`). `MAX_STEPS` is 6, requests share one OpenAI `promptCacheKey`,+and each turn logs its steps and input / cached / output tokens ("Agent turn").++The agent only ever sees URLs (`https://docs.carbon.ms/<slug>`, index pages at their+folder) — slugs/file paths are never surfaced to the user.diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.mdindex 53ccc20bf0..36a91380bc 100644--- a/.claude/rules/mcp-tools-reference.md+++ b/.claude/rules/mcp-tools-reference.md@@ -144,7 +144,8 @@ not substring filtering. The typed, tested logic lives OUTSIDE thefull Porter turned "customer" into "custom". The docs site uses the same stemmer.- The in-app agent's `search_docs` reuses this engine over the docs corpus —`createDocSearch` in `packages/ee/src/mcp/doc-search.ts` shares `expandQueryTerm`- (so a new alias improves both) and the typo retry.+ (so a new alias improves both) and the typo retry. It indexes page SECTIONS, weights+ each page's intro ×2 via `sortBy`, and returns at most two sections per page.- Pinned by `lib/catalog-search.test.ts` and `lib/describe-format.test.ts`;`lib/manifest.ts` carries its own copies of the meta-tool descriptions(pinned >40 chars by `manifest.test.ts`) — keep them in sync withdiff --git a/apps/erp/app/modules/agent/agent.history.test.ts b/apps/erp/app/modules/agent/agent.history.test.tsnew file mode 100644index 0000000000..2068fd813e--- /dev/null+++ b/apps/erp/app/modules/agent/agent.history.test.ts@@ -0,0 +1,77 @@+import type { UIMessage } from "ai";+import { describe, expect, it } from "vitest";+import { compactEarlierToolOutputs } from "./agent.history";++const page = "x".repeat(20_000);++const user = (text: string): UIMessage => ({+ id: text,+ role: "user",+ parts: [{ type: "text", text }]+});++const assistantThatRead = (id: string): UIMessage =>+ ({+ id,+ role: "assistant",+ parts: [+ {+ type: "tool-search_docs",+ toolCallId: `${id}-s`,+ state: "output-available",+ input: { query: "batching" },+ output: [+ {+ title: "Operation batching",+ section: "Building a batch",+ url: "https://docs.carbon.ms/docs/reference/batching#building-a-batch",+ snippet: "A batch groups operations…"+ }+ ]+ },+ {+ type: "tool-read_doc",+ toolCallId: `${id}-r`,+ state: "output-available",+ input: { url: "https://docs.carbon.ms/docs/reference/batching" },+ output: {+ url: "https://docs.carbon.ms/docs/reference/batching",+ content: page+ }+ },+ { type: "text", text: "Batching groups operations." }+ ]+ }) as UIMessage;++describe("compactEarlierToolOutputs", () => {+ it("drops the text of doc results from earlier turns but keeps their urls", () => {+ const [, earlier] = compactEarlierToolOutputs([+ user("what is batching"),+ assistantThatRead("a1"),+ user("and how do I start one")+ ]);+ const [search, read, text] = earlier!.parts as unknown as Array<{+ output?: unknown;+ text?: string;+ }>;++ expect(read!.output).toEqual({+ url: "https://docs.carbon.ms/docs/reference/batching",+ note: "Read in an earlier turn; read_doc again for the text."+ });+ expect(search!.output).toEqual([+ {+ title: "Operation batching",+ section: "Building a batch",+ url: "https://docs.carbon.ms/docs/reference/batching#building-a-batch"+ }+ ]);+ expect(text!.text).toBe("Batching groups operations.");+ expect(JSON.stringify(earlier).length).toBeLessThan(1_000);+ });++ it("leaves the current turn untouched", () => {+ const messages = [user("what is batching"), assistantThatRead("a1")];+ expect(compactEarlierToolOutputs(messages)).toEqual(messages);+ });+});diff --git a/apps/erp/app/modules/agent/agent.history.ts b/apps/erp/app/modules/agent/agent.history.tsnew file mode 100644index 0000000000..b2f9eac9c3--- /dev/null+++ b/apps/erp/app/modules/agent/agent.history.ts@@ -0,0 +1,73 @@+import { getToolName, isToolUIPart, type UIMessage } from "ai";++// Sliding window: send the model only the most recent messages whose combined size stays+// under this character budget (a rough token proxy — ~4 chars/token), dropping the oldest.+// Keeps the conversation from growing unbounded toward the context window. Whole messages+// are kept/dropped so tool-call/result pairs stay intact.+export const HISTORY_CHAR_BUDGET = 100_000; // ~25k tokens of history++function messageSize(m: UIMessage): number {+ let n = 0;+ for (const part of m.parts) {+ if (part.type === "text") n += part.text.length;+ else if (isToolUIPart(part)) {+ n +=+ JSON.stringify(part.input ?? "").length ++ JSON.stringify(part.output ?? "").length;+ }+ }+ return n;+}++// Doc tool results from earlier turns are re-sent with every later request. Keep what the+// model needs to recall them (titles and urls) and drop the text; it can read_doc again.+function compactToolOutput(toolName: string, output: unknown): unknown {+ if (toolName === "read_doc" && output && typeof output === "object") {+ const { url } = output as { url?: string };+ return url+ ? { url, note: "Read in an earlier turn; read_doc again for the text." }+ : output;+ }+ if (toolName === "search_docs" && Array.isArray(output)) {+ return output.map(({ title, section, url }) => ({ title, section, url }));+ }+ return output;+}++export function compactEarlierToolOutputs(messages: UIMessage[]): UIMessage[] {+ const lastUser = messages.findLastIndex((m) => m.role === "user");+ return messages.map((message, i) =>+ i >= lastUser+ ? message+ : {+ ...message,+ parts: message.parts.map((part) =>+ isToolUIPart(part) && part.state === "output-available"+ ? {+ ...part,+ output: compactToolOutput(getToolName(part), part.output)+ }+ : part+ )+ }+ );+}++export function windowByChars(+ messages: UIMessage[],+ budget: number+): UIMessage[] {+ const kept: UIMessage[] = [];+ let total = 0;+ for (let i = messages.length - 1; i >= 0; i--) {+ const size = messageSize(messages[i]);+ // Always keep the most recent message, even if it alone exceeds the budget.+ if (kept.length > 0 && total + size > budget) break;+ kept.unshift(messages[i]);+ total += size;+ }+ // Anthropic requires the first message to be a user message; dropping the oldest+ // turns can leave an assistant at the front, so trim any leading non-user messages.+ while (kept.length > 1 && kept[0].role !== "user") kept.shift();+ return kept;+}diff --git a/apps/erp/app/modules/agent/agent.kb.test.ts b/apps/erp/app/modules/agent/agent.kb.test.tsindex 01cd4dbad5..39f76004c6 100644--- a/apps/erp/app/modules/agent/agent.kb.test.ts+++ b/apps/erp/app/modules/agent/agent.kb.test.ts@@ -2,8 +2,20 @@ import { agentDocs } from "@carbon/content/agent-kb";import { describe, expect, it } from "vitest";import { readDoc, searchDocs } from "./agent.kb";+// The first n distinct pages the hits point into (hits link to a section,+// `…/purchase-orders#fields`, and a page may contribute two).const top = async (query: string, n = 3) =>- (await searchDocs({ query, limit: n })).map((hit) => hit.url);+ [+ ...new Set(+ (await searchDocs({ query, limit: n * 2 })).map(+ (hit) => hit.url.split("#")[0]+ )+ )+ ].slice(0, n);++// What one read_doc may put into the model's context. The chat model once had an 8k-token+// window, and one whole long page (batching, ~7k tokens) overflowed it.+const READ_BUDGET = 16_000;describe("search_docs", () => {it("expands domain abbreviations the way MCP search_tools does", async () => {@@ -25,10 +37,13 @@ describe("search_docs", () => {expect(await searchDocs({ query: " " })).toEqual([]);});- it("returns URLs read_doc can open", async () => {- const [hit] = await searchDocs({ query: "scrap", limit: 1 });- expect(hit).toBeDefined();- expect(readDoc({ url: hit!.url })).toMatchObject({ url: hit!.url });+ it("returns section URLs read_doc can open, with a short snippet", async () => {+ const hits = await searchDocs({ query: "operation batching", limit: 5 });+ expect(hits.length).toBeGreaterThan(0);+ for (const hit of hits) {+ expect(readDoc({ url: hit.url })).toMatchObject({ url: hit.url });+ expect(hit.snippet.length).toBeLessThanOrEqual(281);+ }});it("links an index page at its folder URL, the one the site serves", async () => {@@ -40,7 +55,7 @@ describe("search_docs", () => {(hits) => hits.filter((h) => h.title === doc.title));expect(hit, `"${doc.title}" finds its own page`).toBeDefined();- expect(hit!.url, doc.slug).not.toMatch(/\/index$/);+ expect(hit!.url, doc.slug).not.toMatch(/\/index(#|$)/);}});});@@ -56,12 +71,53 @@ describe("read_doc", () => {).toEqual(folder);});- it("ignores an anchor, a query and a trailing slash", () => {+ it("reads one section by its anchor", () => {+ const page = agentDocs.find((d) => d.slug === "docs/reference/batching")!;+ const section = page.sections.find((s) => s.anchor)!;+ const url = `https://docs.carbon.ms/docs/reference/batching#${section.anchor}`;+ const result = readDoc({ url });+ expect(result).toMatchObject({ url });+ expect((result as { content: string }).content).toContain(section.markdown);+ });++ it("returns a long page as its intro and section links", () => {+ const result = readDoc({+ url: "https://docs.carbon.ms/docs/reference/batching"+ });+ const content = (result as { content: string }).content;+ expect(content).toContain("This page is long");+ expect(content).toContain(+ "https://docs.carbon.ms/docs/reference/batching#"+ );+ });++ it("falls back to the page for an unknown anchor, and ignores a query or trailing slash", () => {const page = readDoc({ url: "https://docs.carbon.ms/docs/reference/jobs" });expect("content" in page).toBe(true);expect(- readDoc({ url: "https://docs.carbon.ms/docs/reference/jobs/#fields" })+ readDoc({+ url: "https://docs.carbon.ms/docs/reference/jobs/#no-such-heading"+ })).toEqual(page);expect(readDoc({ url: "/docs/reference/jobs?ref=x" })).toEqual(page);});++ it("keeps every page and section read within budget", () => {+ const over = agentDocs.flatMap((doc) => {+ const pageUrl = `https://docs.carbon.ms/${doc.slug.replace(/(^|\/)index$/, "")}`;+ const urls = [+ pageUrl,+ ...doc.sections+ .filter((s) => s.anchor)+ .map((s) => `${pageUrl}#${s.anchor}`)+ ];+ return urls.flatMap((url) => {+ const { content = "" } = readDoc({ url }) as { content?: string };+ return content.length > READ_BUDGET+ ? [`${url}: ${content.length}`]+ : [];+ });+ });+ expect(over).toEqual([]);+ });});diff --git a/apps/erp/app/modules/agent/agent.kb.ts b/apps/erp/app/modules/agent/agent.kb.tsindex 1cd45670ed..c7ed390faa 100644--- a/apps/erp/app/modules/agent/agent.kb.ts+++ b/apps/erp/app/modules/agent/agent.kb.ts@@ -1,4 +1,4 @@-import { agentDocs } from "@carbon/content/agent-kb";+import { type AgentDoc, agentDocs } from "@carbon/content/agent-kb";import { DOCS_URL, docUrl } from "@carbon/content/links";import { createDocSearch } from "@carbon/ee/mcp";@@ -9,7 +9,26 @@ const pagePath = (slug: string) => slug.replace(/(^|\/)index$/, "");const byPath = new Map(agentDocs.map((d) => [pagePath(d.slug), d]));const docSearch = createDocSearch(agentDocs);-/** Ranked search over every doc (the MCP catalog's engine and aliases); best matches first. */+// Every tool result lands in the model's context and is re-sent on each later step, so+// both tools return bounded text: search_docs a snippet per section, read_doc one section,+// a short page whole, or a long page's intro plus its section links.+const SNIPPET_CHARS = 280;+const FULL_PAGE_CHARS = 12_000;++const sectionUrl = (doc: AgentDoc, anchor: string | null) =>+ `${docUrl(pagePath(doc.slug))}${anchor ? `#${anchor}` : ""}`;++function snippet(markdown: string): string {+ const text = markdown+ .replace(/^#{2,3}\s+[^\n]*\n?/, "")+ .replace(/\s+/g, " ")+ .trim();+ return text.length > SNIPPET_CHARS+ ? `${text.slice(0, SNIPPET_CHARS)}…`+ : text;+}++/** Ranked search over every doc section (the MCP catalog's engine and aliases). */export async function searchDocs({query,limit = 5@@ -18,26 +37,54 @@ export async function searchDocs({limit?: number;}) {const hits = await docSearch(query, limit);- return hits.map((d) => ({- title: d.title,- description: d.description,- url: docUrl(pagePath(d.slug))+ return hits.map(({ doc, section }) => ({+ title: doc.title,+ ...(section.heading ? { section: section.heading } : {}),+ url: sectionUrl(doc, section.anchor),+ snippet: snippet(section.markdown)}));}-/** Read the full markdown for a doc by its public URL (as returned by search_docs). */+/**+ * Read a doc by its public URL (as returned by search_docs). A `#section` URL returns that+ * section; a page URL returns the page, or for a long page its intro and section links.+ */export function readDoc({ url }: { url: string }) {+ const [location = "", anchor] = url+ .replace(`${DOCS_URL}/`, "")+ .replace(/^https?:\/\/[^/]+\//, "")+ .split("#");const path = pagePath(- url- .replace(`${DOCS_URL}/`, "")- .replace(/^https?:\/\/[^/]+\//, "")- .replace(/[?#].*$/, "")- .replace(/^\/+|\/+$/g, "")+ location.replace(/\?.*$/, "").replace(/^\/+|\/+$/g, ""));const doc = byPath.get(path);if (!doc) return { error: `Doc not found: ${url}` };- const content = `# ${doc.title}\n\n${++ const header = `# ${doc.title}\n\n${doc.description ? `> ${doc.description}\n\n` : ""- }${doc.markdown}\n`;- return { url: docUrl(path), content };+ }`;++ const section = anchor+ ? doc.sections.find((s) => s.anchor === anchor)+ : undefined;+ if (section) {+ return {+ url: sectionUrl(doc, section.anchor),+ content: `${header}${section.markdown}\n`+ };+ }++ if (doc.markdown.length <= FULL_PAGE_CHARS) {+ return { url: docUrl(path), content: `${header}${doc.markdown}\n` };+ }++ const intro = doc.sections.find((s) => s.heading === null)?.markdown;+ const contents = doc.sections+ .filter((s) => s.anchor)+ .map((s) => `- ${s.heading}: ${sectionUrl(doc, s.anchor)}`)+ .join("\n");+ return {+ url: docUrl(path),+ content: `${header}${intro ? `${intro}\n\n` : ""}This page is long. Read the section you need with read_doc and its URL:\n\n${contents}\n`+ };}diff --git a/apps/erp/app/modules/agent/agent.prompt.ts b/apps/erp/app/modules/agent/agent.prompt.tsindex ea7723d112..c5259abc72 100644--- a/apps/erp/app/modules/agent/agent.prompt.ts+++ b/apps/erp/app/modules/agent/agent.prompt.ts@@ -106,8 +106,9 @@ number. Briefly say you can't read their live data yet, then send them to the pasee it (find_page + navigate) and, if helpful, explain how to read it.How to answer:-- For "how do I / what is / where" questions, use search_docs to find relevant docs, then- read_doc (pass the \`url\`) to read them. When you cite a source, ALWAYS show the full \`url\`+- For "how do I / what is / where" questions, use search_docs to find the relevant sections.+ If the snippets answer the question, answer; otherwise read_doc the section \`url\` (read+ sections, not whole pages). When you cite a source, ALWAYS show the full \`url\`(e.g. https://docs.carbon.ms/...) as a clickable link. NEVER show a file path, slug, or foldername — those are internal and must never be shown to the user.- To point the user at where their data lives, use find_page then navigate (see UI blocks below).@@ -129,8 +130,9 @@ How to answer:.join("\n");const body = `How to answer:-- For "how do I / what is / where" questions, use search_docs to find relevant docs,- then read_doc (pass the \`url\`) to read them. When you cite a source, ALWAYS show the+- For "how do I / what is / where" questions, use search_docs to find the relevant+ sections. If the snippets answer the question, answer; otherwise read_doc the section+ \`url\` (read sections, not whole pages). When you cite a source, ALWAYS show thefull \`url\` (e.g. https://docs.carbon.ms/...) as a clickable link. NEVER show a filepath, slug, or folder name — those are internal and must never be shown to the user.- For questions about live data (this record, open orders, quantities, statuses),diff --git a/apps/erp/app/modules/agent/agent.service.ts b/apps/erp/app/modules/agent/agent.service.tsindex 922ec12ec3..b163f6eecf 100644--- a/apps/erp/app/modules/agent/agent.service.ts+++ b/apps/erp/app/modules/agent/agent.service.ts@@ -1,7 +1,7 @@import type { Database } from "@carbon/database";import { Ratelimit, redis } from "@carbon/kv";import { getLogger } from "@carbon/logger";-import { agentChatModel, agentTitleModel } from "@carbon/utils";+import { agentChatModel, agentProvider, agentTitleModel } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import {convertToModelMessages,@@ -14,6 +14,11 @@ import {type UIMessage} from "ai";import { isEphemeralTool, isUiBlockTool } from "./agent.blocks";+import {+ compactEarlierToolOutputs,+ HISTORY_CHAR_BUDGET,+ windowByChars+} from "./agent.history";import { buildSystemPrompt } from "./agent.prompt";import { agentModel } from "./agent.provider";import { createAgentTools } from "./agent.tools";@@ -21,42 +26,9 @@ import type { BrowsingContext } from "./types";const log = getLogger("erp", "agent");-const MAX_STEPS = 20;--// Sliding window: send the model only the most recent messages whose combined size stays-// under this character budget (a rough token proxy — ~4 chars/token), dropping the oldest.-// Keeps the conversation from growing unbounded toward the context window. Whole messages-// are kept/dropped so tool-call/result pairs stay intact.-const HISTORY_CHAR_BUDGET = 100_000; // ~25k tokens of history--function messageSize(m: UIMessage): number {- let n = 0;- for (const part of m.parts) {- if (part.type === "text") n += part.text.length;- else if (isToolUIPart(part)) {- n +=- JSON.stringify(part.input ?? "").length +- JSON.stringify(part.output ?? "").length;- }- }- return n;-}--function windowByChars(messages: UIMessage[], budget: number): UIMessage[] {- const kept: UIMessage[] = [];- let total = 0;- for (let i = messages.length - 1; i >= 0; i--) {- const size = messageSize(messages[i]);- // Always keep the most recent message, even if it alone exceeds the budget.- if (kept.length > 0 && total + size > budget) break;- kept.unshift(messages[i]);- total += size;- }- // Anthropic requires the first message to be a user message; dropping the oldest- // turns can leave an assistant at the front, so trim any leading non-user messages.- while (kept.length > 1 && kept[0].role !== "user") kept.shift();- return kept;-}+// Every step re-sends the whole context. A docs answer is search → read → answer, with a+// read or two more at most, so a few steps cover it and bound the worst-case cost.+const MAX_STEPS = 6;const agentRatelimit = new Ratelimit({redis,@@ -246,7 +218,12 @@ export function streamChat(};const modelMessages = injectContext(- convertToModelMessages(windowByChars(args.messages, HISTORY_CHAR_BUDGET)),+ convertToModelMessages(+ windowByChars(+ compactEarlierToolOutputs(args.messages),+ HISTORY_CHAR_BUDGET+ )+ ),args.context);@@ -267,10 +244,27 @@ export function streamChat(// it has — instead of ending on a dangling tool call and returning no text.prepareStep: ({ stepNumber }) =>stepNumber >= MAX_STEPS - 1 ? { toolChoice: "none" } : undefined,+ // One key for every turn: the system prompt and tool definitions are the same+ // prefix each time, and OpenAI bills a cached prefix at a fraction of the price.+ ...(agentProvider === "openai"+ ? { providerOptions: { openai: { promptCacheKey: "carbon-agent" } } }+ : {}),+ onError: ({ error }) => {+ log.error("Agent model call failed", { error, threadId: args.threadId });+ },onFinish: (event) => {inputTokens = event.totalUsage.inputTokens ?? 0;outputTokens = event.totalUsage.outputTokens ?? 0;finishReason = event.finishReason;+ log.info("Agent turn", {+ threadId: args.threadId,+ model: agentChatModel,+ steps: event.steps.length,+ inputTokens,+ cachedInputTokens: event.totalUsage.cachedInputTokens ?? 0,+ outputTokens,+ finishReason+ });}});diff --git a/apps/erp/app/modules/agent/agent.tools.ts b/apps/erp/app/modules/agent/agent.tools.tsindex 67412cfd6b..92f1f1dee1 100644--- a/apps/erp/app/modules/agent/agent.tools.ts+++ b/apps/erp/app/modules/agent/agent.tools.ts@@ -30,7 +30,7 @@ export function createAgentTools(ctx: AuthedContext) {return {search_docs: tool({description:- "Search Carbon product documentation for how-to and conceptual answers. Returns matching doc slugs.",+ "Search Carbon product documentation for how-to and conceptual answers. Returns matching sections: page title, section heading, a short snippet and a `url` (with #section). Answer from the snippets when they are enough; otherwise read_doc the url.",inputSchema: z.object({query: z.string(),limit: z.number().int().min(1).max(10).optional()@@ -40,7 +40,7 @@ export function createAgentTools(ctx: AuthedContext) {read_doc: tool({description:- "Read the full markdown of a documentation page by its URL (the `url` returned by search_docs).",+ "Read documentation by the `url` search_docs returned. A url with #section returns just that section; a page url returns the page, or for a long page its intro and the section urls to read next.",inputSchema: z.object({ url: z.string() }),execute: async ({ url }) => readDoc({ url })}),diff --git a/docs/content/AGENTS.md b/docs/content/AGENTS.mdindex 9f88ed1fdf..8ed911c477 100644--- a/docs/content/AGENTS.md+++ b/docs/content/AGENTS.md@@ -9,7 +9,8 @@ colocated with the site; the `docs/` Next app renders it, ERP/MES/packages impor- `docs/**`, `guides/**` — the docs pages (Fumadocs reads them via `docs/source.config.ts`).- `src/glossary/` — term definitions for ERP/MES field help and docs `<Term>` popovers.- `src/corpus.ts` — MDX → plain markdown (pure; callers bring the raw text).-- `src/agent-kb.ts` — every page, stripped, for the in-app agent (Vite `import.meta.glob`).+- `src/agent-kb.ts` — every page, stripped and split into sections, for the in-app agent+ (Vite `import.meta.glob`).- `src/links.ts` — `DOCS_URL` and `docUrl()`.- `src/search.ts` — `stemInflection()`, the one stemmer for docs site search, MCP `search_tools`and the agent's `search_docs` (zbsearch's Porter, limited to plural/-ed/-ing/-e).@@ -20,7 +21,7 @@ colocated with the site; the `docs/` Next app renders it, ERP/MES/packages imporimport { terms, getEntry, lookupEntry, type TermId } from "@carbon/content/glossary";import { docUrl, DOCS_URL } from "@carbon/content/links";import { stemInflection } from "@carbon/content/search";-import { parsePage, stripComponents } from "@carbon/content/corpus"; // pure, any bundle+import { parsePage, splitSections, headingAnchor } from "@carbon/content/corpus"; // pure, any bundleimport { agentDocs } from "@carbon/content/agent-kb"; // Vite builds only (ERP)```diff --git a/docs/content/src/agent-kb.ts b/docs/content/src/agent-kb.tsindex 130ed2ed51..fe2b88b1fd 100644--- a/docs/content/src/agent-kb.ts+++ b/docs/content/src/agent-kb.ts@@ -1,5 +1,11 @@/// <reference types="vite/client" />-import { type CorpusPage, keywords, parsePage } from "./corpus";+import {+ type CorpusPage,+ type CorpusSection,+ keywords,+ parsePage,+ splitSections+} from "./corpus";// Vite-only: bundles every page's raw MDX into the importing build (the ERP server),// so the agent needs no fs or docs app at runtime.@@ -9,7 +15,11 @@ const sources = import.meta.glob(["../docs/**/*.mdx", "../guides/**/*.mdx"], {eager: true}) as Record<string, string>;-export type AgentDoc = CorpusPage & { keywords: string[] };+export type AgentDoc = CorpusPage & {+ keywords: string[];+ /** The page split at its headings, so the agent can read one section at a time. */+ sections: CorpusSection[];+};/** Every docs page as stripped markdown, sorted by slug (`docs/reference/jobs`). */export const agentDocs: AgentDoc[] = Object.entries(sources)@@ -18,6 +28,10 @@ export const agentDocs: AgentDoc[] = Object.entries(sources)file.replace(/^\.\.\//, "").replace(/\.mdx$/, ""),raw);- return { ...page, keywords: keywords(page.title, page.slug) };+ return {+ ...page,+ keywords: keywords(page.title, page.slug),+ sections: splitSections(page.markdown)+ };}).sort((a, b) => a.slug.localeCompare(b.slug));diff --git a/docs/content/src/corpus.ts b/docs/content/src/corpus.tsindex 7361478b24..752522ea7a 100644--- a/docs/content/src/corpus.ts+++ b/docs/content/src/corpus.ts@@ -161,6 +161,66 @@ export function keywords(title: string, slug: string): string[] {return Array.from(new Set(words));}+/**+ * A heading's URL anchor as github-slugger (and so Fumadocs) makes it:+ * "Database — Supabase" -> "database--supabase".+ */+export function headingAnchor(heading: string): string {+ return heading+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")+ .replace(/<[^>]+>/g, "")+ .trim()+ .toLowerCase()+ .replace(/[^\p{L}\p{N}\p{M} _-]/gu, "")+ .replace(/ /g, "-");+}++export type CorpusSection = {+ /** `null` for the text before the first heading. */+ heading: string | null;+ anchor: string | null;+ markdown: string;+};++/**+ * Split stripped markdown at its `##` / `###` headings, ignoring code blocks. A repeated+ * heading gets github-slugger's `-1`, `-2` suffix, so every anchor links on the site.+ */+export function splitSections(markdown: string): CorpusSection[] {+ const sections: CorpusSection[] = [];+ const seen = new Map<string, number>();+ let heading: string | null = null;+ let anchor: string | null = null;+ let lines: string[] = [];+ const flush = () => {+ const text = lines.join("\n").trim();+ if (text) sections.push({ heading, anchor, markdown: text });+ lines = [];+ };+ for (const seg of splitByCodeFence(markdown)) {+ if (seg.code) {+ lines.push(seg.text);+ continue;+ }+ for (const line of seg.text.split("\n")) {+ const match = /^#{2,3}\s+(.+)$/.exec(line);+ if (!match?.[1]) {+ lines.push(line);+ continue;+ }+ flush();+ heading = match[1].trim();+ const base = headingAnchor(heading);+ const count = seen.get(base) ?? 0;+ seen.set(base, count + 1);+ anchor = count ? `${base}-${count}` : base;+ lines.push(line);+ }+ }+ flush();+ return sections;+}+export type CorpusPage = {/** Content-relative slug, e.g. `docs/reference/quotes` or `guides/order`. */slug: string;diff --git a/docs/content/src/links.test.ts b/docs/content/src/links.test.tsindex 4adf7a1033..b489f95b48 100644--- a/docs/content/src/links.test.ts+++ b/docs/content/src/links.test.ts@@ -2,7 +2,8 @@ import fs from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";-import { splitByCodeFence, splitFrontmatter } from "./corpus";+import { agentDocs } from "./agent-kb";+import { headingAnchor, splitByCodeFence, splitFrontmatter } from "./corpus";import { terms } from "./glossary";import { DOCS_URL } from "./links";@@ -17,27 +18,24 @@ const mdxFiles = Object.entries(sources).map(([file, raw]) => ({}));const REPO_ROOT = fileURLToPath(new URL("../../..", import.meta.url));-// Mirrors github-slugger, which fumadocs uses for heading ids.-const slugify = (heading: string) =>- heading- .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")- .replace(/<[^>]+>/g, "")- .trim()- .toLowerCase()- .replace(/[^\p{L}\p{N}\p{M} _-]/gu, "")- .replace(/ /g, "-");-/** Route (`/docs/reference/jobs`) → heading anchors on that page. */const pages = new Map<string, Set<string>>();for (const { file, raw } of mdxFiles) {const route = `/${file}`.replace(/\.mdx$/, "").replace(/\/index$/, "");const { body } = splitFrontmatter(raw);+ // github-slugger suffixes a repeated heading's anchor: "fields", "fields-1", …+ const seen = new Map<string, number>();const anchors = new Set(splitByCodeFence(body).filter((seg) => !seg.code).flatMap((seg) => seg.text.split("\n")).filter((l) => /^#{1,6}\s/.test(l))- .map((l) => slugify(l.replace(/^#{1,6}\s+/, "")))+ .map((l) => {+ const base = headingAnchor(l.replace(/^#{1,6}\s+/, ""));+ const count = seen.get(base) ?? 0;+ seen.set(base, count + 1);+ return count ? `${base}-${count}` : base;+ }));pages.set(route, anchors);}@@ -106,6 +104,19 @@ describe("doc links resolve to a real page and heading", () => {expect(broken).toEqual([]);});+ it("every section the agent links to is a real heading", () => {+ const broken = agentDocs.flatMap((doc) =>+ doc.sections.flatMap(({ anchor }) => {+ if (!anchor) return [];+ const link = `/${doc.slug.replace(/(^|\/)index$/, "")}#${anchor}`;+ const reason = brokenReason(link);+ return reason ? [`${link} (${reason})`] : [];+ })+ );+ expect(agentDocs.some((doc) => doc.sections.length > 3)).toBe(true);+ expect(broken).toEqual([]);+ });+it("internal links inside the MDX", () => {const pattern = /\]\((\/(?:docs|guides)[^)\s]*)\)/g;const broken = mdxFiles.flatMap(({ file, raw }) =>diff --git a/packages/ee/src/mcp/doc-search.ts b/packages/ee/src/mcp/doc-search.tsindex 36f2b14a44..0e929fbecf 100644--- a/packages/ee/src/mcp/doc-search.ts+++ b/packages/ee/src/mcp/doc-search.ts@@ -1,61 +1,94 @@// Ranked search over the docs corpus for the in-app agent's `search_docs`. Same// engine as the tool catalog (catalog-search.ts): zbsearch BM25 with prefix// expansion, SEARCH_ALIASES and word stems via expandQueryTerm, and a-// typo-tolerant second pass — indexed over doc fields instead of tool fields.+// typo-tolerant second pass. It indexes SECTIONS, not pages, so a hit points the+// agent at the few hundred words it needs instead of a whole page.import { create, insertMultiple, search } from "zbsearch";import { expandQueryTerm } from "./catalog-search";+export type SearchableSection = {+ /** `null` for the text before a page's first heading. */+ heading: string | null;+ anchor: string | null;+ markdown: string;+};+export type SearchableDoc = {slug: string;title: string;description: string;keywords: string[];- headings: string[];- markdown: string;+ sections: SearchableSection[];+};++export type DocSearchHit<T extends SearchableDoc> = {+ doc: T;+ section: SearchableSection;};const DOC_SCHEMA = {- slug: "string",+ id: "string",title: "string",+ heading: "string",keywords: "string",- headings: "string",description: "string",body: "string"} as const;+// The page's own fields ride on every section of it; the heading and body are the+// section's, so they decide which section of a matching page wins.const DOC_BOOSTS = {title: 4,- keywords: 3,- headings: 2,+ heading: 2,+ keywords: 2,description: 1.5,body: 1};+// A long page has many matching sections; keep the results spread across pages.+const MAX_SECTIONS_PER_PAGE = 2;++// zbsearch ignores term frequency, so a short troubleshooting section whose heading+// repeats the query ties with the page's own overview. Weighting the intro (the text+// before the first heading) lets the page about the term lead, as on the docs site.+const INTRO_WEIGHT = 2;+const weighted = ([, score, doc]: [unknown, number, unknown]) =>+ (doc as { heading?: string }).heading === "" ? score * INTRO_WEIGHT : score;+async function buildDocIndex(docs: SearchableDoc[]) {const db = create({ schema: DOC_SCHEMA });await insertMultiple(db,- docs.map((doc) => ({- slug: doc.slug,- title: doc.title,- keywords: doc.keywords.join(" "),- headings: doc.headings.join(" "),- description: doc.description,- body: doc.markdown- }))+ docs.flatMap((doc) =>+ doc.sections.map((section, i) => ({+ id: `${doc.slug}#${i}`,+ title: doc.title,+ heading: section.heading ?? "",+ keywords: doc.keywords.join(" "),+ description: doc.description,+ body: section.markdown+ }))+ ));return db;}-/** Returns a `(query, limit)` search over `docs`, best match first. */+/** Returns a `(query, limit)` search over the docs' sections, best match first. */export function createDocSearch<T extends SearchableDoc>(docs: T[]) {- const bySlug = new Map(docs.map((doc) => [doc.slug, doc]));+ const byId = new Map(+ docs.flatMap((doc) =>+ doc.sections.map((section, i) => [`${doc.slug}#${i}`, { doc, section }])+ )+ );// Built lazily on the first query so importing this module stays free.let indexPromise: ReturnType<typeof buildDocIndex> | null = null;const getIndex = () => (indexPromise ??= buildDocIndex(docs));- return async function searchDocs(query: string, limit: number): Promise<T[]> {+ return async function searchDocs(+ query: string,+ limit: number+ ): Promise<DocSearchHit<T>[]> {const term = expandQueryTerm(query);if (!term) return [];@@ -63,7 +96,9 @@ export function createDocSearch<T extends SearchableDoc>(docs: T[]) {term,properties: Object.keys(DOC_BOOSTS) as (keyof typeof DOC_BOOSTS)[],boost: DOC_BOOSTS,- limit+ sortBy: (a: [unknown, number, unknown], b: [unknown, number, unknown]) =>+ weighted(b) - weighted(a),+ limit: limit * 12};const db = await getIndex();let results = await search(db, params);@@ -71,8 +106,17 @@ export function createDocSearch<T extends SearchableDoc>(docs: T[]) {results = await search(db, { ...params, tolerance: 1 });}- return results.hits- .map((hit) => bySlug.get((hit.document as { slug: string }).slug))- .filter((doc): doc is T => doc !== undefined);+ const perPage = new Map<string, number>();+ const hits: DocSearchHit<T>[] = [];+ for (const result of results.hits) {+ const hit = byId.get((result.document as { id: string }).id);+ if (!hit) continue;+ const count = perPage.get(hit.doc.slug) ?? 0;+ if (count >= MAX_SECTIONS_PER_PAGE) continue;+ perPage.set(hit.doc.slug, count + 1);+ hits.push(hit);+ if (hits.length === limit) break;+ }+ return hits;};}diff --git a/packages/utils/src/llm.ts b/packages/utils/src/llm.tsindex ce42e38e40..bf185c5614 100644--- a/packages/utils/src/llm.ts+++ b/packages/utils/src/llm.ts@@ -12,5 +12,7 @@ export type AgentProvider = "openai" | "anthropic";export const agentProvider: AgentProvider = "openai";-export const agentChatModel = "gpt-4" as const; // main chat turns+// gpt-4.1-mini: 1M-token window, no reasoning tokens, a small fraction of GPT-4's price.+// Plain "gpt-4" (the 2023 model) has an 8k window: one long docs page overflowed it.+export const agentChatModel = "gpt-4.1-mini" as const; // main chat turnsexport const agentTitleModel = "gpt-4o-mini" as const; // cheap: chat titles