Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent-documents): cap readDocument content to avoid blowing the context window (#16699)

Arvin Xuf80ea6043e66
diff --git a/packages/builtin-tool-agent-documents/package.json b/packages/builtin-tool-agent-documents/package.json
index fee9206f0b0..c1524d76910 100644
--- a/packages/builtin-tool-agent-documents/package.json
+++ b/packages/builtin-tool-agent-documents/package.json
@@ -9,6 +9,11 @@
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
+ "scripts": {
+ "test": "vitest",
+ "test:coverage": "vitest --coverage --silent='passed-only'",
+ "test:update": "vitest -u"
+ },
"dependencies": {
"@lobechat/prompts": "workspace:*"
},
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
index 347c2e841a4..e116e3f08d4 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
@@ -157,4 +157,62 @@ describe('AgentDocumentsExecutionRuntime', () => {
title: 'Draft',
});
});
+
+ it('truncates an oversized readDocument content but keeps full content in state', async () => {
+ const hugeXml = 'x'.repeat(500_000);
+ const hugeMarkdown = 'm'.repeat(500_000);
+ const readDocument = vi.fn().mockResolvedValue({
+ content: hugeMarkdown,
+ id: 'agent-doc-1',
+ litexml: hugeXml,
+ title: 'Newsletter Archive',
+ });
+ const runtime = createRuntime({ readDocument });
+
+ const result = await runtime.readDocument({ id: 'agent-doc-1' }, { agentId: 'agent-1' });
+
+ // LLM-facing content is capped well below the raw 500k chars.
+ expect(result.content.length).toBeLessThan(hugeXml.length);
+ expect(result.content).toContain('document truncated to fit the context window');
+ // Inspector still receives the untruncated document via state.
+ expect(result.state).toMatchObject({ content: hugeMarkdown, xml: hugeXml });
+ });
+
+ it('does not truncate a readDocument content under the cap', async () => {
+ const readDocument = vi.fn().mockResolvedValue({
+ content: 'short markdown',
+ id: 'agent-doc-1',
+ litexml: '<doc>short</doc>',
+ title: 'Small Doc',
+ });
+ const runtime = createRuntime({ readDocument });
+
+ const result = await runtime.readDocument({ id: 'agent-doc-1' }, { agentId: 'agent-1' });
+
+ expect(result.content).toBe('<doc>short</doc>');
+ expect(result.content).not.toContain('document truncated');
+ });
+
+ it('does not split a surrogate pair when the cutoff lands mid-emoji', async () => {
+ // Place a 2-code-unit emoji so its high surrogate sits exactly at the
+ // 200,000-char cutoff; a naive slice would emit a lone `\uD83D`, which some
+ // providers reject and would re-break the large-document request.
+ const content = `${'a'.repeat(199_999)}πŸ˜€${'b'.repeat(2000)}`;
+ const readDocument = vi.fn().mockResolvedValue({
+ content: 'markdown',
+ id: 'agent-doc-1',
+ litexml: content,
+ title: 'Emoji Archive',
+ });
+ const runtime = createRuntime({ readDocument });
+
+ const result = await runtime.readDocument({ id: 'agent-doc-1' }, { agentId: 'agent-1' });
+
+ // No lone high/low surrogate survives in the LLM-facing content.
+ const loneSurrogate = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
+ expect(result.content).not.toMatch(loneSurrogate);
+ // JSON serialization (the actual failure surface) stays well-formed.
+ expect(() => JSON.parse(JSON.stringify(result.content))).not.toThrow();
+ expect(result.content).toContain('document truncated to fit the context window');
+ });
});
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
index f26b4a41528..bc3570b521d 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
@@ -79,6 +79,18 @@ interface AgentDocumentToolTriggerInput {
const CURRENT_PAGE_DOCUMENT_WRITE_ERROR_CODE = 'CURRENT_PAGE_DOCUMENT_WRITE_FORBIDDEN';
const CURRENT_PAGE_DOCUMENT_WRITE_ERROR_TYPE = 'CurrentPageDocumentWriteForbidden';
+/**
+ * Upper bound on the characters a single readDocument result feeds back into the
+ * model context. Agent documents can hold whole email/newsletter archives that
+ * run into the millions of characters; returning one whole once pushed a task
+ * past the model's context window β€” a lone tool result reached ~591k tokens and
+ * the next completion 400'd with ExceededContextWindow. The client Inspector
+ * still renders the full document from `state`, so only the LLM-facing `content`
+ * is capped. ~200k chars is roughly 50k tokens per field β€” generous for a real
+ * document read while leaving ample room in the window.
+ */
+const MAX_READ_DOCUMENT_CONTENT_CHARS = 200_000;
+
type MaybePromise<T> = T | Promise<T>;
export interface AgentDocumentsRuntimeService {
@@ -252,12 +264,41 @@ export class AgentDocumentsExecutionRuntime {
return doc.documentId === currentDocumentId;
}
+ /**
+ * Cap a single field so one oversized document can't blow the model's context
+ * window. Truncation is byte-cheap `slice` on characters (not tokens), so the
+ * cap is deliberately conservative; the trailing marker tells the model the
+ * document was cut and to work with a smaller/targeted read instead of
+ * assuming it saw the whole thing.
+ */
+ private capReadContent(content: string) {
+ if (content.length <= MAX_READ_DOCUMENT_CONTENT_CHARS) return content;
+
+ // Avoid splitting a UTF-16 surrogate pair: if the cutoff lands right after a
+ // high surrogate (e.g. half of an emoji), step back one code unit. Otherwise
+ // JSON.stringify emits a lone `\uD83D`-style escape, which some upstream
+ // providers (DeepSeek, Anthropic) reject β€” which would re-break the exact
+ // large-document requests this cap is meant to protect.
+ let cutoff = MAX_READ_DOCUMENT_CONTENT_CHARS;
+ const lastCharCode = content.charCodeAt(cutoff - 1);
+ if (lastCharCode >= 0xd8_00 && lastCharCode <= 0xdb_ff) cutoff -= 1;
+
+ const omitted = content.length - cutoff;
+ return (
+ content.slice(0, cutoff) +
+ `\n\n[... document truncated to fit the context window: ${omitted} of ${content.length} ` +
+ `characters omitted. This is only the beginning of the document β€” do not assume it is ` +
+ `complete. Read a smaller/specific document, or list and target sections instead of ` +
+ `loading the whole file.]`
+ );
+ }
+
private formatDocumentReadContent(
doc: AgentDocumentRecord,
format: 'xml' | 'markdown' | 'both' = 'xml',
) {
- const markdown = doc.content || '';
- const xml = doc.litexml || '';
+ const markdown = this.capReadContent(doc.content || '');
+ const xml = this.capReadContent(doc.litexml || '');
if (format === 'markdown') return markdown;
if (format === 'both') return JSON.stringify({ markdown, xml });
diff --git a/packages/builtin-tool-agent-documents/vitest.config.mts b/packages/builtin-tool-agent-documents/vitest.config.mts
new file mode 100644
index 00000000000..52f86e133c7
--- /dev/null
+++ b/packages/builtin-tool-agent-documents/vitest.config.mts
@@ -0,0 +1,11 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ provider: 'v8',
+ reporter: ['text', 'json', 'lcov', 'text-summary'],
+ },
+ environment: 'node',
+ },
+});