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): page listDocuments instead of returning every document (#20070)

Arvin Xu7ef02739443a
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 e2cb398e374..52373afba59 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.test.ts
@@ -19,6 +19,57 @@ const createRuntime = (overrides = {}) =>
});
describe('AgentDocumentsExecutionRuntime', () => {
+ // An agent with thousands of web-crawled docs used to get every row in one
+ // result (1.5M chars), overflowing the context window on the next call.
+ describe('listDocuments paging', () => {
+ const docs = Array.from({ length: 120 }, (_, i) => ({
+ documentId: `doc-${i}`,
+ filename: `page-${i}.md`,
+ id: `agent-doc-${i}`,
+ title: `Page ${i}`,
+ }));
+
+ it('returns the first page and tells the model how to fetch the next', async () => {
+ const runtime = createRuntime({ listDocuments: vi.fn().mockResolvedValue(docs) });
+
+ const result = await runtime.listDocuments({}, { agentId: 'agent-1' });
+
+ expect(result.state?.documents).toHaveLength(50);
+ expect(result.content).toContain('"id":"agent-doc-49"');
+ expect(result.content).not.toContain('"id":"agent-doc-50"');
+ expect(result.content).toContain(
+ 'Showing documents 1-50 of 120. For the next page call listDocuments with {"limit":50,"offset":50,"scope":"agent","sourceType":"all"}.',
+ );
+ });
+
+ it('keeps the active filters in the next-page arguments', async () => {
+ const runtime = createRuntime({ listTopicDocuments: vi.fn().mockResolvedValue(docs) });
+
+ const result = await runtime.listDocuments(
+ { limit: 20, parentId: 'folder-1', scope: 'currentTopic', sourceType: 'web' },
+ { agentId: 'agent-1', topicId: 'topic-1' },
+ );
+
+ expect(result.content).toContain(
+ 'For the next page call listDocuments with {"limit":20,"offset":20,"parentId":"folder-1","scope":"currentTopic","sourceType":"web"}.',
+ );
+ });
+
+ it('pages with offset/limit and omits the note on the last page', async () => {
+ const runtime = createRuntime({ listDocuments: vi.fn().mockResolvedValue(docs) });
+
+ const result = await runtime.listDocuments(
+ { limit: 1000, offset: 100 },
+ { agentId: 'agent-1' },
+ );
+
+ expect(result.state?.documents.map((d: { id: string }) => d.id)).toEqual(
+ docs.slice(100).map((d) => d.id),
+ );
+ expect(result.content).not.toContain('Showing documents');
+ });
+ });
+
it('returns agentDocumentId and documentId when creating hinted documents', async () => {
const createDocument = vi.fn().mockResolvedValue({
documentId: 'backing-doc-1',
diff --git a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
index 49085817ab6..cfe109ced78 100644
--- a/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-agent-documents/src/ExecutionRuntime/index.ts
@@ -21,7 +21,17 @@ import type {
ReplaceDocumentContentArgs,
UpdateLoadRuleArgs,
} from '../types';
-import { MAX_READ_DOCUMENT_CONTENT_CHARS } from '../types';
+import {
+ LIST_DOCUMENTS_DEFAULT_LIMIT,
+ LIST_DOCUMENTS_MAX_LIMIT,
+ MAX_READ_DOCUMENT_CONTENT_CHARS,
+} from '../types';
+
+const clampListLimit = (limit: unknown): number => {
+ const value = Math.floor(Number(limit));
+ if (!Number.isFinite(value) || value <= 0) return LIST_DOCUMENTS_DEFAULT_LIMIT;
+ return Math.min(value, LIST_DOCUMENTS_MAX_LIMIT);
+};
interface AgentDocumentRecord {
content?: string;
@@ -331,8 +341,11 @@ export class AgentDocumentsExecutionRuntime {
topicId: topicId!,
})
: await this.service.listDocuments({ agentId, parentId, scope, sourceType });
+ const limit = clampListLimit(args.limit);
+ const offset = Math.max(0, Math.floor(Number(args.offset) || 0));
+ const page = docs.slice(offset, offset + limit);
const list = await Promise.all(
- docs.map(async (d) => {
+ page.map(async (d) => {
const url = await this.buildDocumentUrl(agentId, d.documentId);
return {
...(d.documentId ? { documentId: d.documentId } : {}),
@@ -346,8 +359,23 @@ export class AgentDocumentsExecutionRuntime {
}),
);
+ const nextOffset = offset + page.length;
+ // Page two must read the same filtered set, so the continuation repeats
+ // every active filter instead of just the offset.
+ const nextArgs = JSON.stringify({
+ limit,
+ offset: nextOffset,
+ ...(parentId ? { parentId } : {}),
+ scope,
+ sourceType,
+ });
+ const pagingNote =
+ nextOffset < docs.length
+ ? `\n\nShowing documents ${offset + 1}-${nextOffset} of ${docs.length}. For the next page call listDocuments with ${nextArgs}.`
+ : '';
+
return {
- content: JSON.stringify(list),
+ content: JSON.stringify(list) + pagingNote,
state: { documents: list },
success: true,
};
diff --git a/packages/builtin-tool-agent-documents/src/manifest.ts b/packages/builtin-tool-agent-documents/src/manifest.ts
index 786e518d3b4..12ad3933c0a 100644
--- a/packages/builtin-tool-agent-documents/src/manifest.ts
+++ b/packages/builtin-tool-agent-documents/src/manifest.ts
@@ -1,7 +1,12 @@
import type { BuiltinToolManifest } from '@lobechat/types';
import { systemPrompt } from './systemRole';
-import { AgentDocumentsApiName, AgentDocumentsIdentifier } from './types';
+import {
+ AgentDocumentsApiName,
+ AgentDocumentsIdentifier,
+ LIST_DOCUMENTS_DEFAULT_LIMIT,
+ LIST_DOCUMENTS_MAX_LIMIT,
+} from './types';
const AGENT_DOCUMENT_ID_DESCRIPTION =
'Target agent document ID. Use the "id" field returned by listDocuments, not "documentId".';
@@ -240,6 +245,15 @@ export const AgentDocumentsManifest: BuiltinToolManifest = {
name: AgentDocumentsApiName.listDocuments,
parameters: {
properties: {
+ limit: {
+ description: `Maximum number of documents to return (default ${LIST_DOCUMENTS_DEFAULT_LIMIT}, max ${LIST_DOCUMENTS_MAX_LIMIT}).`,
+ type: 'number',
+ },
+ offset: {
+ description:
+ 'Number of documents to skip. Use the offset given at the end of a truncated listing to fetch the next page.',
+ type: 'number',
+ },
parentId: {
description:
'Restrict the listing to the direct children of this folder. Pass the folder id shown on a collapsed πŸ“ row in the agent_documents_index to expand that folder.',
diff --git a/packages/builtin-tool-agent-documents/src/types.ts b/packages/builtin-tool-agent-documents/src/types.ts
index e03d0baf5be..2d0ceeeae7b 100644
--- a/packages/builtin-tool-agent-documents/src/types.ts
+++ b/packages/builtin-tool-agent-documents/src/types.ts
@@ -228,11 +228,22 @@ export interface ListDocumentsArgs {
* (the folder's `documentId`). The progressive index collapses folders and
* surfaces this id so the model can expand a folder on demand.
*/
+ /** Page size; defaults to {@link LIST_DOCUMENTS_DEFAULT_LIMIT}. */
+ limit?: number;
+ /** Number of documents to skip, for paging past the first page. */
+ offset?: number;
parentId?: string;
scope?: 'agent' | 'currentTopic';
sourceType?: 'all' | 'file' | 'web';
}
+/**
+ * An agent can own thousands of documents (mostly web-crawled pages); listing
+ * them all in one result blew past the model's context window.
+ */
+export const LIST_DOCUMENTS_DEFAULT_LIMIT = 50;
+export const LIST_DOCUMENTS_MAX_LIMIT = 200;
+
export interface ListDocumentsState {
/**
* How many rows `documents` held, pinned by the read-path projector before it