π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent-runtime): dedupe archived tool results by content and page readKnowledge (#19665)
Rdmclin291f36af7de7d
diff --git a/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts b/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.tsindex db13d5e225c..da1df64f400 100644--- a/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/archiveToolResult.test.ts@@ -1,4 +1,6 @@// @vitest-environment node+import { createHash } from 'node:crypto';+import type { LobeChatDatabase } from '@lobechat/database';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -15,11 +17,19 @@ vi.mock('@/database/models/topicDocument', () => ({TopicDocumentModel: vi.fn(),}));+const CONTENT = '0123456789';+const CONTENT_HASH = createHash('sha256').update(CONTENT).digest('hex').slice(0, 32);+const ARCHIVE_PATH = `./.tool-results/${CONTENT_HASH}.txt`;+describe('archiveToolResultIfNeeded', () => {- const db = {} as LobeChatDatabase;+ const tx = { execute: vi.fn() };+ const db = {+ transaction: vi.fn(async (callback: (trx: unknown) => Promise<unknown>) => callback(tx)),+ } as unknown as LobeChatDatabase;const mockVfsService = {mkdir: vi.fn(),read: vi.fn(),+ stat: vi.fn(),write: vi.fn(),};const mockTopicDocumentModel = {@@ -35,8 +45,10 @@ describe('archiveToolResultIfNeeded', () => {vi.mocked(TopicDocumentModel).mockImplementation(function () {return mockTopicDocumentModel as any;});+ tx.execute.mockResolvedValue(undefined);mockVfsService.mkdir.mockResolvedValue({});- mockVfsService.read.mockResolvedValue({ content: '0123456789' });+ mockVfsService.stat.mockResolvedValue(undefined);+ mockVfsService.read.mockResolvedValue({ content: CONTENT });mockVfsService.write.mockResolvedValue({ documentId: 'document-1', id: 'agent-doc-1' });mockTopicDocumentModel.isAssociated.mockResolvedValue(false);mockTopicDocumentModel.associate.mockResolvedValue({@@ -45,44 +57,45 @@ describe('archiveToolResultIfNeeded', () => {});});- it('returns unchanged content when it is under the limit', async () => {- const result = await archiveToolResultIfNeeded({+ const archive = (overrides: Partial<Parameters<typeof archiveToolResultIfNeeded>[0]> = {}) =>+ archiveToolResultIfNeeded({agentId: 'agent-1',- content: 'short result',- limit: 100,+ content: CONTENT,+ limit: 5,serverDB: db,toolCallId: 'call_1',topicId: 'topic-1',userId: 'user-1',+ ...overrides,});+ it('returns unchanged content when it is under the limit', async () => {+ const result = await archive({ content: 'short result', limit: 100 });+expect(result).toEqual({ archived: false, content: 'short result' });expect(AgentDocumentVfsService).not.toHaveBeenCalled();+ expect(db.transaction).not.toHaveBeenCalled();});- it('archives oversized content and returns a truncated pointer', async () => {- const result = await archiveToolResultIfNeeded({- agentId: 'agent-1',- content: '0123456789',- limit: 5,- serverDB: db,- toolCallId: 'call_1',- topicId: 'topic-1',- userId: 'user-1',- });+ it('archives oversized content under a content-hash path and returns a truncated pointer', async () => {+ const result = await archive();expect(mockVfsService.mkdir).toHaveBeenCalledWith('./.tool-results',{ agentId: 'agent-1', topicId: 'topic-1' },{ recursive: true },);+ expect(mockVfsService.stat).toHaveBeenCalledWith(ARCHIVE_PATH, {+ agentId: 'agent-1',+ topicId: 'topic-1',+ });expect(mockVfsService.write).toHaveBeenCalledWith(- './.tool-results/topic-1_call_1.txt',- '0123456789',+ ARCHIVE_PATH,+ CONTENT,{ agentId: 'agent-1', topicId: 'topic-1' },{ contentFormat: 'raw' },);- expect(mockVfsService.read).toHaveBeenCalledWith('./.tool-results/topic-1_call_1.txt', {+ expect(mockVfsService.read).toHaveBeenCalledWith(ARCHIVE_PATH, {agentId: 'agent-1',topicId: 'topic-1',});@@ -91,26 +104,81 @@ describe('archiveToolResultIfNeeded', () => {topicId: 'topic-1',});expect(result.archived).toBe(true);- expect(result.archivePath).toBe('./.tool-results/topic-1_call_1.txt');+ expect(result.archivePath).toBe(ARCHIVE_PATH);expect(result.content).toContain('01234');- expect(result.content).toContain('./.tool-results/topic-1_call_1.txt');+ expect(result.content).toContain(ARCHIVE_PATH);expect(result.content).toContain('lobe-agent-documents');expect(result.content).toContain('readDocument');expect(result.content).toContain('agent-doc-1');});- it('does not duplicate topic association when the archive document is already associated', async () => {- mockTopicDocumentModel.isAssociated.mockResolvedValue(true);+ it('serializes archive writes per agent with a transaction-scoped advisory lock', async () => {+ await archive();++ expect(db.transaction).toHaveBeenCalledTimes(1);+ expect(tx.execute).toHaveBeenCalledTimes(1);+ const [query] = tx.execute.mock.calls[0];+ expect(JSON.stringify(query)).toContain('pg_advisory_xact_lock');+ expect(JSON.stringify(query)).toContain('toolResultArchive:agent-1');+ // Every VFS / topic-document write must run on the locked transaction handle.+ expect(vi.mocked(AgentDocumentVfsService).mock.calls[0][0]).toBe(tx);+ expect(vi.mocked(TopicDocumentModel).mock.calls[0][0]).toBe(tx);+ });- await archiveToolResultIfNeeded({+ it('reuses an existing archive with identical content instead of writing a new document', async () => {+ mockVfsService.stat.mockResolvedValue({+ documentId: 'document-existing',+ id: 'agent-doc-existing',+ type: 'file',+ });++ const result = await archive({ toolCallId: 'call_2', topicId: 'topic-2' });++ expect(mockVfsService.write).not.toHaveBeenCalled();+ expect(mockVfsService.read).toHaveBeenCalledWith(ARCHIVE_PATH, {agentId: 'agent-1',- content: '0123456789',- limit: 5,- serverDB: db,- toolCallId: 'call_1',+ topicId: 'topic-2',+ });+ expect(mockTopicDocumentModel.associate).toHaveBeenCalledWith({+ documentId: 'document-existing',+ topicId: 'topic-2',+ });+ expect(result.archived).toBe(true);+ expect(result.archivePath).toBe(ARCHIVE_PATH);+ expect(result.content).toContain('agent-doc-existing');+ });++ it('falls back to a per-call path when the hash path holds different content', async () => {+ mockVfsService.stat.mockResolvedValue({+ documentId: 'document-other',+ id: 'agent-doc-other',+ type: 'file',+ });+ mockVfsService.read+ .mockResolvedValueOnce({ content: 'something else' })+ .mockResolvedValueOnce({ content: CONTENT });++ const collisionPath = `./.tool-results/${CONTENT_HASH}_call_1.txt`;+ const result = await archive();++ expect(mockVfsService.write).toHaveBeenCalledWith(+ collisionPath,+ CONTENT,+ { agentId: 'agent-1', topicId: 'topic-1' },+ { contentFormat: 'raw' },+ );+ expect(mockTopicDocumentModel.associate).toHaveBeenCalledWith({+ documentId: 'document-1',topicId: 'topic-1',- userId: 'user-1',});+ expect(result.archived).toBe(true);+ expect(result.archivePath).toBe(collisionPath);+ });++ it('does not duplicate topic association when the archive document is already associated', async () => {+ mockTopicDocumentModel.isAssociated.mockResolvedValue(true);++ await archive();expect(mockTopicDocumentModel.associate).not.toHaveBeenCalled();});@@ -118,15 +186,7 @@ describe('archiveToolResultIfNeeded', () => {it('fails closed when the persisted archive content does not match the tool result', async () => {mockVfsService.read.mockResolvedValue({ content: 'corrupted' });- const result = await archiveToolResultIfNeeded({- agentId: 'agent-1',- content: '0123456789',- limit: 5,- serverDB: db,- toolCallId: 'call_1',- topicId: 'topic-1',- userId: 'user-1',- });+ const result = await archive();expect(result.archived).toBe(false);expect(result.error).toBe('Archived content verification failed');@@ -135,14 +195,7 @@ describe('archiveToolResultIfNeeded', () => {});it('falls back to truncation without archive context', async () => {- const result = await archiveToolResultIfNeeded({- agentId: 'agent-1',- content: '0123456789',- limit: 5,- toolCallId: 'call_1',- topicId: 'topic-1',- userId: 'user-1',- });+ const result = await archive({ serverDB: undefined });expect(result.archived).toBe(false);expect(result.archivePath).toBeUndefined();@@ -153,16 +206,7 @@ describe('archiveToolResultIfNeeded', () => {});it('bypasses archive entirely for lobe-agent-documents tool results', async () => {- const result = await archiveToolResultIfNeeded({- agentId: 'agent-1',- content: 'x'.repeat(1000),- identifier: 'lobe-agent-documents',- limit: 5,- serverDB: db,- toolCallId: 'call_1',- topicId: 'topic-1',- userId: 'user-1',- });+ const result = await archive({ content: 'x'.repeat(1000), identifier: 'lobe-agent-documents' });expect(result.archived).toBe(false);expect(result.content).toBe('x'.repeat(1000));@@ -172,18 +216,11 @@ describe('archiveToolResultIfNeeded', () => {it('keeps the tool result bounded when archive writing fails', async () => {mockVfsService.write.mockRejectedValue(new Error('write denied'));- const result = await archiveToolResultIfNeeded({- agentId: 'agent-1',- content: '0123456789',- limit: 5,- serverDB: db,- toolCallId: 'call_1',- topicId: 'topic-1',- userId: 'user-1',- });+ const result = await archive();expect(result.archived).toBe(false);expect(result.error).toBe('write denied');+ expect(result.archivePath).toBe(ARCHIVE_PATH);expect(result.content).toContain('01234');expect(result.content).toContain('Archive failed: write denied');});diff --git a/apps/server/src/services/toolExecution/archiveToolResult.ts b/apps/server/src/services/toolExecution/archiveToolResult.tsindex 614d09e5cc4..000a9990189 100644--- a/apps/server/src/services/toolExecution/archiveToolResult.ts+++ b/apps/server/src/services/toolExecution/archiveToolResult.ts@@ -1,4 +1,8 @@+import { createHash } from 'node:crypto';+import type { LobeChatDatabase } from '@lobechat/database';+import debug from 'debug';+import { sql } from 'drizzle-orm';import { TopicDocumentModel } from '@/database/models/topicDocument';import { AgentDocumentVfsService } from '@/server/services/agentDocumentVfs';@@ -10,9 +14,18 @@ import {import { TOOL_RESULTS_DIR_NAME } from './constants';+const log = debug('lobe-server:tool-result-archive');+const TOOL_RESULTS_DIR = `./${TOOL_RESULTS_DIR_NAME}`;const ARCHIVE_VERIFICATION_ERROR = 'Archived content verification failed';+/**+ * Length of the content-hash prefix used as the archive filename. 32 hex chars+ * (128 bits of sha256) is far beyond any realistic collision budget for one+ * agent's archive, while keeping the path the model sees short.+ */+const ARCHIVE_HASH_LENGTH = 32;+export interface ToolResultArchiveOutcome {archived: boolean;archivePath?: string;@@ -32,12 +45,52 @@ interface ArchiveToolResultParams {workspaceId?: string;}-const buildArchivePath = (topicId: string, toolCallId: string) =>- `${TOOL_RESULTS_DIR}/${topicId}_${toolCallId}.txt`;+interface ArchiveHandle {+ agentDocumentId?: string;+ archivePath: string;+ documentId?: string;+ outcome: 'created' | 'reused' | 'collision';+}++/**+ * Archives are keyed by content hash rather than by `{topicId}_{toolCallId}`.+ * The same oversized tool result (typically a knowledge-base file read) recurs+ * across many topics of one agent; keying by content lets every topic bind to+ * one `documents` row instead of persisting a byte-identical copy per call.+ *+ * Trade-off: one archive row is now shared by every topic (and, in a+ * workspace, every member) that produced the same content, so trashing it+ * from one topic also breaks the `Agent Document ID` pointer persisted in the+ * other topics' tool messages. Archives are hidden from user-facing lists+ * (`excludeArchivedToolResults`), so that path is not reachable from the UI.+ */+const buildArchivePath = (contentHash: string) => `${TOOL_RESULTS_DIR}/${contentHash}.txt`;++/**+ * Fallback path when the hash-named archive already exists but holds different+ * content (hash-prefix collision or a corrupted row). Never reuse such a row.+ */+const buildCollisionArchivePath = (contentHash: string, toolCallId: string) =>+ `${TOOL_RESULTS_DIR}/${contentHash}_${toolCallId}.txt`;++const hashArchiveContent = (content: string) =>+ createHash('sha256').update(content).digest('hex').slice(0, ARCHIVE_HASH_LENGTH);const getErrorMessage = (error: unknown) =>error instanceof Error ? error.message : String(error || 'Unknown archive error');+const buildArchivedContent = (+ truncatedContent: string,+ archivePath: string,+ agentDocumentId?: string,+) => {+ const agentDocumentIdHint =+ agentDocumentId ??+ '(call lobe-agent-documents.listDocuments with scope=currentTopic to look up)';++ return `${truncatedContent}\nFull content archived to the agent-document VFS.\nPath: ${archivePath}\nAgent Document ID: ${agentDocumentIdHint}\nTo inspect specific sections, call the lobe-agent-documents tool with apiName=readDocument and id=<Agent Document ID above>. Do NOT activate cloud-sandbox or local-system file tools β this archive exists only inside the agent document tree.`;+};+export const archiveToolResultIfNeeded = async ({agentId,content,@@ -65,40 +118,100 @@ export const archiveToolResultIfNeeded = async ({return { archived: false, content: truncatedContent };}- const archivePath = buildArchivePath(topicId, toolCallId);+ const contentHash = hashArchiveContent(content);+ const archivePath = buildArchivePath(contentHash);try {- const vfsService = new AgentDocumentVfsService(serverDB, userId, workspaceId);- await vfsService.mkdir(TOOL_RESULTS_DIR, { agentId, topicId }, { recursive: true });- const stats = await vfsService.write(- archivePath,- content,- { agentId, topicId },- { contentFormat: 'raw' },- );- const persisted = await vfsService.read(archivePath, { agentId, topicId });-- // Never tell the model that a full result exists unless the VFS can return it losslessly.- if (persisted.content !== content) throw new Error(ARCHIVE_VERIFICATION_ERROR);-- if (stats.documentId) {- const topicDocumentModel = new TopicDocumentModel(serverDB, userId, workspaceId);- const associated = await topicDocumentModel.isAssociated(stats.documentId, topicId);- if (!associated) {- await topicDocumentModel.associate({+ const handle = await serverDB.transaction(async (tx) => {+ // `mkdir` and the hash lookup below are both read-then-write. Two tool+ // calls of one agent archiving at the same moment used to create two+ // `.tool-results` root folders (or two rows for the same content), and a+ // unique index cannot express "unique per agent" on `documents`, so+ // serialize archive writes per agent instead. `hashtext` returns int4+ // while `pg_advisory_xact_lock` takes bigint, so cast. Under READ+ // COMMITTED the lookups take a fresh snapshot once the lock is granted,+ // so they see whatever the previous holder committed.+ await tx.execute(+ sql`SELECT pg_advisory_xact_lock(hashtext(${`toolResultArchive:${agentId}`})::bigint)`,+ );++ const vfsService = new AgentDocumentVfsService(+ tx as unknown as LobeChatDatabase,+ userId,+ workspaceId,+ );+ const ctx = { agentId, topicId };++ await vfsService.mkdir(TOOL_RESULTS_DIR, ctx, { recursive: true });++ const persistArchive = async (+ path: string,+ outcome: ArchiveHandle['outcome'],+ ): Promise<ArchiveHandle> => {+ const stats = await vfsService.write(path, content, ctx, { contentFormat: 'raw' });+ const persisted = await vfsService.read(path, ctx);++ // Never tell the model that a full result exists unless the VFS can return it losslessly.+ if (persisted.content !== content) throw new Error(ARCHIVE_VERIFICATION_ERROR);++ return {+ agentDocumentId: stats.id,+ archivePath: path,documentId: stats.documentId,- topicId,- });+ outcome,+ };+ };++ const resolveArchive = async (): Promise<ArchiveHandle> => {+ const existing = await vfsService.stat(archivePath, ctx);++ if (!existing || existing.type !== 'file') return persistArchive(archivePath, 'created');++ const persisted = await vfsService.read(archivePath, ctx);++ if (persisted.content === content) {+ return {+ agentDocumentId: existing.id,+ archivePath,+ documentId: existing.documentId,+ outcome: 'reused',+ };+ }++ return persistArchive(buildCollisionArchivePath(contentHash, toolCallId), 'collision');+ };++ const resolved = await resolveArchive();++ // The reuse / collision counters are what tell us whether the dedup is+ // doing its job in production; keep them greppable.+ log(+ 'archive %s agent=%s topic=%s path=%s',+ resolved.outcome,+ agentId,+ topicId,+ resolved.archivePath,+ );++ if (resolved.documentId) {+ const topicDocumentModel = new TopicDocumentModel(+ tx as unknown as LobeChatDatabase,+ userId,+ workspaceId,+ );+ const associated = await topicDocumentModel.isAssociated(resolved.documentId, topicId);+ if (!associated) {+ await topicDocumentModel.associate({ documentId: resolved.documentId, topicId });+ }}- }- const agentDocumentIdHint =- stats.id ?? '(call lobe-agent-documents.listDocuments with scope=currentTopic to look up)';+ return resolved;+ });return {- archivePath,+ archivePath: handle.archivePath,archived: true,- content: `${truncatedContent}\nFull content archived to the agent-document VFS.\nPath: ${archivePath}\nAgent Document ID: ${agentDocumentIdHint}\nTo inspect specific sections, call the lobe-agent-documents tool with apiName=readDocument and id=<Agent Document ID above>. Do NOT activate cloud-sandbox or local-system file tools β this archive exists only inside the agent document tree.`,+ content: buildArchivedContent(truncatedContent, handle.archivePath, handle.agentDocumentId),};} catch (error) {const message = getErrorMessage(error);diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.tsindex d5a05214494..f27a96d8cf1 100644--- a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts@@ -25,6 +25,7 @@ import type {ViewKnowledgeBaseArgs,ViewKnowledgeBaseState,} from '../types';+import { sliceReadWindow } from './readWindow';interface FileContentResult {content: string;@@ -320,23 +321,60 @@ export class KnowledgeBaseExecutionRuntime {options?: { signal?: AbortSignal },): Promise<BuiltinServerRuntimeOutput> {try {- const { fileIds } = args;+ const { fileIds, limit, offset } = args;if (!fileIds || fileIds.length === 0) {return { content: 'Error: No file IDs provided', success: false };}const fileContents = await this.ragService.getFileContents(fileIds, options?.signal);- const formattedContent = promptFileContents(fileContents);++ // Return one bounded window per file rather than the whole document: a+ // whole-file read is the single largest context item in KB conversations+ // and is what pushes tool results past the archive threshold.+ const windows = fileContents.map((file) => {+ if (file.error) return { file, window: undefined };+ return { file, window: sliceReadWindow(file.content, { limit, offset }) };+ });++ const formattedContent = promptFileContents(+ windows.map(({ file, window }) =>+ window+ ? {+ content: window.content,+ fileId: file.fileId,+ filename: file.filename,+ range: {+ cutLine: window.cutLine,+ endLine: window.endLine,+ startLine: window.startLine,+ totalCharCount: window.totalCharCount,+ totalLineCount: window.totalLineCount,+ truncated: window.truncated,+ },+ }+ : {+ content: file.content,+ error: file.error,+ fileId: file.fileId,+ filename: file.filename,+ },+ ),+ );const state: ReadKnowledgeState = {- files: fileContents.map((file) => ({+ files: windows.map(({ file, window }) => ({+ endLine: window?.endLine,error: file.error,fileId: file.fileId,filename: file.filename,- preview: file.preview,- totalCharCount: file.totalCharCount,- totalLineCount: file.totalLineCount,+ // Preview what this window actually returned, so a paged read shows+ // its own first lines on the card instead of the file head.+ preview: window ? window.content.split('\n').slice(0, 5).join('\n') : file.preview,+ startLine: window?.startLine,+ totalCharCount: file.totalCharCount ?? window?.totalCharCount,+ totalLineCount: file.totalLineCount ?? window?.totalLineCount,+ truncated: window?.truncated,})),};diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readKnowledge.test.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readKnowledge.test.tsnew file mode 100644index 00000000000..9814350bb0d--- /dev/null+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readKnowledge.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it, vi } from 'vitest';++import { KnowledgeBaseExecutionRuntime } from './index';++const buildLines = (tag: string, count: number) =>+ Array.from({ length: count }, (_, i) => `${tag} ${i + 1}`).join('\n');++const createRuntime = (files: Record<string, { content: string; error?: string }>) => {+ const ragService = {+ getFileContents: vi.fn(async (ids: string[]) =>+ ids.map((id) => {+ const file = files[id];+ const lines = file.content.split('\n');+ return {+ content: file.content,+ error: file.error,+ fileId: id,+ filename: `${id}.md`,+ preview: lines.slice(0, 5).join('\n'),+ totalCharCount: file.content.length,+ totalLineCount: lines.length,+ };+ }),+ ),+ semanticSearchForChat: vi.fn(),+ };++ return { ragService, runtime: new KnowledgeBaseExecutionRuntime(ragService) };+};++describe('KnowledgeBaseExecutionRuntime.readKnowledge', () => {+ it('returns a bounded window per file and reports the range in state', async () => {+ const { runtime } = createRuntime({+ big: { content: buildLines('L', 1000) },+ small: { content: 'only line' },+ });++ const result = await runtime.readKnowledge({ fileIds: ['big', 'small'] });++ expect(result.success).toBe(true);+ expect(result.content).toContain(+ '<file id="big" name="big.md" lines="1-400" totalLines="1000"',+ );+ expect(result.content).toContain('Call readKnowledge again with offset=401 to continue.');+ expect(result.content).toContain('<file id="small" name="small.md" lines="1-1" totalLines="1"');+ expect(result.content).not.toContain('L 401\n');++ const state = result.state as any;+ expect(state.files[0]).toMatchObject({+ endLine: 400,+ fileId: 'big',+ startLine: 1,+ totalCharCount: buildLines('L', 1000).length,+ totalLineCount: 1000,+ truncated: true,+ });+ expect(state.files[1]).toMatchObject({ endLine: 1, startLine: 1, truncated: false });+ });++ it('passes offset and limit through and previews the returned window', async () => {+ const { runtime } = createRuntime({ big: { content: buildLines('L', 1000) } });++ const result = await runtime.readKnowledge({ fileIds: ['big'], limit: 3, offset: 401 });++ expect(result.content).toContain('lines="401-403"');+ expect(result.content).toContain('offset=404 to continue');+ const state = result.state as any;+ expect(state.files[0].preview).toBe('L 401\nL 402\nL 403');+ expect(state.files[0]).toMatchObject({ endLine: 403, startLine: 401, truncated: true });+ });++ it('keeps error files as errors without a window', async () => {+ const { runtime } = createRuntime({+ missing: { content: '', error: 'Document not found' },+ });++ const result = await runtime.readKnowledge({ fileIds: ['missing'] });++ expect(result.content).toContain('error="Document not found"');+ const state = result.state as any;+ expect(state.files[0]).toMatchObject({ error: 'Document not found', fileId: 'missing' });+ expect(state.files[0].startLine).toBeUndefined();+ expect(state.files[0].truncated).toBeUndefined();+ });++ it('rejects an empty fileIds list', async () => {+ const { ragService, runtime } = createRuntime({});++ const result = await runtime.readKnowledge({ fileIds: [] });++ expect(result.success).toBe(false);+ expect(ragService.getFileContents).not.toHaveBeenCalled();+ });+});diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.test.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.test.tsnew file mode 100644index 00000000000..f5cd673d17d--- /dev/null+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.test.ts@@ -0,0 +1,126 @@+import { describe, expect, it } from 'vitest';++import {+ DEFAULT_READ_KNOWLEDGE_LINE_LIMIT,+ MAX_READ_KNOWLEDGE_CHARS_PER_FILE,+ MAX_READ_KNOWLEDGE_LINE_LIMIT,+ sliceReadWindow,+} from './readWindow';++const buildLines = (count: number, width = 5) =>+ Array.from({ length: count }, (_, i) => `${i + 1}`.padStart(width, 'L')).join('\n');++describe('sliceReadWindow', () => {+ it('returns the whole file when it fits in the default window', () => {+ const content = 'a\nb\nc';+ const window = sliceReadWindow(content);++ expect(window).toEqual({+ content,+ endLine: 3,+ startLine: 1,+ totalCharCount: 5,+ totalLineCount: 3,+ truncated: false,+ });+ });++ it('caps at the default line limit and flags truncation', () => {+ const content = buildLines(DEFAULT_READ_KNOWLEDGE_LINE_LIMIT + 10);+ const window = sliceReadWindow(content);++ expect(window.startLine).toBe(1);+ expect(window.endLine).toBe(DEFAULT_READ_KNOWLEDGE_LINE_LIMIT);+ expect(window.truncated).toBe(true);+ expect(window.content.split('\n')).toHaveLength(DEFAULT_READ_KNOWLEDGE_LINE_LIMIT);+ });++ it('pages from a 1-based offset with an explicit limit', () => {+ const content = buildLines(10);+ const window = sliceReadWindow(content, { limit: 3, offset: 4 });++ expect(window.content).toBe('LLLL4\nLLLL5\nLLLL6');+ expect(window.startLine).toBe(4);+ expect(window.endLine).toBe(6);+ expect(window.truncated).toBe(true);++ const tail = sliceReadWindow(content, { limit: 3, offset: 10 });+ expect(tail.content).toBe('LLL10');+ expect(tail.endLine).toBe(10);+ expect(tail.truncated).toBe(false);+ });++ it('returns an empty window when offset is past the end', () => {+ const window = sliceReadWindow('a\nb', { offset: 5 });++ expect(window.content).toBe('');+ expect(window.startLine).toBe(5);+ expect(window.endLine).toBe(0);+ expect(window.truncated).toBe(false);+ expect(window.totalLineCount).toBe(2);+ });++ it('stops before exceeding the per-file character cap', () => {+ // 3 lines of 4,000 chars: the cap of 10,000 admits two of them.+ const content = ['x'.repeat(4000), 'y'.repeat(4000), 'z'.repeat(4000)].join('\n');+ const window = sliceReadWindow(content);++ expect(window.content.length).toBeLessThanOrEqual(MAX_READ_KNOWLEDGE_CHARS_PER_FILE);+ expect(window.endLine).toBe(2);+ expect(window.truncated).toBe(true);++ const rest = sliceReadWindow(content, { offset: window.endLine + 1 });+ expect(rest.content).toBe('z'.repeat(4000));+ expect(rest.truncated).toBe(false);+ });++ it('cuts a single line that alone exceeds the char cap and still advances', () => {+ const content = ['a'.repeat(30_000), 'b'].join('\n');+ const window = sliceReadWindow(content);++ expect(window.content).toBe('a'.repeat(MAX_READ_KNOWLEDGE_CHARS_PER_FILE));+ expect(window.content.length).toBe(MAX_READ_KNOWLEDGE_CHARS_PER_FILE);+ expect(window.endLine).toBe(1);+ expect(window.truncated).toBe(true);+ expect(window.cutLine).toEqual({+ keptChars: MAX_READ_KNOWLEDGE_CHARS_PER_FILE,+ line: 1,+ totalChars: 30_000,+ });++ const rest = sliceReadWindow(content, { offset: window.endLine + 1 });+ expect(rest.content).toBe('b');+ expect(rest.cutLine).toBeUndefined();+ expect(rest.truncated).toBe(false);+ });++ it('flags a cut even when the oversized line is the last line', () => {+ const window = sliceReadWindow('x'.repeat(20_000));++ expect(window.content.length).toBe(MAX_READ_KNOWLEDGE_CHARS_PER_FILE);+ expect(window.truncated).toBe(true);+ expect(window.cutLine?.totalChars).toBe(20_000);+ });++ it('coerces numeric strings so a string offset does not restart from line 1', () => {+ const content = buildLines(10);+ const window = sliceReadWindow(content, { limit: '2', offset: '4' });++ expect(window.startLine).toBe(4);+ expect(window.endLine).toBe(5);+ expect(sliceReadWindow(content, { offset: 'abc' }).startLine).toBe(1);+ });++ it('clamps out-of-range arguments instead of throwing', () => {+ const content = buildLines(5);++ expect(sliceReadWindow(content, { limit: 0, offset: 0 }).content).toBe('LLLL1');+ expect(sliceReadWindow(content, { limit: Number.NaN, offset: -3 }).endLine).toBe(5);+ expect(+ sliceReadWindow(buildLines(MAX_READ_KNOWLEDGE_LINE_LIMIT + 5), {+ limit: 999_999,+ maxChars: Number.MAX_SAFE_INTEGER,+ }).endLine,+ ).toBe(MAX_READ_KNOWLEDGE_LINE_LIMIT);+ });+});diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.tsnew file mode 100644index 00000000000..2daefb152ae--- /dev/null+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/readWindow.ts@@ -0,0 +1,129 @@+/**+ * Bounded, pageable window over a knowledge file for `readKnowledge`.+ *+ * A single knowledge-base file routinely runs to 30β40k characters. Returning+ * it whole made one `readKnowledge` call the largest item in the model context+ * and pushed every such result past the tool-result archive threshold, which+ * then persisted a byte-identical copy per topic. The tool now returns one+ * window per call and tells the model how to continue.+ */++/** Default number of lines returned per file when the model passes no `limit`. */+export const DEFAULT_READ_KNOWLEDGE_LINE_LIMIT = 400;++/** Upper bound on `limit`, so a model cannot opt back into whole-file reads. */+export const MAX_READ_KNOWLEDGE_LINE_LIMIT = 2000;++/**+ * Hard cap on characters returned per file per call, applied on top of the+ * line limit. Two files at this cap stay under the 25k tool-result archive+ * threshold, so an ordinary two-file read no longer archives anything.+ */+export const MAX_READ_KNOWLEDGE_CHARS_PER_FILE = 10_000;++export interface ReadWindowOptions {+ /** Maximum number of lines to return; defaults to {@link DEFAULT_READ_KNOWLEDGE_LINE_LIMIT}. */+ limit?: number | string;+ /** Maximum characters to return; defaults to {@link MAX_READ_KNOWLEDGE_CHARS_PER_FILE}. */+ maxChars?: number;+ /** 1-based line number to start from; defaults to 1. */+ offset?: number | string;+}++export interface ReadWindow {+ content: string;+ /**+ * Set when the first line of the window alone exceeded `maxChars` and was cut+ * to fit. The window then holds only that partial line; the tail is not+ * reachable through `offset` (which is line-based), so callers should tell+ * the model the line was cut.+ */+ cutLine?: { line: number; keptChars: number; totalChars: number };+ /** 1-based, inclusive. `0` when the window is empty. */+ endLine: number;+ /** 1-based, inclusive. */+ startLine: number;+ totalCharCount: number;+ totalLineCount: number;+ /** True when lines after `endLine` were left out and the model should page. */+ truncated: boolean;+}++const clampInteger = (+ value: number | string | undefined,+ fallback: number,+ min: number,+ max: number,+) => {+ // Some providers emit numeric arguments as strings (`"offset": "401"`);+ // treating those as absent would silently restart from line 1 and loop.+ const parsed = typeof value === 'string' ? Number(value) : value;+ if (parsed === undefined || !Number.isFinite(parsed)) return fallback;+ return Math.min(max, Math.max(min, Math.floor(parsed)));+};++export const sliceReadWindow = (content: string, options: ReadWindowOptions = {}): ReadWindow => {+ const lines = content.split('\n');+ const totalLineCount = lines.length;+ const totalCharCount = content.length;++ const limit = clampInteger(+ options.limit,+ DEFAULT_READ_KNOWLEDGE_LINE_LIMIT,+ 1,+ MAX_READ_KNOWLEDGE_LINE_LIMIT,+ );+ const maxChars = clampInteger(+ options.maxChars,+ MAX_READ_KNOWLEDGE_CHARS_PER_FILE,+ 1,+ Number.MAX_SAFE_INTEGER,+ );+ const startLine = clampInteger(options.offset, 1, 1, Number.MAX_SAFE_INTEGER);++ if (startLine > totalLineCount) {+ return {+ content: '',+ endLine: 0,+ startLine,+ totalCharCount,+ totalLineCount,+ truncated: false,+ };+ }++ const selected: string[] = [];+ let charCount = 0;+ let cutLine: ReadWindow['cutLine'];++ for (let index = startLine - 1; index < totalLineCount && selected.length < limit; index++) {+ const line = lines[index];++ // A single line longer than the cap (minified JSON, generated text) would+ // otherwise defeat the bound entirely. Cut it and still advance one line so+ // paging cannot stall; the caller surfaces the cut to the model.+ if (selected.length === 0 && line.length > maxChars) {+ selected.push(line.slice(0, maxChars));+ cutLine = { keptChars: maxChars, line: index + 1, totalChars: line.length };+ break;+ }++ const nextCount = charCount + line.length + (selected.length > 0 ? 1 : 0);+ if (selected.length > 0 && nextCount > maxChars) break;++ selected.push(line);+ charCount = nextCount;+ }++ const endLine = startLine + selected.length - 1;++ return {+ content: selected.join('\n'),+ cutLine,+ endLine,+ startLine,+ totalCharCount,+ totalLineCount,+ truncated: endLine < totalLineCount || cutLine !== undefined,+ };+};diff --git a/packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/FileCard.tsx b/packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/FileCard.tsxindex 0a758d67888..9f4cd4d13be 100644--- a/packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/FileCard.tsx+++ b/packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/FileCard.tsx@@ -123,7 +123,10 @@ const FileCard = memo<FileCardProps>(({ file }) => {label: 'Chars',},{- children: file.totalLineCount?.toLocaleString(),+ children:+ file.startLine && file.endLine && (file.truncated || file.startLine > 1)+ ? `${file.startLine.toLocaleString()}-${file.endLine.toLocaleString()} / ${file.totalLineCount?.toLocaleString()}`+ : file.totalLineCount?.toLocaleString(),label: 'Lines',},]}diff --git a/packages/builtin-tool-knowledge-base/src/manifest.ts b/packages/builtin-tool-knowledge-base/src/manifest.tsindex ff2cd9fcd9c..b10a05acb98 100644--- a/packages/builtin-tool-knowledge-base/src/manifest.ts+++ b/packages/builtin-tool-knowledge-base/src/manifest.ts@@ -121,7 +121,7 @@ export const KnowledgeBaseManifest: BuiltinToolManifest = {},{description:- 'Read the full content of specific resources from the knowledge base. Accepts both file IDs (file_*) for uploaded files and document IDs (docs_*) for inline documents created via createDocument. Use this after searchKnowledgeBase or viewKnowledgeBase to get complete content. You can read multiple resources at once.',+ 'Read the content of specific resources from the knowledge base, one bounded window per file. Accepts both file IDs (file_*) for uploaded files and document IDs (docs_*) for inline documents created via createDocument. Use this after searchKnowledgeBase or viewKnowledgeBase. Each call returns at most `limit` lines (default 400) and about 10,000 characters per file; when the result says truncated="true", call again with the suggested offset to continue. Prefer searchKnowledgeBase to locate the relevant part first, and do not re-read a file you have already read in this conversation.',name: KnowledgeBaseApiName.readKnowledge,parameters: {properties: {@@ -133,6 +133,19 @@ export const KnowledgeBaseManifest: BuiltinToolManifest = {},type: 'array',},+ limit: {+ description:+ 'Maximum number of lines to return per file (default 400, max 2000). Applies to every file in fileIds. Output is additionally capped at about 10,000 characters per file.',+ maximum: 2000,+ minimum: 1,+ type: 'number',+ },+ offset: {+ description:+ '1-based line number to start reading from (default 1). Applies to every file in fileIds, so page one file per call when their suggested offsets differ. Use the offset suggested in a previous truncated result to read the next window.',+ minimum: 1,+ type: 'number',+ },},required: ['fileIds'],type: 'object',diff --git a/packages/builtin-tool-knowledge-base/src/systemRole.ts b/packages/builtin-tool-knowledge-base/src/systemRole.tsindex a8749a37df3..4d29592670c 100644--- a/packages/builtin-tool-knowledge-base/src/systemRole.ts+++ b/packages/builtin-tool-knowledge-base/src/systemRole.ts@@ -19,7 +19,7 @@ When a user uploads files (images, PDFs, documents, etc.), they go into the reso3. List all knowledge bases (listKnowledgeBases)4. View a knowledge base's details and files (viewKnowledgeBase)5. Semantic vector search across knowledge bases (searchKnowledgeBase)-6. Read full file content (readKnowledge)+6. Read file content in bounded, pageable windows (readKnowledge)**Knowledge Base Management:**7. Create a new knowledge base (createKnowledgeBase)@@ -40,7 +40,7 @@ When a user uploads files (images, PDFs, documents, etc.), they go into the reso1. Use listKnowledgeBases to see what's available2. Use viewKnowledgeBase to browse a specific knowledge base's contents3. Use searchKnowledgeBase to find relevant files via semantic search-4. Use readKnowledge to get full content from the most relevant files+4. Use readKnowledge to read the relevant files (page with offset when a result is truncated)5. Synthesize and cite sources**For knowledge base management:**@@ -62,7 +62,7 @@ When a user uploads files (images, PDFs, documents, etc.), they go into the reso- \`<files>\` β uploaded files matched by semantic vector search at chunk-level (file_* IDs). Resolve pronouns to concrete entities (BAD: "What does it do?" β GOOD: "What does the authentication system do?").- \`<documents>\` β inline notes/documents (created via createDocument) matched by full-text BM25 search at document-level (docs_* IDs). Works well with literal keyword queries.- Adjust topK (5-100, default: 15) per result type.-- **readKnowledge**: Read complete content by ID. Accepts both file IDs (file_*) for uploaded files and document IDs (docs_*) for inline documents. Use the IDs returned by searchKnowledgeBase or viewKnowledgeBase.+- **readKnowledge**: Read content by ID in bounded windows. Accepts both file IDs (file_*) for uploaded files and document IDs (docs_*) for inline documents. Use the IDs returned by searchKnowledgeBase or viewKnowledgeBase. Each call returns up to \`limit\` lines (default 400, ~10k characters) per file; when a result is marked truncated, continue with the suggested \`offset\` instead of re-reading from the start. Read a file once per conversation and reuse what you already have.**Knowledge base management:**- **createKnowledgeBase**: Create a new knowledge base with a name and optional description.diff --git a/packages/builtin-tool-knowledge-base/src/types.ts b/packages/builtin-tool-knowledge-base/src/types.tsindex 427c0fe359b..e18e008f131 100644--- a/packages/builtin-tool-knowledge-base/src/types.ts+++ b/packages/builtin-tool-knowledge-base/src/types.ts@@ -49,15 +49,25 @@ export interface SearchKnowledgeBaseState {export interface ReadKnowledgeArgs {fileIds: string[];+ /** Maximum number of lines to return per file (default 400, max 2000). Some providers send numbers as strings. */+ limit?: number | string;+ /** 1-based line number to start reading from (default 1). Some providers send numbers as strings. */+ offset?: number | string;}export interface FileContentDetail {+ /** 1-based inclusive end line of the returned window; `0` when empty. */+ endLine?: number;error?: string;fileId: string;filename: string;preview?: string;+ /** 1-based inclusive start line of the returned window. */+ startLine?: number;totalCharCount?: number;totalLineCount?: number;+ /** True when more lines follow `endLine` and another call with a higher `offset` is needed. */+ truncated?: boolean;}export interface ReadKnowledgeState {diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snap b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snapindex 151c5c163f6..076191901df 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snap+++ b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatFileContents.test.ts.snap@@ -73,3 +73,17 @@ Another successfully loaded file with more content.</file></knowledge_base_files>"`;++exports[`promptFileContents > should render a paged window with range attributes and a continue notice 1`] = `+"<knowledge_base_files totalCount="2">+<instruction>Use the information from these files to answer the user's question. Always cite the source files.</instruction>+<file id="file-paged" name="long.md" lines="1-2" totalLines="800" totalChars="30334" truncated="true">+line 1+line 2+[Showing lines 1-2 of 800. Call readKnowledge again with offset=3 to continue.]+</file>+<file id="file-complete" name="short.md" lines="1-1" totalLines="1" totalChars="9" truncated="false">+tail line+</file>+</knowledge_base_files>"+`;diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snap b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snapindex 88ec020992b..0d52171bdaf 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snap+++ b/packages/prompts/src/prompts/knowledgeBaseQA/__snapshots__/formatSearchResults.test.ts.snap@@ -10,7 +10,7 @@ Note: full-text document search unavailable (paradedb extension unavailable); onexports[`formatSearchResults > should annotate when BM25 fails but vector succeeds 1`] = `"<knowledge_base_search_results query="test query" totalCount="1">-<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.Note: full-text document search unavailable (paradedb extension unavailable); only file chunk results returned.</instruction><files totalCount="1"><file id="file_only" name="Sole Result.pdf" relevanceScore="0.8">@@ -22,7 +22,7 @@ Note: full-text document search unavailable (paradedb extension unavailable); onexports[`formatSearchResults > should annotate when vector search fails but BM25 succeeds 1`] = `"<knowledge_base_search_results query="test query" totalCount="1">-<instruction>Search results from the knowledge base. Source type: <documents> (full-text search, document-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.+<instruction>Search results from the knowledge base. Source type: <documents> (full-text search, document-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.Note: vector search unavailable (Invalid API key for embedding provider); only document results returned.</instruction><documents totalCount="1"><document id="docs_only" title="Fallback Note" relevance="1.1" knowledgeBaseId="kb_main">@@ -34,7 +34,7 @@ Note: vector search unavailable (Invalid API key for embedding provider); only dexports[`formatSearchResults > should format documents only (BM25 hits, no file chunks) 1`] = `"<knowledge_base_search_results query="machine learning" totalCount="1">-<instruction>Search results from the knowledge base. Source type: <documents> (full-text search, document-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>+<instruction>Search results from the knowledge base. Source type: <documents> (full-text search, document-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.</instruction><documents totalCount="1"><document id="docs_abc123" title="ML Notes" relevance="1.2" knowledgeBaseId="kb_main"><snippet>machine learning is a subset of artificial intelligence...</snippet>@@ -45,7 +45,7 @@ exports[`formatSearchResults > should format documents only (BM25 hits, no fileexports[`formatSearchResults > should format file with special characters in name 1`] = `"<knowledge_base_search_results query="password reset" totalCount="1">-<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.</instruction><files totalCount="1"><file id="special-123" name="FAQ: Common Questions & Answers (2024).md" relevanceScore="0.88"><chunk fileId="special-123" fileName="FAQ: Common Questions & Answers (2024).md" similarity="0.9">Q: How do I reset my password? A: Click on the "Forgot Password" link on the login page.</chunk>@@ -56,7 +56,7 @@ exports[`formatSearchResults > should format file with special characters in namexports[`formatSearchResults > should format long text chunks without truncation 1`] = `"<knowledge_base_search_results query="documentation details" totalCount="1">-<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.</instruction><files totalCount="1"><file id="long-doc" name="Detailed Documentation.md" relevanceScore="0.91"><chunk fileId="long-doc" fileName="Detailed Documentation.md" similarity="0.93">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</chunk>@@ -67,7 +67,7 @@ exports[`formatSearchResults > should format long text chunks without truncationexports[`formatSearchResults > should format mixed file chunks and documents 1`] = `"<knowledge_base_search_results query="neural networks" totalCount="2">-<instruction>Search results from the knowledge base. Two source types: <files> (vector search, chunk-level) and <documents> (full-text search, document-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>+<instruction>Search results from the knowledge base. Two source types: <files> (vector search, chunk-level) and <documents> (full-text search, document-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.</instruction><files totalCount="1"><file id="file_pdf1" name="AI Handbook.pdf" relevanceScore="0.91"><chunk fileId="file_pdf1" fileName="AI Handbook.pdf" similarity="0.94">Neural networks are computational models...</chunk>@@ -83,7 +83,7 @@ exports[`formatSearchResults > should format mixed file chunks and documents 1`]exports[`formatSearchResults > should format multiple files with varying relevance scores 1`] = `"<knowledge_base_search_results query="API authentication security" totalCount="3">-<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.</instruction><files totalCount="3"><file id="doc-001" name="API Reference.md" relevanceScore="0.95"><chunk fileId="doc-001" fileName="API Reference.md" similarity="0.98">The Authentication API provides endpoints for user login, logout, and token refresh. All endpoints require HTTPS and proper API keys.</chunk>@@ -102,7 +102,7 @@ exports[`formatSearchResults > should format multiple files with varying relevanexports[`formatSearchResults > should format query with special characters 1`] = `"<knowledge_base_search_results query="How to use fetchData<T> with async/await?" totalCount="1">-<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.</instruction><files totalCount="1"><file id="code-sample" name="Code Examples.md" relevanceScore="0.94"><chunk fileId="code-sample" fileName="Code Examples.md" similarity="0.96">Use the following TypeScript code: const result = await fetchData<T>({ url, params });</chunk>@@ -113,7 +113,7 @@ exports[`formatSearchResults > should format query with special characters 1`] =exports[`formatSearchResults > should format single file with multiple chunks 1`] = `"<knowledge_base_search_results query="how to install the application" totalCount="1">-<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.</instruction><files totalCount="1"><file id="file-123" name="Getting Started Guide.md" relevanceScore="0.92"><chunk fileId="file-123" fileName="Getting Started Guide.md" similarity="0.95">To get started with the application, first install all dependencies using npm install or yarn install. Make sure you have Node.js version 16 or higher installed on your system.</chunk>@@ -131,7 +131,7 @@ exports[`formatSearchResults > should handle empty file results 1`] = `exports[`formatSearchResults > should handle file with multiple high-similarity chunks 1`] = `"<knowledge_base_search_results query="project setup steps" totalCount="1">-<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.</instruction><files totalCount="1"><file id="comprehensive-guide" name="Complete Tutorial.md" relevanceScore="0.96"><chunk fileId="comprehensive-guide" fileName="Complete Tutorial.md" similarity="0.98">Step 1: Initialize the project with the configuration file.</chunk>@@ -145,7 +145,7 @@ exports[`formatSearchResults > should handle file with multiple high-similarityexports[`formatSearchResults > should handle files with low relevance scores 1`] = `"<knowledge_base_search_results query="specific technical query" totalCount="1">-<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.</instruction>+<instruction>Search results from the knowledge base. Source type: <files> (vector search, chunk-level). Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.</instruction><files totalCount="1"><file id="low-relevance" name="Tangentially Related.md" relevanceScore="0.32"><chunk fileId="low-relevance" fileName="Tangentially Related.md" similarity="0.35">This document contains some loosely related information that might be helpful.</chunk>diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.tsindex 0af9bb8b041..1334841d087 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.ts+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.test.ts@@ -115,4 +115,80 @@ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore euconst result = promptFileContents(fileContents);expect(result).toMatchSnapshot();});++ it('should explain an empty window whose offset is past the end of the file', () => {+ const result = promptFileContents([+ {+ content: '',+ fileId: 'file-eof',+ filename: 'short.md',+ range: {+ endLine: 0,+ startLine: 900,+ totalCharCount: 100,+ totalLineCount: 800,+ truncated: false,+ },+ },+ ]);++ expect(result).toContain('lines="900-0"');+ expect(result).toContain('offset 900 is past the end of this 800-line file');+ });++ it('should explain a line that was cut to fit the per-call cap', () => {+ const result = promptFileContents([+ {+ content: 'x'.repeat(10),+ fileId: 'file-cut',+ filename: 'minified.json',+ range: {+ cutLine: { keptChars: 10, line: 1, totalChars: 30_000 },+ endLine: 1,+ startLine: 1,+ totalCharCount: 30_002,+ totalLineCount: 2,+ truncated: true,+ },+ },+ ]);++ expect(result).toContain('Line 1 is 30000 characters long and was cut at 10');+ expect(result).toContain('offset=2 to continue with the next line');+ });++ it('should render a paged window with range attributes and a continue notice', () => {+ const fileContents: FileContent[] = [+ {+ content: 'line 1\nline 2',+ fileId: 'file-paged',+ filename: 'long.md',+ range: {+ endLine: 2,+ startLine: 1,+ totalCharCount: 30_334,+ totalLineCount: 800,+ truncated: true,+ },+ },+ {+ content: 'tail line',+ fileId: 'file-complete',+ filename: 'short.md',+ range: {+ endLine: 1,+ startLine: 1,+ totalCharCount: 9,+ totalLineCount: 1,+ truncated: false,+ },+ },+ ];++ const result = promptFileContents(fileContents);+ expect(result).toMatchSnapshot();+ expect(result).toContain('lines="1-2" totalLines="800" totalChars="30334" truncated="true"');+ expect(result).toContain('Call readKnowledge again with offset=3 to continue.');+ expect(result).not.toContain('offset=2 to continue');+ });});diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.tsindex 62955ad64eb..0fe7e6be388 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.ts+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatFileContents.ts@@ -1,10 +1,52 @@+/**+ * Line window a file's `content` was cut to. Present only when the caller+ * sliced the file (see `readKnowledge`), so callers that still pass whole+ * files render exactly as before.+ */+export interface FileContentRange {+ /** Present when the window's only line was cut to fit the per-call cap. */+ cutLine?: { keptChars: number; line: number; totalChars: number };+ /** 1-based, inclusive. `0` when the window is empty. */+ endLine: number;+ /** 1-based, inclusive. */+ startLine: number;+ totalCharCount: number;+ totalLineCount: number;+ /** True when lines after `endLine` exist and the model should page. */+ truncated: boolean;+}+export interface FileContent {content: string;error?: string;fileId: string;filename: string;+ range?: FileContentRange;}+const formatRangeAttributes = (range: FileContentRange): string =>+ ` lines="${range.startLine}-${range.endLine}" totalLines="${range.totalLineCount}" totalChars="${range.totalCharCount}" truncated="${range.truncated}"`;++const formatRangeNotice = (range: FileContentRange): string => {+ if (range.endLine === 0) {+ return `\n[offset ${range.startLine} is past the end of this ${range.totalLineCount}-line file; nothing returned. The file is not empty.]`;+ }++ if (range.cutLine) {+ const { keptChars, line, totalChars } = range.cutLine;+ const rest =+ line < range.totalLineCount+ ? ` Call readKnowledge again with offset=${line + 1} to continue with the next line.`+ : '';++ return `\n[Line ${line} is ${totalChars} characters long and was cut at ${keptChars}; the rest of that line cannot be paged.${rest}]`;+ }++ if (!range.truncated) return '';++ return `\n[Showing lines ${range.startLine}-${range.endLine} of ${range.totalLineCount}. Call readKnowledge again with offset=${range.endLine + 1} to continue.]`;+};+/*** Formats a single file content with XML tags*/@@ -13,8 +55,11 @@ const formatFileContent = (file: FileContent): string => {return `<file id="${file.fileId}" name="${file.filename}" error="${file.error}" />`;}- return `<file id="${file.fileId}" name="${file.filename}">-${file.content}+ const rangeAttributes = file.range ? formatRangeAttributes(file.range) : '';+ const rangeNotice = file.range ? formatRangeNotice(file.range) : '';++ return `<file id="${file.fileId}" name="${file.filename}"${rangeAttributes}>+${file.content}${rangeNotice}</file>`;};diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.tsindex f42c2bb57f9..fa6b0e30a56 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.ts+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatSearchResults.ts@@ -109,7 +109,7 @@ ${docsXml}: fileResults.length > 0? 'Source type: <files> (vector search, chunk-level). ': 'Source type: <documents> (full-text search, document-level). '- }Use the readKnowledge tool with the returned IDs (file_* or docs_*) to fetch complete content.${errorNote}`;+ }Use the readKnowledge tool with the returned IDs (file_* or docs_*) to read the relevant content; it returns bounded windows, so page with offset when a result is truncated.${errorNote}`;return `<knowledge_base_search_results query="${query}" totalCount="${totalCount}"><instruction>${instruction}</instruction>diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/index.ts b/packages/prompts/src/prompts/knowledgeBaseQA/index.tsindex d2bb54b55ba..390bd92c5c7 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/index.ts+++ b/packages/prompts/src/prompts/knowledgeBaseQA/index.ts@@ -4,7 +4,7 @@ import { chunkPrompts } from './chunk';import { knowledgePrompts } from './knowledge';import { userQueryPrompt } from './userQuery';-export type { FileContent } from './formatFileContents';+export type { FileContent, FileContentRange } from './formatFileContents';export { promptFileContents } from './formatFileContents';export { promptNoSearchResults } from './formatNoSearchResults';export type { FileSearchResult, FileSearchResultChunk } from './formatSearchResults';